#!/bin/bash
#set -x
BINARY_TAR_FILE=remoteinstaller.tar.gz
INSTALL_FILE_LENGTH=515
SITE24X7_AGENT_INSTALL_LOWERCASE_MESSAGE='install'
SITE24X7_AGENT_INSTALLING_MESSAGE='Site24x7 Linux Server Monitoring Agent Remote Installation Started'
SITE24X7_AGENT_REINSTALLING_MESSAGE='Site24x7 Linux Server Monitoring Agent Remote Installation Started'
SITE24X7_AGENT_UNINSTALLING_MESSAGE='Site24x7 Linux Server Monitoring Agent Remote Uninstallation Started'
AGENT_INSTALLER_STOPPED_MESSAGE='Site24x7 Linux Server Monitoring Agent Remote Installation Stopped'
SITE24X7_AGENT_INSTALLATION_LOWERCASE_MESSAGE='installation'
SITE24X7_AGENT_REINSTALLATION_LOWERCASE_MESSAGE='reinstallation'
SITE24X7_AGENT_UNINSTALL_LOWERCASE_MESSAGE='uninstall'
SITE24X7_AGENT_PROXY=''
SITE24X7_AGENT_COMMON_PASSWORD=''
SITE24X7_AGENT_COMMON_PEMFILE_PATH=''
SITE24X7_AGENT_API_KEY=''
SITE24X7_AGENT_INSTALL_INPUT=''
SITE24X7_AGENT_INSTALL_PARAMS=''
INSTALL='INSTALL'
REINSTALL='REINSTALL'
UNINSTALL='UNINSTALL'
STOP='STOP'
SUCCESS=0
FAILURE=1
PRINT=2
GPRINT=3
RPRINT=4
ECHO_PRINT=5
ECHO_GPRINT=6
ECHO_RPRINT=7
PRODUCT_NAME='site24x7_remote_installer'
INPUT_ARGUMENTS="$@"
INSTALL_DIR=$(pwd)
PRODUCT_HOME=$INSTALL_DIR/$PRODUCT_NAME
SITE24X7_AGENT_LOG_DIR=logs
SITE24X7_AGENT_INSTALL_LOG_FILE_NAME="agentremoteinstall.log"
SITE24X7_AGENT_CONF_FILE_NAME="configuration.properties"
SITE24X7_AGENT_CONF_CSV_FILE_NAME="servers.txt"
SITE24X7_AGENT_INSTALL_LOG=$SITE24X7_AGENT_LOG_DIR/$SITE24X7_AGENT_INSTALL_LOG_FILE_NAME
SITE24X7_AGENT_CONF_DIR=$PRODUCT_HOME/installconfig
SITE24X7_AGENT_CONF_FILE=$SITE24X7_AGENT_CONF_DIR/$SITE24X7_AGENT_CONF_FILE_NAME
SITE24X7_AGENT_CONF_CSV_FILE=$SITE24X7_AGENT_CONF_DIR/$SITE24X7_AGENT_CONF_CSV_FILE_NAME
SITE24X7_AGENT_FILE=$INSTALL_DIR/servers.txt
SITE24X7_AGENT_READMEFILE=$INSTALL_DIR/readme.txt

SITE24X7_AGENT_LIB_DIR=$PRODUCT_HOME/lib
SITE24X7_AGENT_EXEC_FILE=$SITE24X7_AGENT_LIB_DIR/Site24x7RemoteAgentInstaller
SITE24X7_AGENT_REMOTE_INSTALLER=Site24x7RemoteAgentInstaller

SITE24X7_REMOTE_INSTALL_AGENT_HEARTBEAT_FILE=$PRODUCT_HOME/heartbeat.txt
SITE24X7_REMOTE_INSTALL_AGENT_STATS_FILE=$PRODUCT_HOME/stats.txt
AGENT_ALREADY_RUNNING_FLAG_FILE=$PRODUCT_HOME/agent_instance.txt

HEARTBEAT_CONTENT=''

BOOL_TRUE='True'
BOOL_FALSE='False'

INSTALL_SCRIPT_NAME=$(readlink -f $0)

