#!/bin/bash

####################################################################
# OAS Engine Install Script
#
# REQUIREMENTS:
# This installation script requires systemd on the Linux OS.
# As of this writing, systemd is available on all distributions of
# Linux supported by .NET Core 3.1 (a core component of the OASEngine)
# except Alpine Linux.
#
# MODIFICATION OF THIS SCRIPT IS NOT SUPPORTED
#
# Copyright 2023 Open Automation Software
# All rights reserved.
####################################################################

ROOT_UID=0
SUCCESS=0
E_USEREXISTS=70
LOGFILE="install.log"

echo -e "\e[96m***************************"
echo -e " OAS Platform Installation"
echo -e "***************************"
echo -e "\e[0m"

# Enforce this script is running as root
if [ "$UID" -ne 0 ]; then
  echo -e "\e[33mMust be root to run this script. Try executing the script using:\e[0m"
  echo -e "\e[96msudo ./oas_install.sh\e[0m"
  exit $E_NOTROOT
fi

if [ -e $LOGFILE ]; then
  rm $LOGFILE
fi

echo "Enter username under which the OASEngine will be installed as a service."
echo "If the user does not exist, it will be created for you."
echo ""
echo "DO NOT use the current user account ($USER)."
echo ""
read -p $'\e[96mHit ENTER to use the default of (oasuser)\e[0m: ' -r uname
if [[ -z "${uname// }" ]]; then
    uname="oasuser"
fi
echo "uname:$uname" >> $LOGFILE

# Create or use existing user account
RES=`grep -c "$uname" /etc/passwd`
if [ $RES -eq 1 ]; then
    echo -e "\e[33mUser ($uname) exists.\e[0m"
else
    pwd=""
    pwc=0
    echo "Creating new user ($uname)."
    while [[ -z "${pwd// }" ]]; do
        if [ $pwc -eq 3 ]; then
            echo -e "\e[31mExiting.\e[0m"
            exit 1
        fi
        read -p $'\e[96mEnter password for ('"$uname"$'\e[96m)\e[0m: ' -s pwd
        if [[ -z "${pwd// }" ]]; then
            echo -e "\e[33mPassword cannot be blank.\e[0m"
            ((pwc=pwc+1))
        else
            read -p $'\n\e[96mEnter password again to confirm\e[0m: ' -s pwdconfirm
            if [[ -z "${pwdconfirm// }" ]] || [ $pwd != $pwdconfirm ]; then
                echo -e "\e[33mPasswords do not match.\e[0m"
                pwd=""
                ((pwc=pwc+1))
            fi
        fi
    done
    useradd -m $uname
    echo -e "$pwd\n$pwd\n" | passwd $uname &> /dev/null
    # required for unattended operation
    loginctl enable-linger $uname
    echo -e "\nUser ($uname) created."
fi

# copy application to user directory
pathname="$(basename "$(dirname "$PWD")")"
targetpath="/home/$uname/$pathname/"

echo "path:$targetpath" >> $LOGFILE

if [ -d "$targetpath/../$pathname.bak" ]; then
    rm -r "$targetpath/../$pathname.bak"
fi
if [ -d "$targetpath" ]; then
    mv $targetpath "$targetpath/../$pathname.bak"
fi
echo -e "\e[96mInstalling OAS Engine into user home ($targetpath)\e[0m..."
cp -r ../ $targetpath
chown -R $uname:$uname /home/$uname/$pathname

# set up service
svcdir="/home/$uname/.config/systemd/user/"
if [ ! -d "$svcdir" ]; then
    mkdir -p $svcdir
fi

echo "svcdir:$svcdir" >> $LOGFILE

# edit and copy .service to user home
sed -i 's/oasuser\/OASEngine/'"$uname"'\/'"$pathname"'/' oas-engine.service
cp ./oas-engine.service $svcdir
sed -i 's/'"$uname"'\/'"$pathname"'/oasuser\/OASEngine/' oas-engine.service

# set ownership on all files and directories
chown -R $uname:$uname /home/$uname/.config
# reload user daemon and enable service
ouid=`id -u "$uname"`
sudo -u $uname XDG_RUNTIME_DIR="/run/user/$ouid" DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus" systemctl --user daemon-reload &> /dev/null
sudo -u $uname XDG_RUNTIME_DIR="/run/user/$ouid" DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus" systemctl --user enable oas-engine.service &> /dev/null
# ensure OASEngine is executable
chmod +x "$targetpath"OASEngine

echo -e "\n\e[96mOAS Engine installation complete."
echo ""
echo -e "The OAS Engine will now automatically start on reboot.\n\n"

echo -e "\n\e[96mTo manually \e[32mSTART\e[96m the service, log in as ($uname) and execute\e[0m:"
echo -e "\e[0msystemctl --user start oas-engine\n"
echo -e "\e[96mTo manually \e[91mSTOP\e[96m the service, log in as ($uname) and execute\e[0m:"
echo -e "\e[0msystemctl --user stop oas-engine\n\n"

exit 0
