#!/bin/sh

currentUser=`whoami`
if [ "$currentUser" != "root" ]
then
        echo "******************************************************************************"
        echo "This script can only be run by the root user. Exiting ..."
        echo "******************************************************************************"
        exit
fi

XMX="-Xmx512m"
#Xmx to use for the agent

eGuser=eguser
#eG user - please make sure that the user account exists

eGgroup=egurkha
#eG user's group

serviceaccount=no
#whether the user we are going to create is a service account or a normal account

eGInstallDir=/opt
#eG install directory

autoRestart=y
#whether the VMagent should auto-restart

licenseAcceptance=y
#licenseAcceptance the license

eGVMAgentPort=60001
#eG VMAgent port

count=`grep "^$eGgroup:" /etc/group | wc -l`
if [ $count -eq 0 ]
then
	if [ ! -f /usr/sbin/groupadd ]
	then
	echo "/usr/sbin/groupadd does not exist. User creation will fail! Exiting ..."
	exit 0
	fi
	/usr/sbin/groupadd $eGgroup
fi

count=`grep "^$eGuser:" /etc/passwd | wc -l`
if [ $count -eq 0 ]
then
	if [ ! -f /usr/sbin/useradd ]
	then
	echo "/usr/sbin/useradd does not exist. User creation will fail! Exiting ..."
	exit 0
	fi
	if [ "$serviceaccount" = "yes" ]
	then
		/usr/sbin/useradd -r -G $eGgroup -g $eGgroup -d $eGInstallDir/egurkha $eGuser 
	else
		/usr/sbin/useradd -G $eGgroup -g $eGgroup -d $eGInstallDir/egurkha $eGuser 
	fi
fi

#run iAgent first
if [ ! -f "iVMAgent_linux" ]
then
        if [ -f "iVMAgent_linux.sh" ]
        then
                cp -f iVMAgent_linux.sh iVMAgent_linux
                chmod 755 iVMAgent_linux
        fi
        if [ -f "iVMAgent_linux_x64.sh" ]
        then
                cp -f iVMAgent_linux_x64.sh iVMAgent_linux_x64
                chmod 755 iVMAgent_linux_x64
        fi
fi
if [ ! -f "iVMAgent_linux_x64.sh" ]
then
        if [ -f "iVMAgent_linux.sh" ]
        then
                cp -f iVMAgent_linux.sh iVMAgent_linux
                chmod 755 iVMAgent_linux
        fi
        if [ -f "iVMAgent_linux_x64.sh" ]
        then
                cp -f iVMAgent_linux_x64.sh iVMAgent_linux_x64
                chmod 755 iVMAgent_linux_x64
        fi
fi

script=
if [ -f "iVMAgent_linux" ]
then
	script="iVMAgent_linux"
elif [ -f "iVMAgent_linux_x64" ]
then
	script="iVMAgent_linux_x64"
fi

if [ -z "$script" ]
then
	echo "Script file iVMAgent_linux not found! ..."
	exit 0
fi

chmod +x $script
`pwd`/$script $eGuser $eGgroup $eGInstallDir $autoRestart $serviceaccount >/dev/null 

#run setup_agent next
chmod +x $eGInstallDir/egvmagent/bin/setup_vmagent
su - $eGuser -c "$eGInstallDir/egvmagent/bin/setup_vmagent $licenseAcceptance $eGVMAgentPort $XMX" > /dev/null

#now start the agent
su - $eGuser -c $eGInstallDir/egvmagent/bin/start_vmagent

echo "eG VMAgent installation and start-up completed."

