#!/bin/bash

##################################################################################################
#
#	This Script Installs and configure the Cloudamize Agent
#
##################################################################################################

PUBLICIP_FILE=public-ipv4
CUSTOMER_KEY=/usr/local/cloudamize/bin/customer_key
CHECK_PROXY_COMMAND_STATUS="/tmp/cloudamize_check_proxy_command_status.txt"
TMP_LOGFILE=/tmp/cloudamize_install.log

#Proxy status
CO_NO_PROXY_CONFIGURED=1
CO_PROXY_CONFIGURED=2
CO_PROXY_CONFIGURED_AUTH=3

#Collect Modes
CO_COLLECT_DEFAULT=0
CO_COLLECT_MEM=1
CO_COLLECT_APP=2
CO_COLLECT_MEM_AND_APP=3

PROXY_STATUS_FILE=/usr/local/cloudamize/bin/proxy_status
PROXY_SERVER_FILE=/usr/local/cloudamize/bin/proxy_server
PROXY_PORT_FILE=/usr/local/cloudamize/bin/proxy_port
PROXY_UNAME_FILE=/usr/local/cloudamize/bin/proxy_uname
PROXY_PSWD_FILE=/usr/local/cloudamize/bin/proxy_passwd
CONFIG=

setVars()
{
	SERVERIP=127.0.0.1
	SERVERDNS=am.cloudamize.com
	SERVERPRODUCT=ASSESS
	COLLECT_MODE=$CO_COLLECT_DEFAULT
	DEBUG=0
	if [ "x"$2 = "xdebug" ]; then
		DEBUG=1
	fi
	TMPDIR=/tmp/.cconfdloads
}

addDNS()
{
	# insert/update hosts entry
	# find existing instances in the host file and save the line numbers
	matches_in_hosts="$(grep -n $SERVERDNS /etc/hosts | cut -f1 -d:)"

	if [ -z "$matches_in_hosts" ]
	then
		# Make sure the last entry of /etc/hosts has a newline, then add our entry.
		sed -i -e '$a\' /etc/hosts
		echo "${SERVERIP} ${SERVERDNS}" | tee -a /etc/hosts >/dev/null
	fi
}


checkOS()
{
	OSNAME=linux
	uname -a | grep -i ubuntu >> /dev/null
	if [ $? -eq 0 ]; then
		OSNAME=ubuntu
	else
		lsb_release -a 2>/dev/null | grep -i ubuntu >> /dev/null
        if [ $? -eq 0 ]; then
            OSNAME=ubuntu
        else
			uname -a | grep -i suse >> /dev/null
			if [ $? -eq 0 ]; then
				OSNAME=SUSE
			else
			uname -a | grep -i gentoo >> /dev/null
			if [ $? -eq 0 ]; then
				OSNAME=GENTOO
			fi
			fi
		fi
	fi
	echo $OSNAME
	echo `uname -a`
        if hash lsb_release 2>/dev/null; then
                echo `lsb_release -a`
        fi
}

echodebug()
{
	if [ $DEBUG -eq 1 ];then
		echo "DEBUG: $1"
		if [ -e $LOGFILE ]; then
			echo "DEBUG: $1" >> $LOGFILE
		fi
	fi
}

echoError()
{
	if [ $1 -ne 0 ]; then
		echo "ERROR: $2"
	fi
	if [ -e $LOGFILE ]; then
		echo "ERROR: $2" >> $LOGFILE
	fi
}

echoInfo()
{
	echo "INFO: $1"
	if [ -e $LOGFILE ]; then
		echo "INFO: $1" >> $LOGFILE
	fi
}

retry()
{
	count=$1
	printOutput=$2
	shift
	shift
	counter=1
	until [ $counter -gt $count ]
	do
		if [ $printOutput -gt 0 ]; then
			"$@"
			RC=$?
		else
			"$@" >/dev/null 2>&1
			RC=$?
		fi
		if [ $RC -eq 0 ]; then
			break
		fi
		msg="Failed attempt $counter"
		if [ $counter -lt $count ]; then
			msg="$msg, retrying..."
		fi
		echoError $RC "$msg"
		counter=$((counter+1))
	done
	return $RC
}

