#!/bin/bash
mode="dev"


if [[ $* =~ ^(prod)$ ]]; then 
	mode="prod"
fi

if [ $mode == "dev" ]; then
    echo "[Installing AURA ENGINE for Development]"
fi
if [ $mode == "prod" ]; then
    echo "[Installing AURA ENGINE for Production]"
fi

echo "Installation System Packages ..."
bash script/install-system-packages.sh

echo "Installation OPAM Packages ..."
bash script/install-opam-packages.sh


# Development 

if [ $mode == "dev" ]; then
    # Set LOCK file location
    LOCKFILE_DB=configuration/.install.mariadb.lock

    echo "Copy configuration to './configuration/engine.ini'"
    cp -n configuration/sample.engine.ini configuration/engine.ini
fi


# Production 

if [ $mode == "prod" ]; then
    # Set LOCK file location
    LOCKFILE_DB=/etc/aura/engine/.install.mariadb.lock

    if getent passwd 'engineuser' > /dev/null 2>&1; then  
        echo "User 'engineuser' exists already."; 
    else     
        echo "Creating Engine User ..."
        adduser engineuser
        adduser engineuser sudo
    fi
    
    echo "Copy Supervisor Config to '/etc/supervisor/conf.d'"
    cp configuration/supervisor/engine-api.conf /etc/supervisor/conf.d/

    echo "Create Log Directory `/var/log/aura/engine`"
    mkdir -p /var/log/aura
    mkdir -p /var/log/aura/engine

    echo "Create Configuration Directory `/etc/aura/engine`"
    mkdir -p /etc/aura

    echo "Copy configuration to './configuration/engine.ini'"
    cp -n configuration/sample.engine.ini engine.ini
    
    echo "Set Ownership of '/opt/aura/engine', '/var/log/aura/' and '/etc/aura/engine.ini' to Engine User"
    chown -R engineuser:engineuser .
    chown -R engineuser:engineuser /var/log/aura/
    chown -R engineuser:engineuser /etc/aura/engine.ini
fi


# Development and Production

echo "Create local Logs Folder ..."
mkdir -p logs

echo "Installing Web Application Packages ..."
bash script/install-web.sh

echo "Installing Python Requirements ..."
python3.7 $(which pip3) install -r requirements.txt

echo "Setting up database ..."
echo 
echo "Which database system do you want to use? (Press '1' or '2')"
echo "  [1] MariaDB"
echo "  [2] Other / Manually"
echo

while true; do
read -rsn1 input
if [ "$input" = "1" ]; then
    echo "Creating DB for MariaDB ..."
    bash script/init-db-mariadb.sh
    break
fi
if [ "$input" = "2" ]; then
    echo "Manual database setup selected."
    break
fi
done

echo 
echo "+++ Installation of AURA Engine finished! +++"