LOCAL_SETUP=$BOOL_FALSE

OS_BINARY_TYPE=""
DOWNLOAD_URL=""
SCRIPT_DOWNLOAD_URL=""

#grid
THIRTY_TWO_BIT='32-bit'
SIXTY_FOUR_BIT='64-bit'
SERVER='https://staticdownloads.site24x7.com'
SIXTY_FOUR_BIT_AGENT_INSTALLER_TARGZ_FILE="Site24x7_Linux_64bit_Agent_Installer.tar.gz"
THIRTY_TWO_BIT_AGENT_INSTALLER_TARGZ_FILE="Site24x7_Linux_32bit_Agent_Installer.tar.gz"

IS_AGENT_INSTANCE_RUNNING=''
START_TIME=`date +%s`

MON_AGENT_NONROOT=$BOOL_FALSE

print_green() {
    printf "\033[32m%s\033[0m\n" "$*"
}

print_console() {
    printf "%s\n" "$*"
}

print_red() {
    printf "\033[31m%s\033[0m\n" "$*"
}

logToFile() {
	echo $(date +"%F %T.%N") "    $1" >> $SITE24X7_AGENT_INSTALL_LOG 2>&1
}


log() {
	if [ "$1" == $ECHO_PRINT ]; then
		echo "$2"
	elif [ "$1" == $ECHO_GPRINT ]; then
		#echo "${FONT_GREEN}$2${FONT_RESET}"
		echo "$2"
	elif [ "$1" == $ECHO_RPRINT ]; then
		#echo "${FONT_RED}$2${FONT_RESET}"
		echo "$2"	
	elif [ "$1" == $PRINT ]; then
		echo "$2"
		logToFile "$2"		
	elif [ "$1" == $GPRINT ]; then
		#echo "${FONT_GREEN}$2${FONT_RESET}"
		echo "$2"
		logToFile "$2"
	elif [ "$1" == $RPRINT ]; then
		#echo "${FONT_RED}$2${FONT_RESET}"
		echo "$2"
		logToFile "$2"
	else
		logToFile "$1"
	fi
}

logInputParameters() {
	log "Input parameters : $INPUT_ARGUMENTS"
}

isRootUser(){
	if [ "$(id -u)" != "0" ]
	then
		cat <<ERROR_MESSAGE
	Please use 'sudo' or log in as root to $1 $PRODUCT_NAME monitoring agent. 
ERROR_MESSAGE
		exit $FAILURE
	fi	
}


usage() {
printf '\033[31m
	Usage :
		Install command   : sudo bash -c "$(curl -sL https://staticdownloads.site24x7.com/server/Site24x7remoteinstaller.sh)" readlink [options] [authentication_options] -i  -key=<device_key>
		Reinstall command : sudo bash -c "$(curl -sL https://staticdownloads.site24x7.com/server/Site24x7remoteinstaller.sh)" readlink [options] [authentication_options] -ri -key=<device_key>
		Uninstall command   : sudo bash -c "$(curl -sL https://staticdownloads.site24x7.com/server/Site24x7remoteinstaller.sh)" readlink [options] [authentication_options] -u  -key=<device_key>
	
	Authentication Options:
		-password                     Supply the common password for the hosts that are given in servers.txt
		-pemfilepath		      Supply the common pemfilepath for the hosts that are given in servers.txt
	
	Options:
		-h                            output usage information
		-proxy                        Set proxy to connect to the site24x7 server, if needed. For example -proxy=username:password@host:port, if there is no username and passowrd for proxy server then use -proxy=host:port"
		-ct,-CT                       Configuration Template to be associated with the server
		-gn,-GN                       Group to which the server has to be added
		-tp,-TP                       Threshold profile to be associated with the server
		-np,-NP                       Notification profile to be associated with the server
		-rp,-RP                       Resource Profile to be associated with the server
		-lp,-LP                       Log Profile to be associated with the server
		-lt,-LT                       Log Type to be associated with the server. For example -lt=SysLog
		-lf,-LF                       Log Files to be collected for given log type. For example -lf=/var/log/syslog\n\033[0m\n'
	exit $FAILURE
}

if [ $(command -v wget) ]; then
    DOWNLOAD_CMD="wget -O"
    print_console "Download utility :: wget detected"
elif [ $(command -v curl) ]; then
    DOWNLOAD_CMD="curl -Lo"
    print_console "Download utility :: curl detected"
elif [ $(command -v fetch) ]; then
    DOWNLOAD_CMD="fetch -o"
    print_console "Download utility :: fetch detected"
else
    print_red "Download utilities wget, curl and fetch are not present in the server to proceed. Hence quitting !!"
    exit $FAILURE
fi

setServerDomain() {
	DC=`echo $SITE24X7_AGENT_API_KEY | awk '{print substr($0,1,2)}'`
	case "$DC" in
    	eu | cn | in | jp | uk | ca | sa )
			SERVER=`echo $SERVER | sed "s/com/$DC/g"`
        ;;
		au )
			SERVER=`echo $SERVER | sed "s/com/net.$DC/g"`
		;;
	esac
}

