#!/bin/sh

# takes dotnethome as param         -d
# takes network ip as param         -i
# takes installpath as param        -p
# takes installation key as param   -k
# takes install mode as param       -m
# takes verbose as param            -v
# takes password as param           -P
# takes force as param              -F
# takes auto start cache as param   -s

#--------------------------------------------------------------------------------------
echo ""
echo "===================================================="
echo "NCache Installation Script"
echo "===================================================="
echo ""
ISCONTAINER=false
PRODUCT="NCache"
PRODUCT_TAR="ncache-ent-install.tar.gz"
DOTNETPATH=
JAVAHOME=
IP=
NCUSER="ncache"
DESTINATION="/opt"
LUCENE_DIST_MAP_PATH="/usr/share/ncache"
VERBOSE=
FORCE=
PASSWORD=
AUTO_START="yes"
INSTALLMODE="0"
CACHE_NAME="defaultCache"
INSTALLATIONTYPE="server"
INSTALLTYPE="op"
ENV="on-prem"
KEY=
EMAIL=
ENABLE_DUMP="false"
ONPREMHOST="https://app.alachisoft.com"
CLOUDHOST="https://cloud.alachisoft.com"
KEYVALID="false"
eval mac1=
eval mac2=
eval mac3=
eval mac4=


framework=".NET 10.0"
DOTNETCOREVER="10.0"
ncv="NC-ENT-5.3.8-64"

#--------------------------------------------------------------------------------------
# ================================== FUNCTIONS ========================================
#--------------------------------------------------------------------------------------
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 ()
{
	printMessage "This script installs $PRODUCT and then configures it"
	printMessage "Providing optional arguments will override default implementation"
	printMessage ""
	printMessage "Usage: install [OPTION] ARG [OPTION] ARG ..."
	printMessage ""
	printMessage "  -m, --install 			Edition of NCache to be installed (server, client, developer)"
	printMessage "  -k, --key  				Installation key provided by alachisoft.com"
	printMessage "  -p, --install_dir 		If not provided then /opt/ncache will be used."
	printMessage "  -s, --start_cache  		To disable auto start of default cache on installation (-s no)"
	printMessage "  -i, --bind_to_ip   		IP address to be used by $PRODUCT, if not provided then it will use the first IP found."
	printMessage "  -d, --dotnethome  		Provide which .NET home directory is to be used."
	printMessage "  -F, --force       		Force create destination directory if provided directory does not exist."
	printMessage "  -P, --password    		Provide password for user '$NCUSER', if user already exists then it will override its password."
	printMessage "  -t, --enableptrace    	Allows users to take memory dumps of processes running under their ownerships. (default is false)"
	printMessage ""
	printMessage "By default this script will install $PRODUCT in the following directory /opt/ncache/, using first found ip-address."
	printMessage ""
	printMessage "Please contact support@alachisoft.com for any technical help."
	printMessage "For complete documentation visit the website https://www.alachisoft.com/resources/docs/"
	printMessage ""
	exit 1
}

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
}

PostInstallationActivity ()
{

NumberOfCPU="$(grep processor /proc/cpuinfo | wc -l)"
NumberofCores="$(nproc --all)"
NumberOfVCPU="$(grep processor /proc/cpuinfo | wc -l)"

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

OSCode="`uname`"
macName="`hostname`"
case $OSCode in
  'Linux')
    OSCode='12'
    ;;
  *)
	OSCode="-1"
	;;
esac

case $INSTALLMODE in
  '0')
    edt='server'
    ;;
   '2')
    edt='developer'
    ;;
  '3')
    edt='client'
    ;;
esac

GetMacAddresses
mi=$OSCode":"$NumberOfCPU":"$NumberofCores":"$NumberOfVCPU":"$Ram
curl --silent --output /dev/null --data "ncv=$ncv&edt=$edt&netv=$framework&mi=$mi&ip=$ip&macName=$macName&mac1=$mac1&mac2=$mac2&mac3=$mac3&mac4=$mac4&env=$ENV" $ONPREMHOST/ncache/nc-getting-started.php &
}

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


#---------------------------------------------------------------------------------------------
#------------------ Verify required version installation of pre requisites -------------------
verify()
{
	REQUIRED_VERSION=`echo $1 | sed -e 's;\.;;g'`
	FOUND_VERSION=`echo $2 | sed -e 's;\.;;g'`
	
	if [ $FOUND_VERSION -ge $REQUIRED_VERSION ]
	then
		VERIFIED="1"
	else
		VERIFIED="0"
	fi
}
#--------------------------------------------------------------------------------------
#--- Start of execution
#--------------------------------------------------------------------------------------

