#! /bin/bash

set -u

echo -e "
___  ____                            _         _   _ ________  ___
|  \/  (_)                          (_)       | | | |_   _|  \/  |
| .  . |_  ___ _ __ ___   __ ___   ___  __ _  | | | | | | | .  . |
| |\/| | |/ __| '__/ _ \ / _\` \ \ / / |/ _\` | | | | | | | | |\/| |
| |  | | | (__| | | (_) | (_| |\ V /| | (_| | | |_| | | | | |  | |
\_|  |_/_|\___|_|  \___/ \__,_| \_/ |_|\__,_|  \___/  \_/ \_|  |_/
"

#prepairing all dependencies
#key for docker
apt-get install -y curl
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
 $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null

#Installing Posrgres,nginx,certbot,docker,docker-compose - dependencies for UTM and services.
apt-get update -y
apt-get install -y nginx postgresql postgresql-contrib certbot python3-certbot-nginx \
  docker-ce docker-ce-cli containerd.io docker-compose-plugin wireguard rsync \
  libgstreamer1.0-dev libgstreamer-plugins-base1.0 libgstreamer-plugins-bad1.0 \
  libgstreamer-plugins-good1.0 libglib2.0 gstreamer1.0-nice gstreamer1.0-plugins-good libgstreamer-plugins-bad1.0-0
echo "------"
echo "prepair to use db"
echo "-------"
sleep 2

#Setting -e setup, for exiting if there will be a problem with installation
set -e
#Create Database,user and give an acceess. Creates a file pass.sql that will be used down below.
echo "please type the password for db"
read pass

#read -s -p "please type the password for db: " pass
echo "CREATE DATABASE manet;
CREATE USER manet WITH ENCRYPTED PASSWORD '$pass';
GRANT ALL PRIVILEGES ON DATABASE manet TO manet;
ALTER ROLE postgres WITH ENCRYPTED PASSWORD '$pass';
ALTER USER postgres WITH ENCRYPTED PASSWORD '$pass';" >>/tmp/pass.sql

#Using file pass.sql with user postgres(init user when installing postgresql)
sudo -i -u postgres psql -f /tmp/pass.sql
rm /tmp/pass.sql
echo "------"
echo "database done"
echo "------"
echo "Setting up an UTM instance and dependecies "
#Updating repositories and add Microavia repo for installation of UTM,gate,video-gate
sudo apt update
wget -O - https://microavia:CopterPower@deb.microavia.com/public.key | sudo apt-key add
echo 'deb [arch=amd64] https://microavia:CopterPower@deb.microavia.com/ focal main' >>/etc/apt/sources.list.d/microavia.list
apt-get update
apt-get install -y microavia-utm microavia-gate microavia-video-gate microavia-cloud-tools

#Creating config file for nginx web-server. Using HTTP without ssl cert cuz it's local installation.
echo "---------"
echo "enter name of instance [local.utm.microavia.com]"

inst_name=
while [ -z $inst_name ]; do
  read inst_name
done

touch /etc/nginx/sites-available/$inst_name
echo '
# MANet UI

server {
    listen		80;
    server_name		localhost;



    location / {
        root /opt/microavia/utm/www;
	add_header Access-Control-Allow-Origin *;
    }

    location ~* \.(html)$ {
        root /opt/microavia/utm/www;
        add_header Last-Modified $date_gmt;
    }

    location /api/v1 {
        proxy_set_header    X-Real-IP  $remote_addr;
        proxy_pass          http://127.0.0.1:5462$request_uri;
    }

    location /api/v1/ws {
        proxy_set_header    X-Real-IP  $remote_addr;
        proxy_pass          http://127.0.0.1:5462$request_uri;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection "Upgrade";
    }

    location /geoserver {
        proxy_set_header     X-Real-IP  $remote_addr;
        proxy_pass           http://127.0.0.1:8083$request_uri;
        proxy_pass_header    Set-Cookie;
        proxy_set_header     Host $host;
        proxy_set_header     X-Forwarded-Proto $scheme;
        proxy_set_header     X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}' >>/etc/nginx/sites-available/$inst_name

#Changing config file of UTM. Changing string with password to the Database
cp /opt/microavia/utm/configs/config.example.yml /opt/microavia/utm/configs/config.yml
sed -i 's+password: ""+password: "'$pass'"+g' /opt/microavia/utm/configs/config.yml
#Removing default config of nginx web server

if [ -f /etc/nginx/sites-enabled/default ]; then
  rm /etc/nginx/sites-enabled/default
fi
#Enable UTM config in nginx web-server
ln -sf /etc/nginx/sites-available/$inst_name /etc/nginx/sites-enabled/$inst_name

nginx -t
service nginx restart
#Downloading and starting UTM Cache tile proxy and geotiff server from Microavia GITlab. User needs a login and Password for installation.
echo "---------"
echo "enter login to gitlab"
read git_login
echo "---------"
echo "enter pass to git"
read git_pass
echo "--------"
echo "Thank you. Now i am installing a utm tile cache proxy"
docker login gitlab.microavia.com:4567/microavia/utm-tile-proxy --username $git_login --password $git_pass
docker pull gitlab.microavia.com:4567/microavia/utm-tile-proxy/utm-tile-proxy:latest
docker pull gitlab.microavia.com:4567/microavia/geotiffsrv/geotiffsrv:latest
docker run --restart=unless-stopped -d --name tiler -p 8081:8081 -p 5000:5000 -p 8083:8083 --network host -v ~/Microavia/temp/tilesProxyCache:/home/cache/tiles gitlab.microavia.com:4567/microavia/utm-tile-proxy/utm-tile-proxy
docker run --restart=unless-stopped -d --name geotiffsrv -p 10880:10880 --network host -v ~/Microavia/temp/geotiffsrv/geotiffs:/home/geotiffs gitlab.microavia.com:4567/microavia/geotiffsrv/geotiffsrv
sudo chmod 777 -R ~/Microavia/temp/geotiffsrv/geotiffs
echo '{
  "app": {
    "serverBase": "http://'$inst_name'",
    "socketUrl": "ws://'$inst_name'/api/v1/ws",
    "viewExtent": [ -5.06, 41.28, 15.4, 48.3 ],
    "showTraffic": false,
    "showDebug": false,
    "trafficTimeout": 0,
    "activeTrafficTimeout": 0,
    "units": {
      "speed": "kmh",
      "alt": "m",
      "vs": "ms"
    },
    "alt": "msl",
    "layers": [
      {
        "type": "GlobusTerrain",
        "name": "terrain",
        "url": "http://'$inst_name':5000/terrain/{z}/{y}/{x}.ddm"
      },
      {
        "name": "osm",
        "url": "http://'$inst_name':5000/osm/{z}/{x}/{y}.png",
        "attribution": "Data @ OpenStreetMap contributors, ODbL",
        "visibility": true
      },
{
  "name": "sat",
  "url": "http://'$inst_name':5000/sat/a{quad}.jpeg?n=z&g=7146",
  "attribution": "2021 Microsoft Corporation",
  "visibility": true
}
    ]

  }
}' >>/opt/microavia/utm/www/config.json
echo "---------"
echo "Install almost finished. Need to migrate database from init"
echo "---------"
# Initialize DB from Microavia GITlab
wget https://files.microavia.com/init_db.sql -O /tmp/init_db.sql
sudo -i -u postgres psql -f /tmp/init_db.sql
rm /tmp/init_db.sql
#Installing rsync user
useradd rsync-user -p somecomplexpassword123
echo 'uid = nobody
gid = nogroup
use chroot = no
max connections = 10
pid file = /var/run/rsyncd.pid
# port = 873

[resources]
path = /opt/microavia/data
comment = For backups from local servers
uid = root
gid = root
read only = false
auth users = rsync-user
secrets file = /etc/rsyncd.pass
' >>/etc/rsyncd.conf
echo 'rsync-user:somecomplexpassword123' >>/etc/rsyncd.pass
chmod 600 /etc/rsyncd*
systemctl restart rsync
sed -i 's+example_user+rsync-user+g' /opt/microavia/utm/configs/config.yml
sed -i 's+example_pass+somecomplexpassword123+g' /opt/microavia/utm/configs/config.yml
sed -i 's+example_host+rsync://rsync-user@'$inst_name'/resources+g' /opt/microavia/utm/configs/config.yml
#Configuring gate-service
cp /opt/microavia/gate/config_example.json /opt/microavia/gate/config.json
sed -i 's+utm.microavia.com+'$inst_name'+g' /opt/microavia/gate/config.json
systemctl restart microavia-gate
#Configuring Video-gate service
sed -i 's+example.com+'$inst_name'+g' /opt/microavia/utm/configs/config.yml
systemctl restart microavia-video-gate
#Restarting UTM service to accept config file to a service
systemctl restart microavia-utm

echo "ADDR 0011223344
KEY 00112233445566778899AABBCCDDEEFF" >>/opt/microavia/video-gate/manet.conf
systemctl restart microavia-video-gate

systemctl enable rsync
systemctl enable microavia-video-gate
systemctl enable microavia-gate
systemctl enable microavia-utm
echo "---------"
echo "Installation finished. Thank you for using our deployment tool."
echo "---------"