setDownloadUrl(){
	if [ "$OS_BINARY_TYPE" == "$THIRTY_TWO_BIT" ]; then
		printf '\033[31m 
		WARNING:
				Current machine OS-architecture is 32-bit, which is not supported. 
				RemoteInstaller Using SSH can run only on linux 64-bit machine.
				Kindly execute this script in a linux 64-bit machine\n\033[0m\n'
		exit $FAILURE
	fi

	if [ "$LOCAL_SETUP" == "$BOOL_TRUE" ]; then
		DOWNLOAD_URL="$LOCAL_SERVER/64bit/$SIXTY_FOUR_BIT_AGENT_INSTALLER_TARGZ_FILE"
		SCRIPT_DOWNLOAD_URL="$LOCAL_SERVER/scripts/Site24x7remoteinstaller.sh"
	else
		setServerDomain
		DOWNLOAD_URL="$SERVER/server/$SIXTY_FOUR_BIT_AGENT_INSTALLER_TARGZ_FILE"	
		SCRIPT_DOWNLOAD_URL="$SERVER/server/Site24x7remoteinstaller.sh"			
	fi
}

extractBinaries() {
	if [ "$DOWNLOAD_URL" == "" ]; then
	echo "Cannot determine download url hence quitting"
	exit 1
	fi
	echo ""
	printf "\033[34m
        ------------------------------------------------------------------------------------------------------------------
        |                                                                                                                |
        |                              SITE24X7 REMOTE $SITE24X7_AGENT_INSTALL_INPUT STARTED                             |
        |                                                                                                                |
        ------------------------------------------------------------------------------------------------------------------ 
\n\033[0m\n"
	echo ""
	printf "\033[32m
Downloading tar file from $DOWNLOAD_URL
\n"
	$DOWNLOAD_CMD $BINARY_TAR_FILE $DOWNLOAD_URL
	printf "\033[0m"
	if [ ! -f $BINARY_TAR_FILE ]; then
	echo $BINARY_TAR_FILE " not present hence quitting"
	exit 1	
	fi

	executeCommandAndRedirectOutputToLog "chmod -v 755 $INSTALL_DIR/$BINARY_TAR_FILE"
	executeCommandAndRedirectOutputToLog "rm -rvf site24x7_remote_installer"	
	executeCommandAndRedirectOutputToLog "mkdir -p $PRODUCT_HOME"
	log "Extracting The Agent Files"
	executeCommandAndRedirectOutputToLog "tar -zxvf $INSTALL_DIR/$BINARY_TAR_FILE -C $PRODUCT_HOME "	
	log "Successfully Extracted Agent Files to The Directory : $PRODUCT_HOME"	
	executeCommandAndRedirectOutputToLog "rm -rvf $INSTALL_DIR/$BINARY_TAR_FILE"
	executeCommandAndRedirectOutputToLog "chmod -vR 755 $SITE24X7_AGENT_LIB_DIR"
	getDeviceKey
	updateConfFiles
	security_masking
	reinstallConfUpdate
	copyFile
	executeFile
}

createInstallLog() {
	if [ ! -d $PRODUCT_HOME ]; then
		mkdir -p $PRODUCT_HOME
		RET_VAL=$?
		if [ $RET_VAL == $FAILURE ]; then
			echo "Error while creating $PRODUCT_HOME directory. Hence quiting agent "$SITE24X7_AGENT_INSTALL_INPUT"ation"
			exit $FAILURE
		fi
	fi
	RET_VAL=$SUCCESS
	if [ ! -f $SITE24X7_AGENT_INSTALL_LOG ];	then
		touch $SITE24X7_AGENT_INSTALL_LOG	
		RET_VAL=$?
		if [ $RET_VAL == $FAILURE ]; then
			echo "Error while creating "$SITE24X7_AGENT_INSTALL_INPUT"ation log. Hence quiting agent "$SITE24X7_AGENT_INSTALL_INPUT"ation"
			exit $FAILURE
		fi
	fi
}

installationMessage() {
	if [ "$1" == "$SITE24X7_AGENT_UNINSTALLING_MESSAGE" ]; then
		log $RPRINT ""
		log $RPRINT "* $1 $PRODUCT_NAME Monitoring Agent *"
		log $RPRINT ""
	else
		#log $GPRINT "===================================================================================="
		log $GPRINT ""
		#log $GPRINT "                     $1 $PRODUCT_NAME Monitoring Agent			"
		log $GPRINT "* $1 $PRODUCT_NAME Monitoring Agent *"
		log $GPRINT ""
		#log $GPRINT "===================================================================================="
	fi
}

remoteinstallerlogmessage(){
	if [ "$1" == $UNINSTALL ]; then
		log "===================================================================================="
		log $GPRINT "                     $SITE24X7_AGENT_UNINSTALLING_MESSAGE $PRODUCT_NAME Monitoring Agent			"		
		log "                     $SITE24X7_AGENT_UNINSTALLING_MESSAGE $PRODUCT_NAME Monitoring Agent			"
	elif [ "$1" == $REINSTALL ]; then
		log "====================================================================================			"
		log $GPRINT "                     $SITE24X7_AGENT_REINSTALLING_MESSAGE $PRODUCT_NAME Monitoring Agent			"		
		log "                     $SITE24X7_AGENT_REINSTALLING_MESSAGE $PRODUCT_NAME Monitoring Agent			"
	else
		log  "====================================================================================                              "
        log $GPRINT "                                                                           "
        log $GPRINT "                     $SITE24X7_AGENT_INSTALLING_MESSAGE                    "
        log $GPRINT "                                                                  "
        log $GPRINT "                     Check logs in $PWD/logs/remoteinstall.log                    "
        log "                     $SITE24X7_AGENT_INSTALLING_MESSAGE            "
	fi
}

createLogDirectory(){
	if [ ! -d $SITE24X7_AGENT_LOG_DIR ]; then
		mkdir -p $SITE24X7_AGENT_LOG_DIR
		RET_VAL=$?
		if [ $RET_VAL == $FAILURE ]; then
			echo "Error while creating log directory. Hence quitting agent installation!!"
			exit $FAILURE
		fi
	fi
}

executeCommandAndRedirectOutputToLog() {
	log "Executing command : $@"
	$@ >> $SITE24X7_AGENT_INSTALL_LOG 2>&1
}

getDeviceKey() {	
	if [ "$SITE24X7_AGENT_API_KEY" == "" ]; then
		echo "Please enter the authtoken : "
		read SITE24X7_AGENT_API_KEY
	fi	
	if [ "${SITE24X7_AGENT_API_KEY}" == "" ]; then
		echo "Device Key is empty, hence quitting agent installation/uninstallation."
		unInstallAgent
		exit $FAILURE
	fi
}


findAndReplace() {
	log "FIND AND REPLACE : String : $1 File : $2"
	sed -i "$1" "$2" 
}

updateConfFiles() {
	#echo -e "\033[34m\nUpdating Device Key in conf file.........\n\033[0m" 
	log "Updating Device Key in the conf file : $SITE24X7_AGENT_CONF_FILE"	
	sed -i "/devicekey=/c\devicekey=$SITE24X7_AGENT_API_KEY" $SITE24X7_AGENT_CONF_FILE
	findAndReplace "/installparam=/c\installparam=$SITE24X7_AGENT_INSTALL_PARAMS" $SITE24X7_AGENT_CONF_FILE
	if [ "$SITE24X7_AGENT_PROXY" != '' ]; then
		#echo -e "\033[34m\nUpdating Proxy in conf file.........\n\033[0m"
		log "Updating Proxy in the conf file : $SITE24X7_AGENT_CONF_FILE"	
		findAndReplace "/http_proxy=/c\http_proxy=http://$SITE24X7_AGENT_PROXY" $SITE24X7_AGENT_CONF_FILE
		findAndReplace "/https_proxy=/c\https_proxy=https://$SITE24X7_AGENT_PROXY" $SITE24X7_AGENT_CONF_FILE
	fi
	if [ "$SITE24X7_AGENT_COMMON_PASSWORD" != '' ]; then
		log "Updating common password in the conf file : $SITE24X7_AGENT_CONF_FILE"
		findAndReplace "/commonpassword=/c\commonpassword=$SITE24X7_AGENT_COMMON_PASSWORD" $SITE24X7_AGENT_CONF_FILE
	fi
	if [ "$SITE24X7_AGENT_COMMON_PEMFILE_PATH" != '' ]; then
		log "Updating common pemfile path in the conf file : $SITE24X7_AGENT_CONF_FILE"
		findAndReplace "/commonpemfilepath=/c\commonpemfilepath=$SITE24X7_AGENT_COMMON_PEMFILE_PATH" $SITE24X7_AGENT_CONF_FILE
	fi
}

security_masking() {
	if [ -n "$SITE24X7_AGENT_API_KEY" ]; then
		sed -i "s/$SITE24X7_AGENT_API_KEY/xxxx/" $SITE24X7_AGENT_INSTALL_LOG
	fi
}

copyFile(){
	cp $SITE24X7_AGENT_FILE $SITE24X7_AGENT_CONF_CSV_FILE >> $SITE24X7_AGENT_INSTALL_LOG 2>&1
}

check_s24x7_remoteinstall_running_status(){
	if [ -f $AGENT_ALREADY_RUNNING_FLAG_FILE ]; then
		IS_AGENT_INSTANCE_RUNNING=$( cat $AGENT_ALREADY_RUNNING_FLAG_FILE )
	fi	
	if [ ! "$IS_AGENT_INSTANCE_RUNNING" == "$START_TIME" ]; then
		echo -e "\033[31m\nSite24x7 Remote execution already running hence quitting.\n\033[0m"
		printf '\033[34m


To quit the already running site24x7 process use the following commands:

Get the pid of the already running process : \033[31mps -aux | grep -i "Site24x7RemoteAgentInstaller" | grep -v grep
\033[34mThen issue: \033[31mkill -9 <pid-of-Site24x7RemoteAgentInstaller> 


\033[0m'
		exit $FAILURE
	fi
	return $SUCCESS
}

check_s24x7_remoteinstall_heartbeat_file(){
	if [ -f $SITE24X7_REMOTE_INSTALL_AGENT_HEARTBEAT_FILE ]; then
		HEARTBEAT_CONTENT=$( cat $SITE24X7_REMOTE_INSTALL_AGENT_HEARTBEAT_FILE )
	fi
}

check_s24x7_remoteinstall_stats_file(){
	if [ -f $SITE24X7_REMOTE_INSTALL_AGENT_STATS_FILE ]; then
		STATS_CONTENT=$(cat $SITE24X7_REMOTE_INSTALL_AGENT_STATS_FILE )
		echo -e "\033[32m\n$STATS_CONTENT\n\033[0m"		
	fi
}

executeFile(){
	#check_s24x7_remoteinstall_running_status 
	printf "\033[34m\n 
Executing the bin file .........
\n\033[0m"
printf "\033[31m 
Process is running. Don't press Ctrl+C .......
\n\033[0m"
	$SITE24X7_AGENT_EXEC_FILE $START_TIME 2>&1
	check_s24x7_remoteinstall_running_status	
	RETVAL=$?
    	if [ $RETVAL -eq $SUCCESS ]; then
		check_s24x7_remoteinstall_heartbeat_file
		re='^[0-9]+$'
			if ! [[ $HEARTBEAT_CONTENT =~ $re ]]; then
				printf '\033[31m
WARNING:
-------------------------------------------------------------------------------------------------------------

Remote Installer process not running. Kindly contact https://support.site24x7.com/

\033[0m'
				exit $FAILURE
			else
				if [ "$SITE24X7_AGENT_INSTALL_INPUT" == $UNINSTALL ]; then
					printf "\033[34m\n 
Site24x7 Remote Uninstaller ends.......
\n\033[0m"
				else
					printf "\033[34m\n 
Site24x7 Remote installer ends.......
\n\033[0m"	
				fi
			#check_s24x7_remoteinstall_stats_file
			fi
   			exit $SUCCESS
		fi
}

	isInstallerRunning() {
PID=$(ps auxww | grep $SITE24X7_AGENT_REMOTE_INSTALLER | grep -v grep | awk -F ' ' '{print $2}')
if [ "$PID" == "" ]; then
    return $FAILURE
else
    echo "           -------------------------------------------------------------------------------------------------------------------------   "
    echo "           |                                                                                                                       |    " 
    echo "           |       Site24x7 Linux Server Monitoring Agent Remote Installation/Uninstallation is already running  (pid-$PID)        |    "
    echo "           |                                                                                                                       |    " 
    echo "           -------------------------------------------------------------------------------------------------------------------------   "
    return $SUCCESS
fi
}

createMachineDetailsFile(){
	#curl -sLO $SCRIPT_DOWNLOAD_URL
	if [ ! -f $SITE24X7_AGENT_FILE ]; then
inputStr="
# This is the configuration file for Remote installation/uninstallation using SSH.  

# Make a template of the configuration your providing							#Header: hostname, username, password
# In next line provide the inputs in the same order of the made template		102.22.313, robert, robertlove

# If you need different name than hostname in monitor, give template			#Header: hostname, username, password, displayname
# In next line provide the inputs in the same order of the made template		102.22.453, dirk, dirkman, primaryserver

# Refer readme.txt for different examples

"
cat << EOIPFW >> $SITE24X7_AGENT_FILE
$inputStr
EOIPFW
chmod 700 $SITE24X7_AGENT_FILE
echo ""
printf "\033[34m\n
           -----------------------------------------------------------------------------------------------------------------------------------------   
           | FOLLOW THESE STEPS:                                                                                                                   | 
           |             STEP 1: Enter the hostname, username and (password or pemfile) in the servers.txt file                                    |
           |             STEP 2: Save the changes and rerun the command                                                                            |  
           |                                                                                                                                       |   
           ----------------------------------------------------------------------------------------------------------------------------------------- 
\033[0m"

printf "\033[32m

For more details go through the readme.txt file present in the current directory

Have doubt in usage please feel free to contact, https://support.site24x7.com/ 

\033[0m"
exit 1

else
	echo 'servers.txt configuration file is already present. Can we proceed with that configuration?(y/n)'
	read response
	if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
		echo ""
	elif [ "$response" = "n"  ] || [ "$response" = "N" ]; then
	  	echo "configure the servers.txt then try again"
	  	exit $FAILURE
	else
		echo "Exiting $PRODUCT_NAME since keys other than y/n is pressed"
		exit $FAILURE
	fi
fi
}

createReadMeFile(){
	if [ ! -f $SITE24X7_AGENT_READMEFILE ]; then 
inputStr='

1) Execute the following command in the terminal to download and install the remote installer: sudo bash -c "$(curl -sL https://staticdownloads.site24x7.com/server/Site24x7remoteinstaller.sh)" readlink -i -key=<Device Key>

2) By default, two files, readme.txt and servers.txt will be created. Edit the servers.txt file with the configuration of your machines

3) For a common root password/PEM file path authentication, append the word "-password=<server password>" or "-pemfilepath=<PEM file path>" to the above command and enter the hostname and username in the following format: 
Eg:
#Header: hostname, username
SERVER1,root
SERVER2,root

4) If in case some of the servers have a different password/PEM file path other than the root password/PEM file path, enter the hostname, username and the password/PEM file path in the following format:
Eg:
#Header: hostname,username,password
SERVER2,root,<server password>
#Header: hostname,username,pemfile
SERVER2,root,<pemfilepath>

5) If you want to have different name than hostname in monitor, give displayname in the following format:
Eg:
#Header: hostname,username,password,displayname
SERVER2,root,<server password>,displayname      

6) Save the changes done in servers.txt file and rerun the command


Refer https://www.site24x7.com/help/admin/adding-a-monitor/remote-installation-using-SSH.html for detailed information on working with servers.txt file

'
cat << EOIPFW >> $SITE24X7_AGENT_READMEFILE
$inputStr
EOIPFW
	fi	
}

getHardwarePlatform() {		
	if [ "`which file`" = "" ]; then		
	    if [ `/usr/bin/getconf LONG_BIT` = "64" ]; then
		    OS_BINARY_TYPE="$SIXTY_FOUR_BIT"
		elif [ `/usr/bin/getconf LONG_BIT` = "32" ]; then
		    OS_BINARY_TYPE="$THIRTY_TWO_BIT"
		fi
	else
		if /usr/bin/file /sbin/init | grep 'ELF 64-bit' &>/dev/null; then
		    OS_BINARY_TYPE="$SIXTY_FOUR_BIT"
		elif /usr/bin/file /sbin/init | grep 'ELF 32-bit' &>/dev/null; then
		    OS_BINARY_TYPE="$THIRTY_TWO_BIT"
		elif [ `/usr/bin/getconf LONG_BIT` = "64" ]; then
		    OS_BINARY_TYPE="$SIXTY_FOUR_BIT"
		elif [ `/usr/bin/getconf LONG_BIT` = "32" ]; then
		    OS_BINARY_TYPE="$THIRTY_TWO_BIT"
		fi
	fi	
}



installAgent(){
	if [ "$MON_AGENT_NONROOT" != "$BOOL_TRUE" ]; then
		isRootUser $SITE24X7_AGENT_INSTALL_LOWERCASE_MESSAGE
	fi
	printf "\033[31m 
Choosen Mode is INSTALLATION
\n\033[0m"
	getHardwarePlatform
	setDownloadUrl
	#isInstallerRunning
	createReadMeFile
	createMachineDetailsFile
	createLogDirectory
	createInstallLog
	#remoteinstallerlogmessage $INSTALL
	logInputParameters
	extractBinaries
}

unInstallAgent(){
	if [ "$MON_AGENT_NONROOT" != "$BOOL_TRUE" ]; then
		isRootUser $SITE24X7_AGENT_UNINSTALL_LOWERCASE_MESSAGE
	fi
	printf "\033[31m 
Choosen Mode is UN-INSTALLATION
\n\033[0m"
	getHardwarePlatform
	setDownloadUrl
	#isInstallerRunning
	createReadMeFile
	createMachineDetailsFile
	createLogDirectory
	createInstallLog
	#remoteinstallerlogmessage $INSTALL
	logInputParameters
	extractBinaries
}

reinstallConfUpdate(){
	if [ "$SITE24X7_AGENT_INSTALL_INPUT" == $REINSTALL ]; then
		findAndReplace "/force_install=/c\force_install=True" $SITE24X7_AGENT_CONF_FILE
	fi
}

stopInstaller(){
	PID=$(ps auxww | grep $SITE24X7_AGENT_REMOTE_INSTALLER | grep -v grep | awk -F ' ' '{print $2}')
	if [ "$PID" == "" ]; then
	    echo "           ---------------------------------------------------------------------------------------------------------        "
	    echo "           |                                                                                      				 |        " 
	    echo "           |       Site24x7 Linux Server Monitoring Agent Remote Installation / Uninstallation is not running      |        "
	    echo "           |                                                                                      				 |        " 
	    echo "           ---------------------------------------------------------------------------------------------------------        "
	else
		kill -9 $PID
	    sleep 2
	    #isInstallerRunning
	    RETVAL=$?
	    if [ $RETVAL -eq $SUCCESS ]; then
	    		kill -9 $PID
				RETVAL=$?
				if [ $RETVAL -eq $FAILURE ]; then
		    		echo "           ---------------------------------------------------------------------------------------------------------        "
				    echo "           |                                                                                      				 |        " 
				    echo "           |       Site24x7 Linux Server Monitoring Agent Remote Installation / Uninstallation is stopped 	     |        "
				    echo "           |                                                                                      				 |        " 
				    echo "           ---------------------------------------------------------------------------------------------------------        "  	    
			    	return $SUCCESS;
			    else		    	
			    	echo "$AGENT_INSTALLER_STOP_FAILED_MESSAGE"
				fi	 
	    else
		   	echo "           ---------------------------------------------------------------------------------------------------------        "
		    echo "           |                                                                                      				 |        " 
		    echo "           |       Site24x7 Linux Server Monitoring Agent Remote Installation / Uninstallation is stopped      	 |        "
		    echo "           |                                                                                      				 |        " 
		    echo "           ---------------------------------------------------------------------------------------------------------        " 
	    	exit $FAILURE
		fi
	fi
}

main() {	
	if [ "$SITE24X7_AGENT_INSTALL_INPUT" == $INSTALL ] && [ "$SITE24X7_AGENT_API_KEY" != ''  ]; then
		installAgent
		
	elif [ "$SITE24X7_AGENT_INSTALL_INPUT" == $REINSTALL ] && [ "$SITE24X7_AGENT_API_KEY" != '' ]; then
		installAgent
		
	elif [ "$SITE24X7_AGENT_INSTALL_INPUT" == $UNINSTALL ]; then
		unInstallAgent
	
	elif [ "$SITE24X7_AGENT_INSTALL_INPUT" == $STOP ];then
		stopInstaller

		exit $SUCCESS	
	else
		usage
	fi
}


while [ "$1" != "" ]; do
	KEY=`echo $1 | awk -F= '{print $1}'`
	VALUE=`echo $1 | awk -F= '{print $2}'`
	if [ "$VALUE" != "" ]; then
		ARGUMENT=$KEY'='\"$VALUE\"
	else
		ARGUMENT=$KEY
	fi
	skipped_params=("-file" "-password" "-pemfilepath" "-s" "-rlocal")
	if [[ ! ${skipped_params[@]} =~ $KEY ]]; then
		SITE24X7_AGENT_INSTALL_PARAMS=$SITE24X7_AGENT_INSTALL_PARAMS' '$ARGUMENT
	fi
	case $KEY in
		-h|--help)
			usage
			;;
		-i)
			SITE24X7_AGENT_INSTALL_INPUT=$INSTALL
			;;
		-nr)
	        MON_AGENT_NONROOT=$BOOL_TRUE
	        ;;
		-ri)
			SITE24X7_AGENT_INSTALL_INPUT=$REINSTALL
			;;
		-u)
			SITE24X7_AGENT_INSTALL_INPUT=$UNINSTALL
			;;
		-key)
			SITE24X7_AGENT_API_KEY=$VALUE
			;;
		-proxy)
			SITE24X7_AGENT_PROXY=$VALUE
			;;
		-file)
			SITE24X7_AGENT_FILE=$VALUE
			;;
		-password)
			SITE24X7_AGENT_COMMON_PASSWORD=$VALUE
			;;
		-pemfilepath)
			SITE24X7_AGENT_COMMON_PEMFILE_PATH=$VALUE
			;;
		-s)
			SITE24X7_AGENT_INSTALL_INPUT=$STOP
			;;
		-rlocal)
			LOCAL_SETUP=$BOOL_TRUE
			LOCAL_SERVER=$VALUE
			;;
	esac
	shift
done

main
exit 0
