#!/bin/bash

APP=bssapp
PORT=43201
DOMAIN=ss.baggi.com.tr

apt update && apt upgrade
apt -y install mc rsync curl nginx
apt install certbot python3-certbot-nginx
dpkg-reconfigure tzdata

useradd --system --shell=/usr/sbin/nologin ${APP}

mkdir -p /opt/${APP}/sqls
mkdir -p /opt/${APP}/migrate
mkdir -p /opt/${APP}/ui
mkdir -p /opt/${APP}/files

echo "Creating application service"
read -d '' sservice << EOF
[Unit]
Description=${APP}
After=syslog.target
After=network.target
#Requires=postgresql.service
#Requires=memcached.service
#Requires=redis.service

[Service]
# Modify these two values and uncomment them if you have
# repos with lots of files and get an HTTP error 500 because
# of that
###
LimitMEMLOCK=infinity
LimitNOFILE=1048576

RestartSec=2s
Type=simple
User=${APP}
Group=${APP}
WorkingDirectory=/opt/${APP}/
ExecStart=/opt/${APP}/nerp
Restart=always

Environment=HTTPPORT=${PORT} SQLSDIR=./sqls DBHOST=10.0.0.2 DBNAME=${APP} DBPASS=tesnos.+ed

# enable to bind to a port below 1024 uncomment
###
#CapabilityBoundingSet=CAP_NET_BIND_SERVICE
#AmbientCapabilities=CAP_NET_BIND_SERVICE

# Prevent writes to /usr, /boot, and /etc
ProtectSystem=full

# Prevent accessing /home, /root and /run/user
ProtectHome=true

# Execute pre and post scripts as root, otherwise it does it as User=
PermissionsStartOnly=true

[Install]
WantedBy=multi-user.target
EOF
echo "$sservice" > /etc/systemd/system/${APP}.service


echo "Creating nginx conf"
read -d '' ngconf << EOF
server {
    server_name ${DOMAIN}
    listen 80;
    client_max_body_size 100M;

    location / {
        proxy_pass http://localhost:${PORT};

        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}
EOF
echo "$ngconf" > /etc/nginx/sites-available/${DOMAIN}
ln -s /etc/nginx/sites-available/${DOMAIN} /etc/nginx/sites-enabled
systemctl restart nginx
certbot --nginx -d ${DOMAIN}

systemctl daemon-reload
systemctl enable ${APP}

