#!/bin/bash

# Description   :   This script is used to remove the existing DC agent and install the new one..
#
# Maintainer    :   ManageEngine Desktop Central <desktopcentral-support@manageengine.com>

errorCode=2

euid=$(id -u)
for i in 1
    do

	#check root access
	if [ $euid -ne 0 ]; then
	   echo "This script must be run as root"
	   break
	fi
	product_settings_file="/etc/desktopcentralagent/dcagentsettings.json"


	if [ -e $product_settings_file ]; then
		existing_agent_dir=$(cat $product_settings_file | grep "DIRECTORY_PATH" | cut -f 2 -d ":" | cut -f 2 -d "\"" | rev | cut -f 1 -d "/" --complement | rev)
	fi

	if [[ ! -e $existing_agent_dir ]]; then
		if [ -e /usr/bin/dcservice ]; then
			existing_agent_dir=$(ls -l /usr/bin/ | grep dcservice | cut -d ">" -f 2 | rev | tail -c +35 | rev | cut -d " " -f 2)
		fi
	fi

	if [[ ! -e $existing_agent_dir ]]; then
		existing_agent_dir="/usr/local" # Default Agent Install Directory
	fi

	# Removing the old agent
    #
    chmod +x "$existing_agent_dir/desktopcentralagent/RemoveDCAgent.sh"
    echo "Uninstalling Existing Version of Agent"
   	"$existing_agent_dir/desktopcentralagent/RemoveDCAgent.sh"

   	cd /dcAgentFiles

	chmod +x /dcAgentFiles/UEMS_LinuxAgent.bin
	/dcAgentFiles/UEMS_LinuxAgent.bin
	
	cat /etc/crontab | grep -v LinuxAgentInstaller.sh >>/etc/crontab_temp
    cp /etc/crontab_temp /etc/crontab
    rm /etc/crontab_temp

    rm -rf /dcAgentFiles


done
errorFunc(){
 return $errorCode
}
errorFunc