setConfig()
{
	grep "$1" /usr/local/cloudamize/bin/config.sh
	if [ $? -eq 0 ]; then
		sed -i "s/$1=.*/$1=\"$2\"" /usr/local/cloudamize/bin/config.sh
	else
		echo "$1=\"$2\"" >> /usr/local/cloudamize/bin/config.sh
	fi
}


uninstallCCAgent()
{
# Check if process CCAgent is runing, kill it
ps auxww |grep -v grep |grep CCAgent >/dev/null 2>&1

if [ $? -eq 0 ]; then
      kill -9 `ps auxww | grep CCAgent | grep -v grep | awk  '{print $2}'` >/dev/null 2>&1
    echo "CCAgent Stopped"
fi

# Check if process cloudamized is runing, kill it
ps auxww |grep -v grep |grep cloudamized >/dev/null 2>&1

if [ $? -eq 0 ]; then
	kill -9 `ps auxww | grep cloudamized | grep -v grep | awk  '{print $2}'` >/dev/null 2>&1
fi
#check_cloudamized
PID=`ps auxww | grep "check_cloudamized" | grep -v grep | awk {'print $2'}|wc -l`
if [ $PID -gt 0 ]; then
	for i in `ps auxww | grep "check_cloudamized" | grep -v grep | awk {'print $2'}`; do  kill -9 $i; done
fi

# Remove cloudamize enrty rc.local if exists
if [ -f /etc/rc.local ]; then
	grep cloudamized /etc/rc.local |grep cloudamize > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		sed -i '/cloudamized/ d' /etc/rc.local
	fi
fi
chkconfig --del cloudamized >/dev/null 2>&1
systemctl disable cloudamized >/dev/null 2>&1
rm -f /etc/init.d/cloudamized >/dev/null 2>&1
rm -f /etc/systemd/system/cloudamized.service 2>&1

if [ -e /etc/local.d/cloudamized.start ]; then
	rm -f /etc/local.d/cloudamized.start >/dev/null 2>&1
fi

# Remove port 5106 from service if exist
grep -w cloudamized /etc/services |grep 5106 > /dev/null 2>&1
if [ $? -eq 0 ]; then
  sed -i '/cloudamized / d' /etc/services
fi

# Delete old agent if exists
if [ -d /usr/local/CloudConfidence ]; then
  rm -rf /usr/local/CloudConfidence > /dev/null 2>&1
fi

# Delete agent if exists
if [ -e /usr/local/cloudamize/ ]; then
	UUID=`cat /usr/local/cloudamize/bin/uuid 2>/dev/null`
	INFO=`cat /usr/local/cloudamize/bin/info 2>/dev/null`
	DOCKER=0
	if [ -e /usr/local/cloudamize/bin/cc_docker ]; then
		DOCKER=1
	fi

	CONFIG=`cat /usr/local/cloudamize/bin/config.props 2>/dev/null`

	rm -rf  /usr/local/cloudamize/ > /dev/null 2>&1

	if [ -n "$UUID" ] || [ -n "$INFO" ]; then
		mkdir -p /usr/local/cloudamize/bin
		echo $UUID > /usr/local/cloudamize/bin/uuid
		echo "$INFO" > /usr/local/cloudamize/bin/info
	fi

	if [ $DOCKER -eq 1 ]; then
		mkdir -p /usr/local/cloudamize/bin
		touch /usr/local/cloudamize/bin/cc_docker
	fi
fi

}

