PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin:.

OS_NAME=`uname -s`
OS_ARCH=`uname -m`

LDD_VERSION=`ldd --version 2>/dev/null | awk 'NR==1{ print $NF }'`

SUCCESS=0
WARNING=1
FAILURE=2
BOOL_TRUE='True'
BOOL_FALSE='False'
IS_UNSUPPORTED_ARCH=$BOOL_FALSE
IS_ALPINE_ARCH=$BOOL_FALSE
IS_ARM_ARCH=$BOOL_FALSE

ECHO_PRINT=5
SUDO=''
PRODUCT_NAME='Site24x7 APM Insight'
API_KEY=''
SITE24X7_AGENT_INSTALL_INPUT=''
SITE24X7_AGENT_INSTALL_PARAMS=''

STATIC_DOWNLOAD_URL="https://staticdownloads.site24x7.com/apminsight/agents/agent_php.zip"
STATIC_CHECKSUM_URL="https://staticdownloads.site24x7.com/apminsight/checksum/agent_php.zip.sha256"
STATIC_DOWNLOAD_ALPINE_URL="https://staticdownloads.site24x7.com/apminsight/agents/agent_php_alpine.zip"
STATIC_CHECKSUM_ALPINE_URL="https://staticdownloads.site24x7.com/apminsight/checksum/agent_php_alpine.zip.sha256"
STATIC_DOWNLOAD_ARM_URL="https://staticdownloads.site24x7.com/apminsight/agents/agent_php_arm.zip"
STATIC_CHECKSUM_ARM_URL="https://staticdownloads.site24x7.com/apminsight/checksum/agent_php_arm.zip.sha256"

DOWNLOAD_URL=""
CHECKSUM_URL=""
AGENT_ZIPFILE="agent_php.zip"
UNZIP_CMD="unzip -o "

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

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

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


print_done() {
    print_green "Done"
}

`command -v which 2>/dev/null 1>/dev/null`
if [ $? = 0 ]; then
    COMMAND_CHECKER="which"
else
    COMMAND_CHECKER="command -v"
fi

if [ $(command -v curl) ]; then
    DOWNLOAD_CMD="curl -Lo"
    print_green "curl detected"
elif [ $(command -v wget) ]; then
        DOWNLOAD_CMD="wget -O"
        print_green "wget detected"
else
    DOWNLOAD_CMD=''
    print_red "Both curl and wget not present hence exiting"
    exit $FAILURE
fi

log() {
	if [ "$1" = "$ECHO_PRINT" ]; then
		echo "$2"
	fi
}


command_test() {
    $COMMAND_CHECKER $1 2>/dev/null 1>/dev/null
    if [ $? -ne 0 ]; then
    	if [ $2 = "optional" ]; then
    		WARNING_MSG=$WARNING_MSG" $1"
    		WARNING_FLAG=$BOOL_TRUE
    	else
    		ERROR_MSG=$ERROR_MSG" $1"
    		SEVERE_FLAG=$BOOL_TRUE
    	fi 
    fi
}

utilityCheck() {
	WARNING_MSG='Kindly install these if possible : '
	ERROR_MSG='Please install the following utility : '
	SUGGESTION_MSG='If packages are installed in a non-default directory, kindly add it to the PATH and retry the installation.'
	WARNING_FLAG=$BOOL_FALSE
	SEVERE_FLAG=$BOOL_FALSE
	command_test awk "mandatory"
	command_test unzip "mandatory"
	command_test php "mandatory"
 	if [ "$SEVERE_FLAG" = "$BOOL_TRUE" ]; then
 		print_red $ERROR_MSG
 		print_red $WARNING_MSG
		print_red $SUGGESTION_MSG
 		exit $FAILURE
 	fi
}

detectArchitectureType(){
	if [[ "$OS_ARCH" = *"arm"* ]] || [[ "$OS_ARCH" = *"ARM"* ]] || [[ "$OS_ARCH" = *"Arm"* ]] || [[ "$OS_ARCH" = *"aarch"* ]]; then
	  IS_ARM_ARCH=$BOOL_TRUE
	fi
	print_green "Detected os arch : $OS_ARCH"
}

detectOs(){
	if [ "$OS_NAME" = "Linux" ]; then
		print_green "detected os is linux"
	else
		IS_UNSUPPORTED_ARCH=$BOOL_TRUE
	fi
	print_green "Detected OS : $OS_NAME"
}

format_version() {
        echo "$@" | awk -F. '{ printf("%03d%03d%03d\n", $1,$2,$3); }';
}

detectLibc(){
	libc_version="$(ldd --version 2>/dev/null | awk 'NR==1{ print $NF }')"
	muslc_version="$(ldd --version 2>&1 | awk 'NR==2{print $NF}')"
	if [ "$libc_version" != "" ]; then
		if [ "$(format_version $libc_version)" -lt "$(format_version 2.14)" ]; then
			print_red "Libc vesion $libc_version which is less than 2.14"
			IS_UNSUPPORTED_ARCH=$BOOL_TRUE
		fi
	elif [ "$(format_version $muslc_version)" -gt "$(format_version 1.1)" ]; then
		print_green "Musl version $muslc_version found. Proceeding with alpine instllation..."
		IS_ALPINE_ARCH=$BOOL_TRUE
	fi
}

