#!/bin/bash

####################################################################
# OAS Engine Uninstall 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 2020 Open Automation Software
# All rights reserved.
####################################################################

LOGFILE="install.log"

# 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[39m"
  echo -e "\e[96msudo ./oas_uninstall.sh\e[39m"
  exit $E_NOTROOT
fi

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

if [ ! -e $LOGFILE ]; then
  echo -e "\e[91mInstall log does not exist. Cannot proceed.\e[39m"
  exit 0
fi

uname=""
path=""
svcdir=""
while IFS= read -r line; do
  readarray -d : -t farray <<< "$line"
  key="${farray[0]}"
  val="${farray[1]}"
  if [ $key = "uname" ]; then
    uname=$val
  elif [ $key = "path" ]; then
    path=$val
  elif [ $key = "svcdir" ]; then
    svcdir=$val
  fi
done < $LOGFILE

echo -e "Stopping the OAS Engine process..."

pid=$(ps aux | grep '[O]ASEngine' | awk '{print $2}')
if [ -z "$pid" ]; then
  echo -e "\e[91mProcess is not running.\e[39m"
else
  kill -9 $pid > /dev/null 2>&1
  echo -e "\e[91mOASEngine stopped.\e[39m"
fi

echo -e "OAS user account: ${uname}"
read -p $'\e[96mWould you like to remove the OAS user account and all install files? (y/n)\e[0m: ' yn
if [ "$yn" = "y" ] || [ "$yn" = "Y" ]; then
  echo -e "\nDeleting account: $uname..."
  killall -u $uname > /dev/null 2>&1
  if userdel -r -f $uname > /dev/null 2>&1; then
    echo -e "\e[91mOAS account deleted.\e[0m"
  else
    echo -e "\e[91mCould not delete OAS user.\nEnsure user account exists and is not being used.\e[39m"
  fi
fi
echo -e "\n\e[32mOAS Engine uninstall complete.\e[39m"

exit 0
