#!/bin/sh
echo "deploy openresty"
package_path="/home/quant_group"

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

export NAMESPACE=`cat /var/run/secrets/kubernetes.io/serviceaccount/namespace`
echo "NAMESPACE is $NAMESPACE"

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/.xyqb.com/-$NAMESPACE.q-gp.com/g"
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