#!/bin/sh
FILE=/usr/lib/ncinfo.xml
ncv="NC-ENT-5.3.8-64"
PRODUCT="NCache"
InstallType=
REMOVEUSER="true"
NCUSER="ncache"
LUCENE_DIST_MAP_PATH="/usr/share/ncache"
ISCONTAINER=false

#--------------------------------------------------------------------------------------
printMessage ()
{
	message=$1
	echo "$message"
}
#--------------------------------------------------------------------------------------
printError ()
{
	message=$1
	echo "------"
	echo "ERROR: $message" 1>&2;
	echo ""
}
#--------------------------------------------------------------------------------------
printMode ()
{
	message=$1
	if [ ! -z "$VERBOSE" ]
	then
		echo "$message"
	fi
}
#--------------------------------------------------------------------------------------
usage()
{
	echo "This script uninstalls NCache."
	echo ""
	echo "Usage: uninstall [OPTIONS]"
	echo ""
	echo "  -p, --path			NCache install directory. If not provided, then it tries to use the default path (/opt/ncache)"
	echo "  -d, --donotremoveuser 	Do not remove user '$NCUSER' on uninstallation"
	echo "  -F, --force			Suppresses all prompts."
	echo ""
	exit 1
}
#--------------------------------------------------------------------------------------
uninstall()
{
	rm /etc/systemd/system/ncached.service
	
	if [  -f "/etc/systemd/system/ncachebridged.service" ]; then 
		rm /etc/systemd/system/ncachebridged.service
	fi
	
	if [  -f "/etc/systemd/system/ncachecloud.service" ]; then 
		rm /etc/systemd/system/ncachecloud.service
	fi
	 
	# if [  -f "/etc/systemd/system/ncacheloaderd.service" ]; then 
		# rm /etc/systemd/system/ncacheloaderd.service
	# fi
	 
	if [  -f "/etc/systemd/system/ncexecution.service" ]; then 
		rm /etc/systemd/system/ncexecution.service
	fi
	
	if [ $REMOVEUSER = "true" ]; then
		userdel -r "$NCUSER" -f 2> /dev/null
		groupdel $NCUSER -f 2> /dev/null 
		printMessage "Removed '$NCUSER' user"
	fi

	rm /usr/lib/ncinfo.xml
	rm -r $NCHOME
	rm -r $LUCENE_DIST_MAP_PATH/lucene-index
}
#--------------------------------------------------------------------------------------
reconfirm()
{
	read -p "Are you sure you want to uninstall? (y/n)" yn
	case $yn in
		y )
			printMessage "Uninstalling NCache..."
			;;
		n )
			printMessage "Uninstallation cancelled."
			echo ""
			exit
			;;
		* )
			printMessage "Invalid argument."
			echo ""
			exit
			;;
	esac
}
#--------------------------------------------------------------------------------------
stopservice()
{
	systemctl disable ncached.service
	systemctl stop ncached.service

	pgrep -f Alachisoft.NCache.CacheHost | while read -r line ; do
		kill -9 $line 
	done
	
	pgrep -f Alachisoft.NCache.ManagementCenter | while read -r line ; do
		kill -9 $line 
	done

	if [  -f "/etc/systemd/system/ncachecloud.service" ]; then 
		systemctl disable ncachecloud.service
		systemctl stop ncachecloud.service
	fi

	if [  -f "/etc/systemd/system/ncachebridged.service" ]; then 
		systemctl disable ncachebridged.service
		systemctl stop ncachebridged.service
	fi

	# if [  -f "/etc/systemd/system/ncacheloaderd.service" ]; then 	
		# systemctl disable ncacheloaderd.service
		# systemctl stop ncacheloaderd.service
	# fi
	
	if [  -f "/etc/systemd/system/ncexecution.service" ]; then 	
		systemctl disable ncexecution.service
		systemctl stop ncexecution.service
	fi
	
	systemctl daemon-reload
}

GetMacAddresses()
{
i=1
D='/sys/class/net'
for nic in $( ls $D )
do
    if  grep -q up $D/$nic/operstate
    then
		eval mac$i=$(cat $D/$nic/address)
		if [ $i -eq 4 ]
		then
			break
		fi
		i=$((i+1))
    fi
done
}