downloadAgent()
{
	rm -rf $TMPDIR/ccagent-v2
	mkdir -p $TMPDIR/ccagent-v2
	cd $TMPDIR/ccagent-v2

	INSTALL_FILE=ccagent-v2.tgz
	if [ -n "$CLOUDAMIZE_INSTALL_FILE" ]; then
		INSTALL_FILE=$CLOUDAMIZE_INSTALL_FILE
		echoInfo "Using specified installer file $INSTALL_FILE"
	fi

	if [ $CO_PROXY_STATUS -eq $CO_NO_PROXY_CONFIGURED ]; then
		#Check if the machine is on AWS
		# curl $CURL_FLAGS -m 1000 https://$SERVERDNS/cxf/downloadFile/$INSTALL_FILE > ccagent-v2.tgz
		retry 3 1 curl -s $CURL_FLAGS -m 1000 "https://$SERVERDNS/cxf/downloadFileV3?custkey=$customerKey&filename=$INSTALL_FILE" -L -o $INSTALL_FILE
	fi

	if [ $CO_PROXY_STATUS -eq $CO_PROXY_CONFIGURED ]; then
		# curl $CURL_FLAGS -m 100 --proxy $PROXY_SERVER:$PROXY_PORT https://$SERVERDNS/cxf/downloadFile/$INSTALL_FILE > ccagent-v2.tgz
		retry 3 1 curl -s $CURL_FLAGS -m 100 --proxy $PROXY_SERVER:$PROXY_PORT "https://$SERVERDNS/cxf/downloadFileV3?custkey=$customerKey&filename=$INSTALL_FILE" -L -o $INSTALL_FILE
	fi

	if [ $CO_PROXY_STATUS -eq $CO_PROXY_CONFIGURED_AUTH ]; then
		# curl $CURL_FLAGS -m 100 --proxy $PROXY_SERVER:$PROXY_PORT --proxy-user $PROXY_UNAME:$PROXY_PSWD https://$SERVERDNS/cxf/downloadFile/$INSTALL_FILE > ccagent-v2.tgz
		retry 3 1 curl -s $CURL_FLAGS -m 100 --proxy $PROXY_SERVER:$PROXY_PORT --proxy-user $PROXY_UNAME:$PROXY_PSWD "https://$SERVERDNS/cxf/downloadFileV3?custkey=$customerKey&filename=$INSTALL_FILE" -L -o $INSTALL_FILE
	fi

	output=$(tar -zxf ccagent-v2.tgz 2>&1)
	if [ $? -ne 0 ]; then
		echoError 1 "Failed to download cloudamize agent."
		file ccagent-v2.tgz | grep text >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			msg=$(cat ccagent-v2.tgz)
			echoInfo "$msg"
		fi
		rm -rf $TMPDIR/ccagent-v2
		exit 1
	fi
}

