#!/bin/bash

# Place this file in /home/satsense/installers/ and make it executable
# Then run 
#           ./admin.bash $SERVICE $PORT1 $INSTALL_PATH $DOMAIN
# e.g.      ./admin.bash staging-admin 5010 /var/www/staging/admin staging.admin.satsense.com


# NOTE: $PORT2 will be automatically generated by adding 1 to the value provided for $PORT1

SERVICE=$1
PORT1=$2
PORT2=$(($PORT1+1))
INSTALL_PATH=$3
DOMAIN=$4
TIMESTAMP=$(/bin/date +"%Y%m%d_%H%M%S")


if [ ! -z "$4" ]; then
  echo "Service names:   $SERVICE-blue, $SERVICE-green"
  echo "Port numbers:    $PORT1, $PORT2"
  echo "Install paths:   $INSTALL_PATH"
  echo "Domain:          $DOMAIN"
  echo "Download:        /home/flask/admin/$TIMESTAMP"
else
  echo "Must provide 3 params:    Service name    |     Port number   |    Path   |       Domain"
  echo "e.g.  ./admin.bash       staging-admin         5000     /var/www/staging/admin    staging.admin.satsense.com"
  exit
fi

printf "\n\nTo revert everything this script is about to do, run the following commands:\n\n"

echo "sudo rm /etc/systemd/system/$SERVICE-blue.service"
echo "sudo rm /etc/systemd/system/$SERVICE-green.service"
echo "sudo rm /etc/apache2/sites-available/$SERVICE.conf"
echo "sudo rm /etc/apache2/sites-enabled/$SERVICE.conf"
echo "sudo rm -rf $INSTALL_PATH"
echo "sudo systemctl daemon-reload"
echo "sudo service apache2 reload"
echo ""

read -r -p "Type Y to continue, or anything else to exit: " input
if [ $input != 'Y' ]; then
  echo "Exiting"
  exit
fi

# Download artifacts
sudo -i -u flask /home/flask/releases/admin/download_artifacts.bash master $TIMESTAMP

download_path="/home/flask/releases/admin/${TIMESTAMP}/dist"
pip="${INSTALL_PATH}/virtual_environments/venv/bin/pip"

# Create directories
printf "\n\nInstalling to $INSTALL_PATH\n\n"
sudo mkdir -p $INSTALL_PATH
cd $INSTALL_PATH

sudo mkdir public/
sudo chown flask:www-data public/

sudo mkdir log/
sudo chown flask:www-data log/

sudo mkdir log/flask
sudo chown flask:flask log/flask/

sudo mkdir app_home/
sudo chown flask:flask app_home/

sudo mkdir virtual_environments/
sudo chown flask:flask virtual_environments/

# Create virtual environment
printf "\n\nWill create and use pip instance in $pip\n\n"
sudo -i -u flask /usr/bin/python3.7 -m venv $INSTALL_PATH/virtual_environments/venv

# Install
printf "\n\nInstalling using download $download_path\n\n"
sudo -i -u flask cp $download_path/satadmin/app.py $INSTALL_PATH/app_home
sudo -i -u flask cp $download_path/satadmin/config.ini $INSTALL_PATH/app_home
printf "\n\nNow edit $INSTALL_PATH/app_home/config.ini with the necessary config.\n\n"

sudo -i -u flask mkdir $INSTALL_PATH/public/error
sudo -i -u flask cp -r ${download_path}/satadmin/error $INSTALL_PATH/public/

sudo -i -u flask $pip install "$(sudo -i -u flask cat $download_path/satadmin/requirements/production.txt | grep numpy)"
sudo -i -u flask $pip install GDAL==$(gdal-config --version | awk -F'[.]' '{print $1"."$2}') --global-option=build_ext --global-option="-I/usr/include/gdal"
sudo -i -u flask $pip install -r $download_path/satadmin/requirements/production.txt

printf "\n\nInstalling SatSense Domain packages\n\n"
sudo mkdir $INSTALL_PATH/tmp
sudo cp -r $download_path/satdom $INSTALL_PATH/tmp/
sudo -i -u flask $pip install $INSTALL_PATH/tmp/satdom/satdom*.whl

printf "\n\nInstalling Admin packages\n\n"
sudo cp -r $download_path/satadmin $INSTALL_PATH/tmp/
sudo -i -u flask $pip install $INSTALL_PATH/tmp/satadmin/satadmin*.whl

sudo rm -rf $INSTALL_PATH/tmp

sudo -i -u flask $pip install gunicorn


INDEX=0
for colour in blue green
do
  # Services
  SERVICE_NAME="${SERVICE}-${colour}"
  printf "\n\nCreating $SERVICE_NAME service\n\n"
  sudo touch /etc/systemd/system/$SERVICE_NAME.service
  sudo chmod 664 /etc/systemd/system/$SERVICE_NAME.service

  sudo tee -a /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOT
[Unit]
Description = $SERVICE_NAME
After = network.target

[Service]
User=flask
WorkingDirectory=$INSTALL_PATH/app_home
ExecStart=$INSTALL_PATH/virtual_environments/venv/bin/gunicorn -b localhost:$(($PORT1+$INDEX)) -w 4 app:app
Restart=always

[Install]
WantedBy = multi-user.target
EOT

  sudo systemctl daemon-reload

  sudo systemctl start $SERVICE_NAME
  systemctl status $SERVICE_NAME
  sudo systemctl stop $SERVICE_NAME
  sudo systemctl enable $SERVICE_NAME

  sudo systemctl start $SERVICE_NAME

  INDEX=$(expr $INDEX + 1)
done


# Apache
printf "\n\nCreating Apache VirtualHost at /etc/apache2/sites-available/$SERVICE.conf"
sudo tee -a /etc/apache2/sites-available/$SERVICE.conf > /dev/null <<EOT
<VirtualHost *:80>

ServerName $DOMAIN
ServerAlias $DOMAIN
DocumentRoot $INSTALL_PATH/public

# rewrite to https
RewriteEngine on
RewriteCond %{SERVER_NAME} =$DOMAIN
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

</VirtualHost>

<VirtualHost *:443>
ServerName $DOMAIN
ServerAlias $DOMAIN
DocumentRoot $INSTALL_PATH/public

<Proxy balancer://admin>
    BalancerMember http://localhost:$PORT1
    BalancerMember http://localhost:$PORT2
</Proxy>

# flask proxy
ProxyPreserveHost On
ProxyPass /error !
ProxyPass / balancer://admin/
ProxyPassReverse / balancer://admin/

# logs
ErrorLog $INSTALL_PATH/log/error.log
CustomLog $INSTALL_PATH/log/requests.log combined

# headers:
Header always set Strict-Transport-Security "max-age=31536000; includeSubdomains"
Header always set X-Frame-Options "deny"
Header always set X-Xss-Protection "1; mode=block"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "no-referrer"
Header always edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure;SameSite=Strict

# Error Documents
ErrorDocument 503 /error/503.html
</VirtualHost>
EOT

sudo ln -s /etc/apache2/sites-available/$SERVICE.conf /etc/apache2/sites-enabled/$SERVICE.conf

sudo service apache2 reload


# Certbot
sudo certbot --apache

echo "Done."