while [ "$1" != "" ]; do
    case $1 in
	 -d | --dotnethome )	shift
			 DOTNETPATH=$1
			 ;;
			
	-i | --bind_to_ip )	shift
			IP=$1
			;;

	-p | --install_dir )	shift
			DESTINATION=$1
			;;	

	-k | --key )	shift
			KEY=$1
			;;
			
	-m | --install )	shift
			INSTALLMODE=$(echo "$1" | tr '[:upper:]' '[:lower:]')
			if [ $INSTALLMODE = "client" ] || [ $INSTALLMODE = "3" ] ; then
				INSTALLATIONTYPE="client"
				CACHE_NAME="defaultLocalCache"
				INSTALLMODE="3";
			elif [ $INSTALLMODE = "developer" ] || [ $INSTALLMODE = "2" ] ; then
				INSTALLATIONTYPE="developer"
				CACHE_NAME="defaultCache"
				INSTALLMODE="2";
				
			else
				INSTALLATIONTYPE="server"
				CACHE_NAME="defaultCache"
				INSTALLMODE="0";
			fi
			;;
			
	-P | --password )	shift
			PASSWORD=$1
			NEWPASS="true"
			;;
			
	--onpremhost )	shift
			ONPREMHOST=$1
			;;
			
	--cloudhost )	shift
			CLOUDHOST=$1
			;;

	-s | --start_cache ) shift
			AUTO_START=$1
			;;

	-t | --enableptrace ) shift
			ENABLE_DUMP=$1
			;;
			
	-F | --force )
			FORCE="true"
			;;
			
	-v | --verbose )
			VERBOSE="true"
			;;

	-h | --help )
			usage
			exit
			;;
			
	* )
			usage
			exit 1
    esac
    shift
done

printMessage "Executing script from user: $USER"

#--------------------------------------------------------------------------------------
# Ensure that NCache is not already installed
if [  -f "/usr/lib/ncinfo.xml" ]; then 
	echo ""
	printError "Either NCache is already installed or wasn't uninstalled properly."
	exit 1
fi
#--------------------------------------------------------------------------------------
# Make sure only root user can run our script
if [ "$(id -u)" != "0"  ] ; then
   printError "Installation requires root privileges."
   exit 1
fi

if [ ! -d $DESTINATION ] ; then
	if [ ! -z $FORCE ] ; then

		printMode "Creating $DESTINATION"
		mkdir -p $DESTINATION

		if [ ! -d $DESTINATION ] ; then
			printError "Unable to create $DESTINATION."
			exit 1
		fi	
		
	else
		printError "$DESTINATION does not exist (Using setup with --force parameter will create it automatically)"
		exit 1
	fi
fi

printMode "Creating $LUCENE_DIST_MAP_PATH"
mkdir -p $LUCENE_DIST_MAP_PATH/lucene-index
#--------------------------------------------------------------------------------------
#--- Check all the required parameters
ERROR_EXISTS=

if [ -z "$KEY" ] ; then
	printError "-k (key) Please provide the product installation key or please contact support@alachisoft.com"
	ERROR_EXISTS="yes";
fi

if [ -z "$PASSWORD" ] ; then
    while [ -z "$PASSWORD" ] ; do
        printf "Enter password for user '%s': " "$NCUSER"
        read PASSWORD

        if [ -z "$PASSWORD" ] ; then
            echo "Password cannot be empty."
        fi
    done
fi


if [ "$ERROR_EXISTS" ] ; then
	exit 1;
fi


#--------------------------------------------------------------------------------------
# INSTALLMODE should be valid
case "$INSTALLMODE" in
	"0" )
		INSTALLMODE="0"
		printMode "Install Mode: $INSTALLMODE"
		;;
	"2" )
	INSTALLMODE="2"
	printMode "Install Mode: $INSTALLMODE"
	;;
	"3" )
		INSTALLMODE="3"
		printMode "Install Mode: $INSTALLMODE"
		;;
	* )
		printError "Install Mode invalid, please provide from the following: server/client"
		exit 1;
esac

#--------------------------------------------------------------------------------------
# Setting IP to be used for caches configuration files
if [ $ISCONTAINER != true ] ; then
	ip=
	if [ "$IP" ] ; then
		printMessage "Validating ip-address : $IP ..."
		ipaddress=$(hostname -I | grep -w "$IP" 2>/dev/null)
		if [ "$ipaddress" ] ; then
			printMessage "$IP is a valid ip-address"
			ip=$IP
		else
			printError "$IP is not a valid ip-address, this machine does not contain ip-address: $IP"
			exit 1;
		fi
	else
		ipaddress=$(hostname -I)
		set -- $ipaddress
		one=${1}
		if [ "$one" ] ; then		
			ip=$one
			printMessage "Selected ip-address: $ip"		
		else
			printError "Unable to find a valid ip-address."
			exit 1;
		fi
	fi
fi