installCCAgent()
{
	mkdir -p /usr/local/cloudamize/bin
	mkdir -p /usr/local/cloudamize/cl-out
	mkdir -p /usr/local/cloudamize/ofl-out
	mkdir -p /usr/local/cloudamize/out
	mkdir -p /usr/local/cloudamize/logs
	mkdir -p /usr/local/cloudamize/temp

	echoInfo "Created cloudamize directories"

	cd $TMPDIR/ccagent-v2

	chmod 755 /usr/local/cloudamize/bin
	chmod 755 /usr/local/cloudamize/out /usr/local/cloudamize/logs /usr/local/cloudamize/cl-out /usr/local/cloudamize/ofl-out

	#Save proxy configuration parameters
	echo $CO_PROXY_STATUS > $PROXY_STATUS_FILE

	if [ $CO_PROXY_STATUS -eq $CO_PROXY_CONFIGURED ]; then
		echo $PROXY_SERVER > $PROXY_SERVER_FILE
		echo $PROXY_PORT > $PROXY_PORT_FILE
	fi

	if [ $CO_PROXY_STATUS -eq $CO_PROXY_CONFIGURED_AUTH ]; then
		echo $PROXY_SERVER > $PROXY_SERVER_FILE
		echo $PROXY_PORT > $PROXY_PORT_FILE
		echo $PROXY_UNAME > $PROXY_UNAME_FILE
		echo $PROXY_PSWD > $PROXY_PSWD_FILE
	fi

	echo $customerKey > $CUSTOMER_KEY

	echoInfo "Set proxy and customer key"

	cp -f ccagent-v2/* /usr/local/cloudamize/bin >> $LOGFILE 2>&1

	echoInfo "Adding cloudamized service"

	chmod +x /usr/local/cloudamize/bin/cloudamized
	if command -v systemctl >/dev/null; then
		cp /usr/local/cloudamize/bin/cloudamized.service /etc/systemd/system
		systemctl enable cloudamized
		echoInfo "Done with systemctl"
	elif command -v chkconfig >/dev/null; then
		cp -f /usr/local/cloudamize/bin/cloudamized /etc/init.d/ >> $LOGFILE 2>&1
		chmod +x /etc/init.d/cloudamized >/dev/null 2>&1
		# Check if SuSE Linux
		IS_SUSE=0
		grep 'ID="sles' /etc/os-release >/dev/null 2>&1
		if [ $? -eq 0 ]; then IS_SUSE=1; fi
		grep 'ID="opensuse' /etc/os-release >/dev/null 2>&1
		if [ $? -eq 0 ]; then IS_SUSE=1; fi
		if [ -e /etc/SuSE-release ]; then IS_SUSE=1; fi

		# adds to sysv init
		chkconfig --add cloudamized >/dev/null 2>&1
		# SuSE has a different chkconfig. level is ignored and will completely disable the service.
		# Run levels are set via LSB header in cloudamized, so this is unnecessary (for suse).
		if [ $IS_SUSE -eq 0 ]; then
			chkconfig --level 06 cloudamized off >/dev/null 2>&1
		fi
		echoInfo "Done with chkconfig"
	elif command -v update-rc.d >/dev/null; then
		cp -f /usr/local/cloudamize/bin/cloudamized /etc/init.d/ >> $LOGFILE 2>&1
		chmod +x /etc/init.d/cloudamized >/dev/null 2>&1
		update-rc.d cloudamized defaults 2>/dev/null
		update-rc.d cloudamized enable 2>/dev/null
		echoInfo "Done with update-rc.d"
	elif [ -f /etc/rc.local ]; then
		grep "^exit 0" /etc/rc.local >/dev/null
		if [ $? -eq 0 ]; then
			sed -i '/^exit 0/c\/usr/local/cloudamize/bin/cloudamized start\nexit 0' /etc/rc.local
			if [ $? -ne 0 ]; then
				echoInfo "Failed - Updating of rc.local"
			fi
		else
			grep "^cat <<EOL >> /etc/ssh/sshd_config" /etc/rc.local
			if [ $? -eq 0 ]; then
				sed -i '/^cat <<EOL >> \/etc\/ssh\/sshd_config/c\/usr/local/cloudamize/bin/cloudamized start\ncat <<EOL >> /etc/ssh/sshd_config' /etc/rc.local
				if [ $? -ne 0 ]; then
					echoInfo "Failed - Updating of rc.local"
				fi
			else
				echo "/usr/local/cloudamize/bin/cloudamized start " >> /etc/rc.local
			fi
		fi
		echoInfo "Done updating rc.local"
	elif [ -d /etc/local.d ]; then
			cp /usr/local/cloudamize/bin/cloudamized.start /etc/local.d/
			echoInfo "Done updating local.d"
	else
		echoError 1 "Could not determine service system - agent will not start on reboot!"
	fi

	if [ ! -e /usr/local/cloudamize/bin/config.sh ]; then
		echo '#!/bin/bash' > /usr/local/cloudamize/bin/config.sh
	fi

	# Replace or add endpoint information in config.sh
	sed -i "/^SERVERIP=/{h;s/=.*/=${SERVERIP}/};\${x;/^$/{s//SERVERIP=${SERVERIP}/;H};x}" /usr/local/cloudamize/bin/config.sh
	sed -i "/^SERVERDNS=/{h;s/=.*/=${SERVERDNS}/};\${x;/^$/{s//SERVERDNS=${SERVERDNS}/;H};x}" /usr/local/cloudamize/bin/config.sh
	sed -i "/^SERVERPRODUCT=/{h;s/=.*/=${SERVERPRODUCT}/};\${x;/^$/{s//SERVERPRODUCT=${SERVERPRODUCT}/;H};x}" /usr/local/cloudamize/bin/config.sh
	echo "socket_byte_count=0" > /usr/local/cloudamize/bin/config.props
	echo "run=1" >> /usr/local/cloudamize/bin/config.props
	sed -i "/^collect_mode=/{h;s/=.*/=${COLLECT_MODE}/};\${x;/^$/{s//collect_mode=${COLLECT_MODE}/;H};x}" /usr/local/cloudamize/bin/config.props
	sed -i "/^USE_INSECURE_CURL=/{h;s/=.*/=${insecureCurl}/};\${x;/^$/{s//USE_INSECURE_CURL=${insecureCurl}/;H};x}" /usr/local/cloudamize/bin/config.sh
	sed -i "/^PREFER_SYS_CURL=/{h;s/=.*/=${preferSysCurl}/};\${x;/^$/{s//PREFER_SYS_CURL=${preferSysCurl}/;H};x}" /usr/local/cloudamize/bin/config.sh
	if [ -n "$curlCaCert" ]; then
		# escape the forward slashes
		curlCaCert=$(echo "$curlCaCert" | sed -e 's#/#\\/#g')
		sed -i "/^CURL_CACERT=/{h;s/=.*/=${curlCaCert}/};\${x;/^$/{s//CURL_CACERT=${curlCaCert}/;H};x}" /usr/local/cloudamize/bin/config.sh
	fi
	sed -i "/^USE_STRICT_TLS_1_3=/{h;s/=.*/=${curlStrictTls13}/};\${x;/^$/{s//USE_STRICT_TLS_1_3=${curlStrictTls13}/;H};x}" /usr/local/cloudamize/bin/config.sh

	echoInfo "Agent config settings updated"

	uname -m |grep "64" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		cp -f ccagent-v2/cpu_32/* /usr/local/cloudamize/bin >> $LOGFILE 2>&1
	else
		cp -f ccagent-v2/cpu_64/* /usr/local/cloudamize/bin >> $LOGFILE 2>&1
	fi
	chmod 755 /usr/local/cloudamize/bin/* >> $LOGFILE 2>&1
	echoInfo "Install step complete"
}

configure()
{

	cd /usr/local/cloudamize/bin

	if [ -n "$CONFIG" ]; then
		echo "$CONFIG" > /usr/local/cloudamize/bin/config.props
	fi

	if [ ! -z "$socketByteCount" ]; then
		/usr/local/cloudamize/bin/config-set.sh socket_byte_count $socketByteCount
	fi
	if [ ! -z "$monitorLevel" ]; then
		/usr/local/cloudamize/bin/config-set.sh collect_mode $monitorLevel
	fi
	if [ "$noOracleDb" = "1" ]; then
		/usr/local/cloudamize/bin/config-set.sh data.LINUX_ORACLE_DB_DATA 0
	fi
}

startAgent()
{
	if [ ! -e /usr/local/cloudamize/bin/cc_docker ]; then
		if command -v systemctl >/dev/null; then
			systemctl stop cloudamized >/dev/null 2>&1
			systemctl start cloudamized >/dev/null 2>&1
		else
			/usr/local/cloudamize/bin/cloudamized stop
			/usr/local/cloudamize/bin/cloudamized start
		fi
	fi
}

testCurl() {
	echoInfo "Testing curl."
	if [ $CO_PROXY_STATUS -eq $CO_NO_PROXY_CONFIGURED ]; then
		cmd="curl $CURL_FLAGS -s --fail -m 15"
		cmd_log="$cmd"
	fi
	if [ $CO_PROXY_STATUS -eq $CO_PROXY_CONFIGURED ]; then
		cmd="curl $CURL_FLAGS -s --fail -m 15 --proxy $PROXY_SERVER:$PROXY_PORT"
		cmd_log="$cmd"
	fi
	if [ $CO_PROXY_STATUS -eq $CO_PROXY_CONFIGURED_AUTH ]; then
		cmd="curl $CURL_FLAGS -s --fail -m 15 --proxy $PROXY_SERVER:$PROXY_PORT --proxy-user $PROXY_UNAME:$PROXY_PSWD"
		cmd_log="curl $CURL_FLAGS -s --fail -m 15 --proxy $PROXY_SERVER:$PROXY_PORT --proxy-user ***:***"
	fi
	retry 3 0 $cmd https://$SERVERDNS/cxf/test
	RC=$?
	if [ $RC -ne 0 ]; then
		resolvedServerIp=$(dig +short $SERVERDNS 2>/dev/null)
		echoError $RC "Curl could not connect to $SERVERDNS ($resolvedServerIp). Running additional debug commands..."
		echo "[INFO] Running $cmd_log -v https://$SERVERDNS/cxf/test" >$TMP_LOGFILE
		retry 2 1 $cmd -v https://$SERVERDNS/cxf/test >>$TMP_LOGFILE 2>&1
		echo "[INFO] Running $cmd_log -k -v https://$SERVERDNS/cxf/test" >>$TMP_LOGFILE
		retry 2 1 $cmd -k -v https://$SERVERDNS/cxf/test >>$TMP_LOGFILE 2>&1
		echo "[INFO] Running $cmd_log -v https://google.com" >>$TMP_LOGFILE
		retry 2 1 $cmd -v https://google.com >>$TMP_LOGFILE 2>&1
		echoError $RC "Please include $TMP_LOGFILE if contacting cloudamize support."
		exit 1
	else
		echoInfo "Curl success!"
	fi
}

usage() {
	echo "Usage: $0 [OPTION]..."
	echo "Installs the Cloudamize agent."
	echo ""
	echo "Options:"
	echo "  --proxy-server            Proxy server to connect to"
	echo "  --proxy-port              Port the proxy server is on"
	echo "  --proxy-user              User name for proxy server"
	echo "  --proxy-pass              Password for proxy server"
	echo "  --monitor-level           'assess' or 'manage' monitor types"
	echo "  --insecure-curl           Uses curl -k to ignore SSL certificate errors"
	echo "  --prefer-sys-curl         Prefer using system curl instead of packaged curl"
	echo "  --no-oracle-db            Do not collect oracle db info"
	echo "  --register                Attempt registration immediately and uninstall if failed"
	echo "  --curl-ca-cert            A file with CA certs in pem format to use after install"
	echo "  --curl-strict-tls1.3      Require use of TLS 1.3"
}

#####################################
#Main

# Usage

#read -p "Enter customer key: " customerKey

customerKey=$CLOUDAMIZE_CUSTOMER_KEY
serverIP=$SERVER_IP
serverDNS=$SERVER_DOMAIN_NAME
#socketByteCount=$SOCKET_BYTE_COUNT
socketByteCount=
noUpgrade=$NO_UPGRADE
monitorLevel=""
noHosts=$NO_HOSTS
insecureCurl=$USE_INSECURE_CURL
preferSysCurl=$PREFER_SYS_CURL
noOracleDb=$NO_ORACLE_DB
registerImmediately=$REGISTER_IMMEDIATELY
curlCaCert=$CURL_CACERT
curlStrictTls13=$STRICT_TLS_1_3

# Sometimes customers set these without the proxy options, causing the agent to
# install and run successfully and then break on reboot.
http_proxy=
https_proxy=

if [ `whoami` != "root" ] ; then
    echo "ERROR: $0 must be run as user 'root'."
    exit 1
fi

# Set Base Variables
setVars

#Set Cloudamize server IP
if [ ! -z "$serverIP" ]; then
	SERVERIP=$serverIP
fi

#Set Cloudamize server DOMAIN NAME
if [ ! -z "$serverDNS" ]; then
	SERVERDNS=$serverDNS
fi

if [ -z "$insecureCurl" ]; then
	insecureCurl=0
fi

if [ -z "$registerImmediately" ]; then
	registerImmediately=0
fi

if [ -z "$curlStrictTls13" ]; then
	curlStrictTls13=0
fi

CO_PROXY_STATUS=$CO_NO_PROXY_CONFIGURED

posCount=0
while [ $# -gt 0 ]
do
key="$1"
case $key in
	--socket-monitor-level)
	socketByteCount="$2"
	shift
	shift
	;;
	--monitor-level)
	monitorLevel="$2"
	shift
	shift
	;;
	--proxy-server)
	PROXY_SERVER="$2"
	shift
	shift
	;;
	--proxy-port)
	PROXY_PORT="$2"
	shift
	shift
	;;
	--proxy-user)
	PROXY_UNAME="$2"
	shift
	shift
	;;
	--proxy-pass)
	PROXY_PSWD="$2"
	shift
	shift
	;;
	--server-ip)
	serverIP="$2"
	shift
	shift
	;;
	--server-dns)
	serverDNS="$2"
	shift
	shift
	;;
	--customer-key)
	customerKey="$2"
	shift
	shift
	;;
	--no-hosts)
	noHosts=1
	shift
	;;
	--insecure-curl)
	insecureCurl=1
	shift
	;;
	--prefer-sys-curl)
	preferSysCurl=1
	shift
	;;
	--no-oracle-db)
	noOracleDb=1
	shift
	;;
	--register)
	registerImmediately=1
	shift
	;;
	--curl-ca-cert)
	curlCaCert="$2"
	shift
	shift
	;;
	--curl-strict-tls1.3)
	curlStrictTls13=1
	shift
	;;
	--help)
	usage
	exit 0
	;;
	*) # Parse positional params.
	case $posCount in
		0)
		PROXY_SERVER=$1
		;;
		1)
		PROXY_PORT=$1
		;;
		2)
		PROXY_UNAME=$1
		;;
		3)
		PROXY_PSWD=$1
		;;
		4)
		echo "ERROR: too many parameters. Please double check your command."
		exit 1
		;;
	esac
	posCount=$((posCount+1))
	shift
	;;
esac
done

if [ -z "$preferSysCurl" ]; then
	preferSysCurl=0
fi

if [ -z $customerKey ]; then
	echo "ERROR: set CLOUDAMIZE_CUSTOMER_KEY environment variable using export command or --customer-key and rerun."
	exit 1
fi

CURL_FLAGS=
if [ -n "$insecureCurl" ] && [ "$insecureCurl" -eq 1 ]; then
	CURL_FLAGS="-k"
fi

if [ -n "$socketByteCount" ]; then
	if [ "$socketByteCount" = "full" ]; then
		socketByteCount=1
	elif [ "$socketByteCount" = "partial" ]; then
		socketByteCount=2
	elif [ "$socketByteCount" = "off" ]; then
		socketByteCount=0
	else
		echo "[Error] Invalid socket monitor level. Please specify full, partial, or off."
		exit 1
	fi
fi

if [ -n "$monitorLevel" ]; then
	if [ "$monitorLevel" = "assess" ]; then
		monitorLevel=0
	elif [ "$monitorLevel" = "manage" ]; then
		monitorLevel=3
	else
		echo "[Error] Invalid monitor level. Please specify assess or manage."
		exit 1
	fi
fi

if [ ! -z "$PROXY_SERVER" ] || [ ! -z "$PROXY_PORT" ]; then
	if [ -z "$PROXY_SERVER" ] || [ -z "$PROXY_PORT" ]; then
		echo "[Error] Please provide both --proxy-server and --proxy-port"
		echo ""
		usage
		exit 1
	fi
	CO_PROXY_STATUS=$CO_PROXY_CONFIGURED
fi

if [ ! -z "$PROXY_UNAME" ] || [ ! -z "$PROXY_PSWD" ]; then
	if [ -z "$PROXY_UNAME" ] || [ -z "$PROXY_PSWD" ]; then
		echo "[Error] Please provide both --proxy-user and --proxy-pass"
		echo ""
		usage
		exit 1
	fi
	if [ -z "$PROXY_SERVER" ] || [ -z "$PROXY_PORT" ]; then
		echo "[Error] Please provide both --proxy-server and --proxy-port"
		echo ""
		usage
		exit 1
	fi
	CO_PROXY_STATUS=$CO_PROXY_CONFIGURED_AUTH
fi

if [ $CO_PROXY_STATUS -eq $CO_NO_PROXY_CONFIGURED ]; then
	if [ $posCount -eq 1 ]; then
			echo "[Error] Please provide proxy configuration as mentioned on UI"
		exit 1
	fi

	if [ $posCount -eq 2 ]; then
		CO_PROXY_STATUS=$CO_PROXY_CONFIGURED
	fi

	if [ $posCount -eq 3 ]; then
			echo "[Error] Please provide proxy configuration as mentioned on UI"
		exit 1
	fi

	if [ $posCount -eq 4 ]; then
		CO_PROXY_STATUS=$CO_PROXY_CONFIGURED_AUTH
	fi
fi

#if [ -z "$noHosts" ] || [ "$noHosts" = "0" ] || [ "$noHosts" = "false" ]; then
#	addDNS
#fi

LOGFILE="/usr/local/cloudamize/logs/install.log"
testCurl
echoInfo "Downloading Cloudamize Monitor"
downloadAgent
uninstallCCAgent
installCCAgent
echoInfo "Done."

# Determine OS
checkOS

echoInfo "Done Checking Dependencies"

rm -rf $TMPDIR

echoInfo "Configuring Cloudamize Monitor"
configure

if [ "$registerImmediately" = "1" ]; then
	/usr/local/cloudamize/bin/register.sh
	if [ $? -ne 0 ]; then
		echoError 1 "Failed to register cloudamize agent. Response:"
		cat /usr/local/cloudamize/bin/reg_agent_resp.xml # register script logs this, but print for user
		echo ""
		echoInfo "Uninstalling agent."
		# When uninstalling, the logs will be deleted. We should preserve them.
		cp $LOGFILE $TMP_LOGFILE
		uninstallCCAgent
		echoInfo "Done."
		echoInfo "Please check $TMP_LOGFILE for details."
		exit 1
	fi
	echoInfo "Successfully registered agent."
fi

echoInfo "Starting Cloudamize Agent"
startAgent

echoInfo "Cloudamize Monitor Installed Successfully"
exit 0
