#!/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/manageengine/uems_agent/uemsagentsettings.json"

	if [[ -e "/etc/desktopcentralagent/dcagentsettings.json" ]]; then
		product_settings_file="/etc/desktopcentralagent/dcagentsettings.json"
	fi

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

		existing_agent_dir="/usr/local" # Default Agent Install Directory

		if [[ -e "$existing_agent_dir/desktopcentralagent/RemoveDCAgent.sh" ]] || [[  -e "$existing_agent_dir/desktopcentralagent/RemoveUEMSAgent.sh" ]]; then
			existing_agent_dir="$existing_agent_dir/desktopcentralagent"
		elif [[ -e "$existing_agent_dir/uems_agent/RemoveUEMSAgent.sh" ]]; then
			existing_agent_dir="$existing_agent_dir/uems_agent"
		elif [[ -e "$existing_agent_dir/manageengine/uems_agent/RemoveUEMSAgent.sh" ]]; then
			existing_agent_dir="$existing_agent_dir/manageengine/uems_agent"
		elif [[ -e "$existing_agent_dir/pmpagent/RemovePMPAgent.sh" ]]; then
			existing_agent_dir="$existing_agent_dir/pmpagent"
		else
			echo "Unable to find agent installed directory."
			break
		fi
	fi

	# Removing the old agent
    #

    if [[ -e "$existing_agent_dir/RemoveDCAgent.sh" ]]; then 
		chmod +x "$existing_agent_dir/RemoveDCAgent.sh"
    	echo "Uninstalling Existing Version of Agent"
   		"$existing_agent_dir/RemoveDCAgent.sh"
	elif [[ -e "$existing_agent_dir/RemoveUEMSAgent.sh" ]]; then
		chmod +x "$existing_agent_dir/RemoveUEMSAgent.sh"
	    echo "Uninstalling Existing Version of Agent"
   		"$existing_agent_dir/RemoveUEMSAgent.sh"
   	elif [[ -e "$existing_agent_dir/RemovePMPAgent.sh" ]]; then
		chmod +x "$existing_agent_dir/RemovePMPAgent.sh"
	    echo "Uninstalling Existing Version of Agent"
   		"$existing_agent_dir/RemovePMPAgent.sh"
	fi

	# Installing new agent
    #

   	cd /dcAgentFiles

   	if [[ -e /dcAgentFiles/DesktopCentral_LinuxAgent.bin ]]; then 
		chmod +x /dcAgentFiles/DesktopCentral_LinuxAgent.bin
		/dcAgentFiles/DesktopCentral_LinuxAgent.bin
	else
		chmod +x /dcAgentFiles/UEMS_LinuxAgent.bin
		/dcAgentFiles/UEMS_LinuxAgent.bin
	fi

	cat /etc/crontab | grep -v LinuxAgentInstaller.bash >>/etc/crontab_temp
    cp /etc/crontab_temp /etc/crontab
    rm /etc/crontab_temp

    rm -rf /dcAgentFiles


done
errorFunc(){
 return $errorCode
}
errorFunc