#----------------------------------------------------------------------------------------------------
#--- Verify required .NET version, if unable to find the required .NET version then exit installation
VERSION=



if [ $DOTNETPATH ] && [ -d $DOTNETPATH ] ; then
    DOTNETPATH="$DOTNETPATH/dotnet"
fi

if [ -z $DOTNETPATH ] ; then
    DOTNETPATH=$(command -v dotnet)
fi

if [ $DOTNETPATH ] ; then
        versions=$($DOTNETPATH --list-runtimes | cut -f 2 -d ' ')
fi

for version in $versions
do
        v=$(echo $version | cut -c-4)
        verify $DOTNETCOREVER $v
        VERSION=$version
        if [ "$VERIFIED" = "1" ]
                then
                break;
        fi
done

if [ "$VERIFIED" = "1" ]
then
        printMessage ".NET version $DOTNETCOREVER found."
        versionFound=$VERSION
else
        #installDOTNET
        #VERSION="10.0"
        printError "Unable to find .NET 10.0 runtime on local machine. For more details about the pre-reqs, use this URL\n\thttps://www.alachisoft.com/resources/docs/ncache/install-guide/linux-pre-reqs.html"
        exit 1
fi

POWERSHELLPATH=$(command -v pwsh)
VERIFIED="0"
if [ "$POWERSHELLPATH" ] ; then
    PSVERSION=$($POWERSHELLPATH -NoLogo -NoProfile -Command '$PSVersionTable.PSVersion.ToString()')

    REQUIRED_VERSION="7.6.2"

    if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$PSVERSION" | sort -V | head -n1)" = "$REQUIRED_VERSION" ]; then
        VERIFIED=1
    fi
fi

if [ "$VERIFIED" = "1" ]
then
    printMessage "PowerShell version $PSVERSION found."
else
    printError "Unable to find PowerShell 7.6.2 or later on local machine. Please install PowerShell 7.6.2 or newer."
    exit 1
fi
#--------------------------------------------------------------------------------------
#-------------- Verify Java required version  installed at Specified path -------------
verifyJava()
{
	JHOME=$1
	REQUIRED_VERSION=$JAVAVER
	
	if [ -z $JHOME ]; then
	
		# Check if 'java' executable is available
		VERIFY_JAVA=$(echo $(command -v java))
		if [ -z $VERIFY_JAVA ]; then
			printError "Before installing NCache, please make sure that you have Java 17 installed on your system. If Java 17 is already installed, please use '--javahome' or '-j' to provide the path where Java 17 is installed."
			exit 1
		fi
		JHOME=$(readlink -f $VERIFY_JAVA | sed "s:/bin/java::")
	fi
	printMessage "Validating Java..."	

	# Transform the required version string into a number that can be used in comparisons

	REQUIRED_VERSION=`echo $JAVAVER | sed -e 's;\.;0;g'`
	# Check JAVA_HOME directory to see if Java version is adequate
	if [ $JHOME ]
	then
			JAVA_EXE=$JHOME/bin/java
			JAVAVERSION=$($JAVA_EXE -version 2>&1 | grep -oP '(?<=version ")[0-9]+')
			JVERSION=`echo $JAVAVERSION | sed -e 's;\.;0;g'`
			REQUIRED_VERSION=`echo $REQUIRED_VERSION | sed -e 's;\.;0;g'`
			if [ $JVERSION ]
			then
				if [ $JVERSION -ge $REQUIRED_VERSION ]
				then
					printMessage "Correct Java version is verified."
					JAVAVER=$JAVAVERSION
					JAVAHOME=$JHOME
					return
				fi
			fi
			JAVAHOME=
			printError "Before installing NCache, please make sure that you have Java 17 installed on your system and that the 'JAVA_HOME' environment variable is correctly set"
			exit 1
	fi
}
#--------------------------------------------------------------------------------------
#--- Verify required Java version, if unable to find the required Java version then exit installation
correctPath=
version=

# verifyJava $JAVAHOME

#--------------------------------------------------------------------------------------
# Creating user for NCache... 
printMessage "Checking if user '$NCUSER' already exists ..."
userExists=

if [ -z $(id -u $NCUSER 2>/dev/null) ] ; then
	printMessage "Creating '$NCUSER' user ..."
	useradd -m "$NCUSER"
	passwd $NCUSER 2>/dev/null <<EOF
$PASSWORD
$PASSWORD
EOF
	printMessage "User successfully created."
	printMessage "Password of '$NCUSER' user is: $PASSWORD"
else
	printMessage "User '$NCUSER' already exists."
	printMessage ""
	userExists="yes"

	if [ "$NEWPASS" ] ; then
	passwd $NCUSER 2>/dev/null <<EOF
$PASSWORD
$PASSWORD
EOF
	fi
fi