checkShellUtility(){
	if command -v bash; then
    	SHELL_UTILITY="bash"
    else
    	SHELL_UTILITY="sh"
    fi
}

checkForBinSupport(){
	checkShellUtility
	detectOs
	detectLibc
	detectArchitectureType 2>/dev/null
}


setDownloadUrl() {
	if [ "$IS_UNSUPPORTED_ARCH" = "$BOOL_FALSE" ]; then
		if [ "$IS_ALPINE_ARCH" = "$BOOL_TRUE" ]; then
			DOWNLOAD_URL=$STATIC_DOWNLOAD_ALPINE_URL
			CHECKSUM_URL=$STATIC_CHECKSUM_ALPINE_URL
			SUDO=""
		elif [ "$IS_ARM_ARCH" = "$BOOL_TRUE" ]; then
			DOWNLOAD_URL=$STATIC_DOWNLOAD_ARM_URL
			CHECKSUM_URL=$STATIC_CHECKSUM_ARM_URL
		else
			DOWNLOAD_URL=$STATIC_DOWNLOAD_URL
			CHECKSUM_URL=$STATIC_CHECKSUM_URL
		fi
	else
		print_red "Deprecated or Unsupported Architecture found. Please contact technical support."
		exit $FAILURE
	fi
}

isRootUser() {
	if [ "$(id -u)" != "0" ]; then
		SUDO="sudo -E"
        fi
}

verifychecksum() {
	FILECHECKSUM="$(sha256sum $AGENT_ZIPFILE | awk '{print $1}')"
	AGENTCHECKSUMURL="$(curl -sL $CHECKSUM_URL | awk '{print $1}')"
	print_console "Checksum of downloaded agent: $FILECHECKSUM"
	print_console "Checksum of live agent: $AGENTCHECKSUMURL"
	if [ $FILECHECKSUM != $AGENTCHECKSUMURL ]; then
		print_red "Checksum validation failed. Please retry after some time"
		exit $FAILURE
	else
		print_green "Downloaded agent is the current live agent." 
	fi
}

installAgent() {
	isRootUser
	utilityCheck
	checkForBinSupport
	setDownloadUrl
	echo ""
	
	echo "      -------------------------------------------------------------------------------------------------------------------------------------------------"
	echo "      |																			  																	|"	
	echo "      |							      Site24x7 APM Insight PHP Agent Installation																	|"
	echo "      |																			  																	|"
	echo "      -------------------------------------------------------------------------------------------------------------------------------------------------"
	echo ""	
	echo ""
	echo ""	
    echo "      --------------------------------------------------------Downloading agent install file ----------------------------------------------------------"
	cd /opt/
	$SUDO $DOWNLOAD_CMD $AGENT_ZIPFILE $DOWNLOAD_URL
	verifychecksum
	$SUDO $UNZIP_CMD $AGENT_ZIPFILE
	cd /opt/zpa/bin
	$SUDO $SHELL_UTILITY $SITE24X7_AGENT_INSTALL_INPUT $SITE24X7_AGENT_INSTALL_PARAMS
}


usage() {
	log $ECHO_PRINT ""
	log $ECHO_PRINT "Usage :"
	log $ECHO_PRINT '	Install command   :bash s247apminstall.sh -key=<device_key> -appname=<application name>'
	
	log $ECHO_PRINT ""
	exit $FAILURE
}



parseInput() {
	while [ "$1" != "" ]; do
        	PARAM=`echo $1 | awk -F= '{print $1}'`
        	VALUE=`echo $1 | awk -F= '{print $2}'`
        	case $PARAM in
			-h|--help)
				usage
				;;
			-key)
				MON_AGENT_API_KEY=$VALUE
				SITE24X7_AGENT_INSTALL_INPUT=configure.sh
				SITE24X7_AGENT_INSTALL_PARAMS=$SITE24X7_AGENT_INSTALL_PARAMS" "$VALUE

				;;
			-appname)
				APPNAME=$VALUE
				SITE24X7_AGENT_INSTALL_PARAMS=$SITE24X7_AGENT_INSTALL_PARAMS" "$VALUE
			
				;;
			*)
				log $ECHO_PRINT ""
		                log $ECHO_PRINT "Unknown installation parameter : $PARAM"
                		usage
		            	;;

		esac

		shift
	done
	if [ "$MON_AGENT_API_KEY" = "" ] || [ "$SITE24X7_AGENT_INSTALL_INPUT" = "" ]; then
		usage
	else
		installAgent
		
		printf "\n"
	fi
}


main() {
	parseInput "$@"
}

main "$@"
