#!/bin/bash
python3 -m venv env
export nameproj=${PWD##*/}
echo $nameproj;

SERVER_NAME="127.0.0.1"
GUNICORN_FILE="/etc/systemd/system/${nameproj}.service"
NGINX_FILE="/etc/nginx/sites-available/${nameproj}"


# parse arguments
while [[ "$#" -gt 0 ]]; do
    case $1 in
        -s|--servername) SERVER_NAME="$2"; shift ;;
        -V|--printvars) declare -p | grep -- '--'|sed -e 's/^declare -- //g' ; exit 0 ;;
        -h|*) echo "Usage: ${PROG} [-s|--servername <hostname of webserver>]"; exit 1 ;;
    esac
    shift
done

if [ -e ${GUNICORN_FILE} -o -e ${NGINX_FILE} ] ; then
	echo "A service for ${instr_db} is already installed! Exiting."
	exit 1
fi


#GUNICORN_FILE="/etc/systemd/system/$nameproj.service"
/bin/cat <<EOM >$GUNICORN_FILE
[Unit]
Description=gunicorn service
After=network.target

[Service]
User=$USER
Group=www-data
WorkingDirectory=$PWD
ExecStart=$PWD/env/bin/gunicorn --log-level error --timeout 120 --access-logfile $PWD/$nameproj/logs/misc.log --workers 1 --bind unix:$PWD/$nameproj.sock $nameproj.wsgi:application

[Install]
WantedBy=multi-user.target
EOM

#NGINX_FILE="/etc/nginx/sites-available/$nameproj"
touch $NGINX_FILE
/bin/cat <<EOM >$NGINX_FILE
server {
    listen 80;
    server_name ${SERVER_NAME}; #127.0.0.1;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root $PWD;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:$PWD/$nameproj.sock;
    }
}
EOM
rm -rf /etc/nginx/sites-enabled/default
rm -rf /etc/nginx/sites-available/default
ln -s /etc/nginx/sites-available/$nameproj /etc/nginx/sites-enabled