#--------------------------------------------------------------------------------------
# All values specified, proceeding with installation
printMessage ""
printMessage "--------------------------------------------------"
printMessage "Proceeding installation with the following values:"
printMessage "--------------------------------------------------"
printMessage "Installation Key      : $KEY"
printMessage "Destination           : $DESTINATION/ncache"
printMessage "Lucene Index Path     : $LUCENE_DIST_MAP_PATH"
printMessage ".NET Home             : $DOTNETPATH"
printMessage ".NET Version          : $VERSION"
printMessage "IP Address            : $ip"
printMessage "$PRODUCT user           : $NCUSER"
printMessage "Install Mode          : $INSTALLATIONTYPE"
printMessage "--------------------------------------------------"
printMessage ""

#--------------------------------------------------------------------------------------
# Extract installation tar.gz
printMode "Extracting setup ..."
tar -zxf "$PRODUCT_TAR" -C $DESTINATION

#--------------------------------------------------------------------------------------
# Copying post installation README file
sed -i "s|<IP>|$ip|g" $DESTINATION/ncache/README

#--------------------------------------------------------------------------------------
# Verify Key and Cloud Machine...
chmod +x ${DESTINATION}/ncache/lib/NActivate.dll
chmod +x ${DESTINATION}/ncache/lib/Alachisoft.NCache.License.NetCore.dll
chmod +x ${DESTINATION}/ncache/lib/license/Alachisoft.NCache.License.NetCore.dll

 $DOTNETPATH ${DESTINATION}/ncache/lib/license/Alachisoft.NCache.License.NetCore.dll $KEY $CLOUDHOST > /dev/null
res=$?
if [ $res = 0 ] ;	then
	printError "Invalid installation key. Recheck key or please contact support@alachisoft.com\n"
	rm -r $DESTINATION/ncache 
	exit 1
elif [ $res = 3 ] ; then
	printError "NCache cannot be installed on Azure virtual Machine. Please use NCache Enterprise Software (https://azuremarketplace.microsoft.com/en-us/marketplace/apps/ncache.ent-linux) available on Azure Marketplace. Please contact sales@alachisoft.com if you have any questions.\n"
	rm -r $DESTINATION/ncache 
	exit 1
elif [ $res = 4 ] ; then
	printError "NCache cannot be installed on AWS virtual Machine. Please use NCache Enterprise Software (https://aws.amazon.com/marketplace/pp/prodview-syoynu6xuh4j6) available on AWS Marketplace. Please contact sales@alachisoft.com if you have any questions.\n"
	rm -r $DESTINATION/ncache 
	exit 1
elif [ $res = 5 ] ; then
	INSTALLTYPE="az"
	ENV="azure"
elif [ $res = 6 ] ; then
	INSTALLTYPE="aw"
	ENV="aws"
elif [ $res = 7 ] ; then
	INSTALLTYPE="azs"
	ENV="azure-saas"
elif [ $res = 8 ] ; then
	INSTALLTYPE="aws"
	ENV="aws-saas"	
fi

EMAIL=$("$DOTNETPATH" "${DESTINATION}/ncache/lib/license/Alachisoft.NCache.License.NetCore.dll" --get-email "$KEY")
email_result=$?
if [ "$email_result" != "1" ] || [ -z "$EMAIL" ] ; then
	printError "Unable to read email from the installation key."
	rm -r "$DESTINATION/ncache"
	exit 1
fi
#--------------------------------------------------------------------------------------
# Verify Cloud Machine...
# if [ $CLOUDKEY = "false" ] ; then
	# if [ $INSTALLMODE = "0" ] ; then
		# output=`curl --silent -s -H Metadata:true --noproxy "*" "http://169.254.169.254/metadata/instance?api-version=2021-02-01" --connect-timeout 2`
		# if [ ! -z "$output" ] ; then
			# if [[ $output == *"AzurePublicCloud"* ]] ; then
				# printError "NCache cannot be installed on Azure virtual Machine. Please use NCache Enterprise Software available on Azure Marketplace. Please contact sales@alachisoft.com if you have any questions."
				# rm -r $DESTINATION/ncache 
				# exit 1
			# else
				# TOKEN=`curl --silent -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" --connect-timeout 2`
				# awsRes=`curl --silent  -H "X-aws-ec2-metadata-token: $TOKEN" "http://169.254.169.254/latest/dynamic/instance-identity/document" --connect-timeout 2`
				# if [ ! -z "$awsRes" ] ; then
					# if [[ $awsRes == *"ami-"* ]] ; then
						# printError "NCache cannot be installed on AWS virtual Machine. Please use NCache Enterprise Software available on AWS Marketplace. Please contact sales@alachisoft.com if you have any questions."
						# rm -r $DESTINATION/ncache 
						# exit 1
					# fi
				# fi
			# fi
		# fi
	# fi
