#!/bin/sh
echo "start run lua-ui"
package_path="/home/quant_group"

#历史遗留问题，抽空fix
replaceGitRemote

echo "cd ${package_path}"
cd ${package_path}

export NAMESPACE=`cat /var/run/secrets/kubernetes.io/serviceaccount/namespace`
echo "NAMESPACE is $NAMESPACE"
echo "NETWORKING=yes" >> /etc/sysconfig/network

for entry in ./*tgz
do
    with_ext=$(basename "$entry")
    fname="${with_ext%.*}"
    
    echo "mkdir -p /home/quant_group/$fname"
    mkdir -p /home/quant_group/$fname
    
    echo "tar zxf ${package_path}/$with_ext -C ${package_path}/$fname"
    tar zxf ${package_path}/$with_ext -C ${package_path}/$fname
    
    echo "rm -rf ${package_path}/$with_ext"
    rm -rf ${package_path}/$with_ext
done

echo "cd /home/qg-xterm/;git pull;cd -"
cd /home/qg-xterm/;git pull;cd -
source ~/.bash_profile

echo "sed xyqb.com to q-gp.com"
find ${package_path}/ -name "*.js" | xargs sed -i "s#.domain.com#-$NAMESPACE.q-gp.com#g"

sed -i "s/xterm.js demo/${SYSTEM_NAME}@${NAMESPACE}/"  /home/qg-xterm/demo/index.html

default_conf_file="/usr/local/openresty/nginx/conf/conf.d/default.vh.conf"
if [ -f "$default_conf_file" ]
then
    sed -i "s/SYSTEM_NAME/${SYSTEM_NAME}/" $default_conf_file
fi

echo "mkdir -p /var/log/nginx"
mkdir -p /var/log/nginx

echo "touch /var/log/nginx/error.log"
touch /var/log/nginx/error.log

echo "touch /var/log/nginx/access.log"
touch /var/log/nginx/access.log

echo "/usr/bin/openresty -g 'daemon off;'"
nohup /usr/bin/openresty -g 'daemon off;' &

echo "node /home/qg-xterm/demo/app.js"
nohup node /home/qg-xterm/demo/app.js &

echo "frontail logs/*.log -d -n 1000"
frontail /var/log/nginx/*log -n 1000

replaceGitRemote(){
	originDomain="192.168.3.60"
	activeDomain="git.q-gp.com"

	gdir=/home/qg-xterm
    cd $gdir && echo '进入' $gdir
    git rev-parse --is-inside-work-tree 2>&1 1>/dev/null; # 有个不行

    if [ $? -ne 0 ]
    then
       echo "不是git目录 $gdir" $?;
       cd ..
       continue
    fi

    remoteUrl=`git config --get remote.origin.url`
    echo $remoteUrl | grep $originDomain

    if [ $? -eq 0 ]
      then
        remoteGit="${remoteUrl/$originDomain/$activeDomain}"
        echo '替换后的' $remoteGit
        git remote set-url origin $remoteGit || echo "修改失败" #状态
    fi
    cd -
}