#!/bin/bash
source settings.sh

apt-get -y install python3-tornado nginx supervisor psmisc python3-reportlab git
git config --global core.editor "vim"

#File install
rm -Rf $INSTALLDIR
git archive master $APPDIR | tar -x --overwrite -C $SITEPACKAGES

#Supervisor Install
systemctl stop supervisor.service
killall supervisord >/dev/null 2>&1
sleep 1
rm -f /var/run/supervisor.sock >/dev/null 2>&1
cat $INSTALLRES/supervisor.conf |
    sed s/NAME/$NAME/g |
    sed s#INSTALLDIR#$INSTALLDIR#g |
    sed s/STARTPORT/$STARTPORT/g |
    sed s/DEBUGPORT/$DEBUGPORT/g |
    sed s/NUMPROCS/$NUMPROCS/g \
    > /etc/supervisor/conf.d/$NAME.conf

systemctl start supervisor.service
sleep 1
supervisorctl update
supervisorctl stop $NAME:*
rm -f /var/log/$NAME*
rm -f /var/log/supervisor/$NAME*
supervisorctl start $NAME:*

#NGINX Install
unlink /etc/nginx/sites-enabled/default > /dev/null 2>&1
cat $INSTALLRES/nginx.conf |
    sed -n '/BACKENDS/q;p' \
    > /etc/nginx/conf.d/$NAME.conf
let ENDPORT=$STARTPORT+$NUMPROCS-1
for i in `seq $STARTPORT $ENDPORT`; do
echo -e "\tserver 127.0.0.1:$i;" \
 >> /etc/nginx/conf.d/$NAME.conf
done
cat $INSTALLRES/nginx.conf |
    sed 'N; s|^.*BACKENDS\(.*\)$||' \
  >> /etc/nginx/conf.d/$NAME.conf
systemctl restart nginx.service