# fi

#--------------------------------------------------------------------------------------
printMode "Switching to directory $DESTINATION/ncache/bin/service ..."
cd $DESTINATION/ncache/bin/service

if [ $INSTALLMODE = "3" ] ; then

	mv $DESTINATION/ncache/bin/service/client/* $DESTINATION/ncache/bin/service/
fi

rm -r $DESTINATION/ncache/bin/service/client

if [ $ISCONTAINER != true ] ; then
	printMode "Setting ip-address in Alachisoft.NCache.Daemon.dll.config ..."
	sed -i "s/<IP>/$ip/g" "Alachisoft.NCache.Daemon.dll.config"

	printMode "Setting ip-address in Alachisoft.NCache.BridgeDaemon.dll.config ..."
	sed -i "s/<IP>/$ip/g" "Alachisoft.NCache.BridgeDaemon.dll.config"

fi

if [ $INSTALLMODE = "0" ] ; then
	sed -i "s/<FeatureUsageLogging>/true/g" "Alachisoft.NCache.Daemon.dll.config"
	sed -i "s/<FeatureUsageStats>/true/g" "Alachisoft.NCache.Daemon.dll.config"
else
	sed -i "s/<FeatureUsageLogging>/false/g" "Alachisoft.NCache.Daemon.dll.config"
	sed -i "s/<FeatureUsageStats>/false/g" "Alachisoft.NCache.Daemon.dll.config"
fi

printMode "Switching to directory $DESTINATION/ncache/config ..."
cd $DESTINATION/ncache/config

if [ $ISCONTAINER != true ] ; then
	printMode "Setting ip-address in bridge.ncconf ..."
	sed -i "s/<IP>/$ip/g" "bridge.ncconf"

	printMode "Setting ip-address to $ip ..."

	printMode "Setting ip-address in config.ncconf ..."
	sed -i "s/<IP>/$ip/g" "config.ncconf"
	
fi

printMode "Setting install-dir in ncinfo.xml ..."
loc="$DESTINATION/ncache/"

sed -i "s|<INSTALLDIR>|$loc|g" "ncinfo.xml"

printMode "Setting install-type in ncinfo.xml ..."
sed -i "s/<INSTALLTYPE>/$INSTALLTYPE/g" "ncinfo.xml"

printMode "Setting email in ncinfo.xml ..."
EMAIL_XML=$(printf '%s' "$EMAIL" | sed \
	-e 's/&/\&amp;/g' \
	-e 's/</\&lt;/g' \
	-e 's/>/\&gt;/g' \
	-e 's/[|\\&]/\\&/g')
sed -i "s|<EMAIL>|$EMAIL_XML|g" "ncinfo.xml"

INSTALLCODE=

case $INSTALLMODE in
	"0")
		INSTALLCODE="p2exJ2fWV2GQ4DGwg7cSMxP3N5a3" 
		;;
	"3" ) 
		INSTALLCODE="p2exR2fWV2GQ4DGwg7cSMxP3N5a3"                     	             
		;;
	"2")
		INSTALLCODE="p2exN9f2ceDwAaB0pyIjY+cHhkc="
		;;
esac

printMode "Setting install-code in ncinfo.xml ..."
sed -i "s/<INSTALLCODE>/$INSTALLCODE/g" "ncinfo.xml"

cp $DESTINATION/ncache/config/ncinfo.xml /usr/lib
rm $DESTINATION/ncache/config/ncinfo.xml

if [ ! -f /usr/lib/nclicense.xml ]; then
    cp $DESTINATION/ncache/config/nclicense.xml /usr/lib 
fi

rm $DESTINATION/ncache/config/nclicense.xml

printMode "Changing directory to $DESTINATION/ncache"
loc="$DESTINATION/ncache"
cd $DESTINATION/ncache/

#--------------------------------------------------------------------------------------
# Prepare PowerShell Tools...

cd $DESTINATION/ncache/lib/tools/ncacheps

sed -i "s|<NCHOME>|$loc|g" ncacheps.psd1

PWSHPATH=$(command -v pwsh)

if [ -n "$PWSHPATH" ]
then
    chmod +x $DESTINATION/ncache/lib/tools/ncacheps/*

    # ---------------------------------------------------
    # Get real PowerShell install root (PSHOME)
    # ---------------------------------------------------
    PSHOME=$($PWSHPATH -NoLogo -NoProfile -Command '$PSHOME')

    if [ -n "$PSHOME" ]
    then
        MODULE_DIR="$PSHOME/Modules"

        # Create symlink into PowerShell module directory
        ln -sf "$DESTINATION/ncache/lib/tools/ncacheps" "$MODULE_DIR/ncacheps"
    else
        echo "Failed to detect PSHOME"
        exit 1
    fi
fi

#--------------------------------------------------------------------------------------
rm -f $DESTINATION/ncache/lib/*.CachingModule.dll

#--------------------------------------------------------------------------------------
#--- Change ownership of ncache related files and folder
printMode "Making $NCUSER the owner of $DESTINATION/ncache ..."
chown -R $NCUSER:$NCUSER $LUCENE_DIST_MAP_PATH
chown -R $NCUSER:$NCUSER $DESTINATION/ncache

chmod -R +664 $DESTINATION/ncache/config
chmod -R a+rwx $DESTINATION/ncache/log-files
chmod -R +s $DESTINATION/ncache/log-files

chown  	$NCUSER:$NCUSER /usr/lib/ncinfo.xml
chown  	$NCUSER:$NCUSER /usr/lib/nclicense.xml
#--------------------------------------------------------------------------------------
#--- CreateDump Changes

cp $DESTINATION/ncache/lib/libmscordaccore.so $DESTINATION/ncache/bin/management/
cp $DESTINATION/ncache/lib/libmscordaccore.so $DESTINATION/ncache/bin/service/

cd $DESTINATION
#---------------------------------------------------------------------------------------
printMode "Setting INSTALLDIR in ncached.service ..."

if [ $ISCONTAINER != true ] ; then
	# Installing NCache Service...
	printMode "Changing directory to $DESTINATION/ncache/bin/service"
	cd $DESTINATION/ncache/bin/service
	printMode "Installing service"
	
	printMode "Setting DOTNETHOME in ncached.service ..."
    sed -i "s|<DOTNETHOME>|$DOTNETPATH|g" "ncached.service"

	printMode "Setting INSTALLDIR in ncached.service ..."
	sed -i "s|<INSTALLDIR>|$loc|g" "ncached.service"

	cp $DESTINATION/ncache/bin/service/ncached.service /etc/systemd/system
	rm $DESTINATION/ncache/bin/service/ncached
	rm $DESTINATION/ncache/bin/service/ncached.service
	printMode "Daemon Coppied Successfully."

	# Installing Loader Service...
	#printMode "Changing directory to $DESTINATION/ncache/bin/service"
	# cd $DESTINATION/ncache/bin/service
	# printMode "Installing loader service"

	# printMode "Setting INSTALLDIR in ncacheloaderd.service ..."
	# sed -i "s|<INSTALLDIR>|$loc|g" "ncacheloaderd.service"

	# cp $DESTINATION/ncache/bin/service/ncacheloaderd.service /etc/systemd/system
	# rm $DESTINATION/ncache/bin/service/ncacheloaderd
	# rm $DESTINATION/ncache/bin/service/ncacheloaderd.service
	# printMode "Loader Daemon Coppied Successfully."	
	
	# # Installing Cloud Service...
	# printMode "Changing directory to $DESTINATION/ncache/bin/service"
	# cd $DESTINATION/ncache/bin/service
	# printMode "Installing Cloud service"
	
	# printMode "Setting DOTNETHOME in ncachecloud.service ..."
    # sed -i "s|<DOTNETHOME>|$DOTNETPATH|g" "ncachecloud.service"

	# printMode "Setting INSTALLDIR in ncachecloud.service ..."
	# sed -i "s|<INSTALLDIR>|$loc|g" "ncachecloud.service"

	# cp $DESTINATION/ncache/bin/service/ncachecloud.service /etc/systemd/system
	# rm $DESTINATION/ncache/bin/service/ncachecloud.service
	# printMode "Cloud Daemon Coppied Successfully."
	
	# Installing Bridge Service...
	printMode "Changing directory to $DESTINATION/ncache/bin/service"
	cd $DESTINATION/ncache/bin/service
	printMode "Installing bridge service"
	
	printMode "Setting DOTNETHOME in ncachebridged.service ..."
    sed -i "s|<DOTNETHOME>|$DOTNETPATH|g" "ncachebridged.service"

	printMode "Setting INSTALLDIR in ncachebridged.service ..."
	sed -i "s|<INSTALLDIR>|$loc|g" "ncachebridged.service"

	cp $DESTINATION/ncache/bin/service/ncachebridged.service /etc/systemd/system
	rm $DESTINATION/ncache/bin/service/ncachebridged
	rm $DESTINATION/ncache/bin/service/ncachebridged.service
	printMode "Bridge Daemon Coppied Successfully."
	
	# Installing NCExecution Service...
	#-----------
	printMode "Changing directory to $DESTINATION/ncache/bin/service"
	cd $DESTINATION/ncache/bin/service
	printMode "Installing NCExecution service"
	
	printMode "Setting DOTNETHOME in ncexecution.service ..."
    sed -i "s|<DOTNETHOME>|$DOTNETPATH|g" "ncexecution.service"

	printMode "Setting INSTALLDIR in ncexecution.service ..."
	sed -i "s|<INSTALLDIR>|$loc|g" "ncexecution.service"

	cp $DESTINATION/ncache/bin/service/ncexecution.service /etc/systemd/system
	rm $DESTINATION/ncache/bin/service/ncexecution.service
	printMode "NCExecution Daemon Coppied Successfully."
	
else

	cd $DESTINATION/ncache/bin/service/
	printMode "Installing service"
	
	printMode "Setting DOTNETHOME in ncached ..."
    sed -i "s|<DOTNETHOME>|$DOTNETPATH|g" "ncached"

	printMode "Setting INSTALLDIR in ncached ..."
	sed -i "s|<INSTALLDIR>|$loc|g" "ncached"

	cp $DESTINATION/ncache/bin/service/ncached /etc/init.d/
	chmod +x /etc/init.d/ncached
	rm $DESTINATION/ncache/bin/service/ncached
	rm $DESTINATION/ncache/bin/service/ncached.service
	printMode "Daemon Coppied Successfully."

	# Installing Loader Service...
	# printMode "Changing directory to $DESTINATION/ncache/bin/service"
	# cd $DESTINATION/ncache/bin/service
	# printMode "Installing loader service"

	# printMode "Setting INSTALLDIR in ncacheloaderd.service ..."
	# sed -i "s|<INSTALLDIR>|$loc|g" "ncacheloaderd"

	# cp $DESTINATION/ncache/bin/service/ncacheloaderd /etc/init.d/
	# chmod +x /etc/init.d/ncacheloaderd
	# rm $DESTINATION/ncache/bin/service/ncacheloaderd
	# rm $DESTINATION/ncache/bin/service/ncacheloaderd.service
	# printMode "Loader Daemon Coppied Successfully."
	
	# # Installing Cloud Service...
	# printMode "Changing directory to $DESTINATION/ncache/bin/service"
	# cd $DESTINATION/ncache/bin/service
	# printMode "Installing Cloud service"

	# printMode "Setting INSTALLDIR in ncachecloud ..."
	# sed -i "s|<INSTALLDIR>|$loc|g" "ncachecloud"

	# cp $DESTINATION/ncache/bin/service/ncachecloud /etc/init.d/
	# chmod +x /etc/init.d/ncachecloud
	
	# rm $DESTINATION/ncache/bin/service/ncachecloud.service
	# printMode "Cloud Daemon Coppied Successfully."
	
	# Installing Bridge Service...
	printMode "Changing directory to $DESTINATION/ncache/bin/service"
	cd $DESTINATION/ncache/bin/service
	printMode "Installing bridge service"
	
	printMode "Setting DOTNETHOME in ncachebridged ..."
    sed -i "s|<DOTNETHOME>|$DOTNETPATH|g" "ncachebridged"

	printMode "Setting INSTALLDIR in ncachebridged ..."
	sed -i "s|<INSTALLDIR>|$loc|g" "ncachebridged"

	cp $DESTINATION/ncache/bin/service/ncachebridged /etc/init.d/
	chmod +x /etc/init.d/ncachebridged
	
	rm $DESTINATION/ncache/bin/service/ncachebridged
	rm $DESTINATION/ncache/bin/service/ncachebridged.service
	printMode "Bridge Daemon Coppied Successfully."		
	
fi

#--------------------------------------------------------------------------------------
#--- Execute license ...
if [ $INSTALLMODE != "2" ] ; then

	if [ $INSTALLMODE = "0" ] ; then
		$DOTNETPATH ${DESTINATION}/ncache/lib/license/Alachisoft.NCache.License.NetCore.dll $KEY $INSTALLMODE $ONPREMHOST $CLOUDHOST
	elif [ $INSTALLMODE = "3" ] ; then
		$DOTNETPATH ${DESTINATION}/ncache/lib/license/Alachisoft.NCache.License.NetCore.dll $INSTALLMODE
	fi
	
	result=$?
	if [ $result = "0" ] ; then
		printError "Invalid installation key. Recheck key or please contact support@alachisoft.com"
		rm -r $DESTINATION/ncache 
		rm -r /usr/lib/ncinfo.xml
		exit 1
	elif [ $result = "2" ] ; then 
		KEYVALID="true"
	elif [ $result = "3" ] ; then 
		printMode "HTTP_RESPONSE : ERROR "
		rm -r $DESTINATION/ncache 
		rm -r /usr/lib/ncinfo.xml
		exit 1
	elif [ $result = "4" ] ; then 
		printMode "HTTP_RESPONSE : NotUpdated_CouldNotConnect"
	elif [ $result = "5" ] ; then 
		printMode "HTTP_RESPONSE : NotUpdated"
	elif [ $result = "6" ] ; then 
		printMode "HTTP_RESPONSE : Updated"
	fi
fi

#--------------------------------------------------------------------------------------
#--- Allowing ncache to run services ...
SUDOERS_FILE="/etc/sudoers.d/ncache"
cat > "$SUDOERS_FILE" <<'EOF'
Cmnd_Alias NCACHED_SYSTEMCTL = \
    /usr/bin/systemctl start ncached.service, \
    /usr/bin/systemctl stop ncached.service, \
    /usr/bin/systemctl restart ncached.service, \
	/usr/bin/systemctl status ncached.service, \
    /usr/bin/systemctl start ncached, \
    /usr/bin/systemctl stop ncached, \
    /usr/bin/systemctl restart ncached, \
    /usr/bin/systemctl status ncached

Cmnd_Alias NCACHEBRIDGED_SYSTEMCTL = \
    /usr/bin/systemctl start ncachebridged.service, \
    /usr/bin/systemctl stop ncachebridged.service, \
    /usr/bin/systemctl restart ncachebridged.service, \
    /usr/bin/systemctl status ncachebridged.service, \
    /usr/bin/systemctl start ncachebridged, \
    /usr/bin/systemctl stop ncachebridged, \
    /usr/bin/systemctl restart ncachebridged, \
    /usr/bin/systemctl status ncachebridged

Cmnd_Alias NCEXECUTION_SYSTEMCTL = \
    /usr/bin/systemctl start ncexecution.service, \
    /usr/bin/systemctl stop ncexecution.service, \
    /usr/bin/systemctl restart ncexecution.service, \
    /usr/bin/systemctl status ncexecution.service, \
    /usr/bin/systemctl start ncexecution, \
    /usr/bin/systemctl stop ncexecution, \
    /usr/bin/systemctl restart ncexecution, \
    /usr/bin/systemctl status ncexecution

ncache ALL=(root) NOPASSWD: \
    NCACHED_SYSTEMCTL, \
    NCACHEBRIDGED_SYSTEMCTL, \
    NCEXECUTION_SYSTEMCTL
EOF

chmod 0440 "$SUDOERS_FILE"

#--------------------------------------------------------------------------------------
#--- Starting ncache service ...

if [ $ISCONTAINER != true ] ; then
	printMessage "Starting NCache service ..."
	systemctl daemon-reload
	systemctl enable ncached.service
	systemctl start ncached.service
	
	# systemctl enable ncacheloaderd.service
	# systemctl start ncacheloaderd.service
	
	systemctl enable ncachebridged.service
	# systemctl enable ncachecloud.service
	systemctl enable ncexecution.service
	
	if [ $INSTALLMODE = "0" ] ; then
		
		systemctl start ncachebridged.service	
	fi
	
	systemctl start ncexecution.service	
	
	rm -r ${DESTINATION}/ncache/lib/license

	
	if [ $ENABLE_DUMP = "true" ] ; then
		echo 0 | tee /proc/sys/kernel/yama/ptrace_scope > /dev/null
	fi
	
	printMessage "NCacheServer.BindToClientServerIP = $ip  " 
	printMessage "NCacheServer.BindToClusterIP      = $ip  " 
	printMessage "NCacheServer.Port                 = 9800 " 
	printMessage "NCacheServer.ManagementPort       = 9803 " 
	NCPID=$(pgrep -f  Alachisoft.NCache.Daemon)
	if [ $NCPID ] ; then
		printMessage "NCache service started successfully with following process-id (pid): $NCPID" 
	else
		printMessage "Job for ncached.service failed because the control process exited with error code.\nSee \"systemctl status ncached.service\" and \"journalctl -xe\" for details."
	fi
	
	if [ "$AUTO_START" = "yes" ] ; then
		PWSHPATH=$(command -v pwsh)

		"$PWSHPATH" -NoLogo -NoProfile -Command "
			Start-Cache -Name '$CACHE_NAME'
		" > /dev/null
	fi
	
	CURLPATH=$(command -v curl)
	if [ -n "$CURLPATH" ] ; then	
		PostInstallationActivity
	fi
	
	if [ $INSTALLMODE != "3" ] ; then
		
		printMessage ""
		printMessage "To manage caches and clusters with NCache Management Center, use this URL:"
		printMessage "	http://${ip}:9801"
	fi
		
	
fi

printMessage ""
printMessage "Read more details below:"
printMessage ""
printMessage "	https://www.alachisoft.com/resources/docs/ncache/getting-started.html"
printMessage "	https://www.alachisoft.com/resources/docs/ncache/admin-guide/"
printMessage "	https://www.alachisoft.com/resources/docs/ncache/prog-guide/"
printMessage "	https://github.com/Alachisoft/NCache-Samples/"
