#!/bin/bash

while [ -n "$1" ]
do
        if [ -z "$2" ]
        then
            echo "ERROR! no values specified after "$1" !" | tee -a $LOG_FILE
            echo "$USAGE"
            exit 1
        fi
        param="$2"

        case "$1" in
                --domain_name)
                     DOMAIN_NAME=$param
                        shift ;;
                --hes_port)
                        HES_PORT=$param
                        shift ;;
                --) shift
                break ;;
                *) echo "ERROR! $1 is not an option"
                   echo "$USAGE"
                   exit 1
        esac
        shift
done


#create certs
if [ ! -d /etc/nginx/certs ]; then
    mkdir /etc/nginx/certs
fi
openssl req -x509 -nodes -days 3652 -newkey rsa:2048 -keyout /etc/nginx/certs/$DOMAIN_NAME.key -out /etc/nginx/certs/$DOMAIN_NAME.crt  -subj "/C=''/ST=''/L=''/O='' Security/OU=''/CN=''"


#Configuration for the Nginx Reverse Proxy

#create backup of Configuration file
if [ -f /etc/nginx/conf.d/$DOMAIN_NAME.conf ]; then
    mv /etc/nginx/conf.d/$DOMAIN_NAME.conf  /etc/nginx/conf.d/$DOMAIN_NAME.conf-$(date +%Y-%m-%d-%H-%M-%S)
fi

cat > /etc/nginx/conf.d/$DOMAIN_NAME.conf << EOF
server {
        listen       80;
        #or if it is one single server
        #listen       80 default_server;
        #listen       [::]:80;
        #or if it is one single server
        #listen       [::]:80 default_server;
        server_name  $DOMAIN_NAME;
        return 301 https://\$host\$request_uri;

}
server {
        listen       443 ssl http2;
        #or if it is one single server
        #listen       443 ssl http2 default_server;
        #listen       [::]:443 ssl http2;
        #or if it is one single server
        #listen       [::]:443 ssl http2 default_server;
        server_name  $DOMAIN_NAME;
        ssl_certificate "certs/$DOMAIN_NAME.crt";
        ssl_certificate_key "certs/$DOMAIN_NAME.key";
        location / {
            proxy_set_header Host \$host;
            proxy_set_header X-Real-IP \$remote_addr;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            # Enable proxy websockets for the hideez Client to work
            proxy_http_version 1.1;
            proxy_buffering off;
            proxy_set_header Upgrade \$http_upgrade;
            proxy_set_header Connection \$http_connection;
            proxy_pass http://localhost:$HES_PORT;
        }
}
EOF

#Restarting the Nginx Reverse Proxy and check its status
systemctl restart nginx
#sudo systemctl status nginx

################################