PostUnInstallationActivity ()
{
	NumberOfCPU="$(grep processor /proc/cpuinfo | wc -l)"
	NumberofCores="$(nproc --all)"
	NumberOfVCPU="$(grep processor /proc/cpuinfo | wc -l)"
	macName="`hostname`"

	Ram="$(cat /proc/meminfo | grep MemTotal | grep -o -E '[0-9]+')"
	Ram=$((Ram/(1024*1024)))

	OSCode="`uname`"
	case $OSCode in
	  'Linux')
		OSCode='12'
		;;
	  *)
		OSCode="-1"
		;;
	esac
	GetMacAddresses
	mi=$OSCode":"$NumberOfCPU":"$NumberofCores":"$NumberOfVCPU":"$Ram
	curl --connect-timeout 10 --max-time 30 --silent --output /dev/null --data "fn=$FirstName&ln=$LastName&email=$Email&company=$Company&ncv=$ncv&edt=$InstallType&netv=$versionFound&mi=$mi&act=0&ip=$ip&macName=$macName&mac1=$mac1&mac2=$mac2&mac3=$mac3&mac4=$mac4" https://app.alachisoft.com/ncache/nc-getting-started.php
}
#--------------------------------------------------------------------------------------
#--- Start of execution
#--------------------------------------------------------------------------------------
if test -f "$FILE"; then
	Email=$(grep -oP '(?<=email>)[^<]+' "/usr/lib/ncinfo.xml")
	FirstName=$(grep -oP '(?<=first-name>)[^<]+' "/usr/lib/ncinfo.xml")
	LastName=$(grep -oP '(?<=last-name>)[^<]+' "/usr/lib/ncinfo.xml")
	Company=$(grep -oP '(?<=company>)[^<]+' "/usr/lib/ncinfo.xml")
	InstallCode=$(grep -oP '(?<=install-code>)[^<]+' "/usr/lib/ncinfo.xml")
	
	InstallType="Unknown"
	case $InstallCode in
	"p2exJ2fWV2GQ4DGwg7cSMxP3N5a3")
		InstallType="server"
		;;
	"p2exR2fWV2GQ4DGwg7cSMxP3N5a3" )
		InstallType="client"
		;;
	esac
fi
#--------------------------------------------------------------------------------------
# if [ ! -f "/usr/lib/ncinfo.xml" ]; then 
# 	echo ""
# 	printError "NCache is not installed on your machine or installation is corrupt"
# 	exit 1
# fi
	
NCHOME=$(awk -F '[<>]' '/install-dir/{print $3}' /usr/lib/ncinfo.xml) 2> /dev/null
#--------------------------------------------------------------------------------------
while [ "$1" != "" ]; 
do
    case $1 in
    -p | --path ) shift
           NCPATH=$1           
           ;;

    -F | --force )
           FORCE="y"
           ;;
					
	-d | --donotremoveuser )
			REMOVEUSER="false"
			;;
			
	-h | --help )
			usage
			exit
			;;

    * )
		usage
        exit 
        ;;

    esac
    shift
done
#--------------------------------------------------------------------------------------
#--- Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   printError "Uninstallation requires root privileges."
   exit 1
fi
#--------------------------------------------------------------------------------------
if [ -z "$NCPATH" ]; then
   if [ -z "$NCHOME" ]; then
      printError "No install path provided with -p or --path and NCHOME is also not set. Aborting NCache uninstallation..."
      exit 1
   fi
   NCPATH="$NCHOME";
   printMessage "NCHOME found, uninstalling NCache from location: $NCHOME"
fi
#--------------------------------------------------------------------------------------
if [ ! -f "$NCPATH/lib/Alachisoft.NCache.Common.dll" ]; then 
	echo ""
	printError "Provided installation path is not valid."
	exit 1
fi

if [ ! -f "/usr/lib/ncinfo.xml" ]; then 
	echo ""
	printError "NCache is not installed on this machine or installation is corrupt"
	exit 1
fi
#--------------------------------------------------------------------------------------
if [ -z "$FORCE" ]; then
	reconfirm
fi

#------------------ Verify whether the environment is docker or not --------------------------
if [ -f "/.dockerenv" ] || grep -q "docker" /proc/1/cgroup; then
  ISCONTAINER=true
fi

if [ $ISCONTAINER != true ] ; then
	ip=
	
		ipaddress=$(hostname -I)
		set -- $ipaddress
		one=${1}
		if [ "$one" ] ; then		
			ip=$one
		fi
fi


CURLPATH=$(command -v curl)
if [ -n "$CURLPATH" ]; then	
	PostUnInstallationActivity
fi

rm -f /etc/sudoers.d/ncache

printMessage "Stopping & Removing NCache Daemon(s)..."
stopservice 
uninstall
#--------------------------------------------------------------------------------------
printMessage "NCache uninstalled."
printMessage ""
printMessage "For complete documentation visit the website https://www.alachisoft.com/resources/docs"
printMessage ""
#--------------------------------------------------------------------------------------
exit 0
