#!/bin/sh
cloud_setup=FALSE
sysctl_loc="$(which "systemctl")"
updaterc_loc="$(which "update-rc.d")"
chkconfig_loc="$(which "chkconfig")"
php_loc="$(which php)"
php_api="$(php -i|grep 'PHP API')"
php_ini="$(php -i|grep 'Scan this dir')"
php_ext="$(php -i|grep 'extension_dir')"
curl_version="$(curl --version | awk 'NR==1{print $2}')"
ssl_version="$(openssl version | awk 'NR==1{print $2}')"
dock_loc="$(grep -q docker /proc/1/cgroup)"
libexecinfo_link="$(readlink /usr/lib/libexecinfo.so.1)"

#Once used, the $1,$2.. variables disappear
options=$1

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

check_root()
{
	if [ $(id -u) != 0 ] ; then
    		echo "Please login as root with <sudo -s> command and try again"
    		exit 0
	fi
}

check_php()
{
	if [ ! -n "$php_loc" ]; then
    		echo "PHP is not found in PATH. Kindly install php or add php installation directory to PATH!"
			echo "If PHP is managed by thirdparty applications like cPanel/WHM, kindly refer manual installation steps."
    		exit 0
	fi
	echo "PHP info found. The following info will be used for configuring the APM Insight PHP agent."
	echo $php_loc
	echo $php_api
	echo $php_ini
	echo $php_ext
}
error_handle()
{
	if [ "$?" != "0" ] ; then
		echo "Error while installing phpagent"
		exit 0
	fi
}

start_install()
{
	# In many cases, a symbolic link is needed, 
	# as libcurl is not found in /usr/lib or /usr/local dirs. 
	echo "Removing old links.."
	if [ -f "../lib/libcurl.so.4" ]; then
		# Remove the old, probably outdated link. 
		rm ../lib/libcurl.so.4
	fi
	if [ -f "../lib/libssl.so" ]; then
		# Remove the old, probably outdated link.
		rm ../lib/libssl.so
	fi
	if [ -f "../lib/libcrypto.so" ]; then
		# Remove the old, probably outdated link.
		rm ../lib/libcrypto.so
	fi
	#Only available in alpine builds. 
	if [ -f "../lib/libuuid.so" ]; then
		# Remove the old, probably outdated link.
		rm ../lib/libuuid.so
		rm ../lib/libuuid.so.1
	fi 
	if [ -f "../lib/libnghttp2.so" ]; then
		# Remove the old, probably outdated link.
		rm ../lib/libnghttp2.so
		rm ../lib/libnghttp2.so.14
	fi 
	echo "checking Curl version : $curl_version"
	echo "checking libssl version : $ssl_version"
	
	echo "Updating dependecies..."
	if [ $(version $curl_version) -lt $(version "7.49.1") ]; then
		echo "Using curl version bundled with agent."
		ln -s ../lib/libcurl.so.4.4.0 ../lib/libcurl.so.4
	else
		echo "OS curl version used. "
		if [ -f "../lib/libcurl.so.4.4.0" ]; then
			mv ../lib/libcurl.so.4.4.0 ../lib/libcurl.so.old
		fi
	fi
	if [ $(version $ssl_version) -lt $(version "1.1.1") ]; then
		echo "Using curl version bundled with agent."
		ln -s ../lib/libssl.so.1.1 ../lib/libssl.so
		ln -s ../lib/libcrypto.so.1.1 ../lib/libcrypto.so
	else
		echo "OS ssl version used. "
		if [ -f "../lib/libssl.so.1.1" ]; then
			mv ../lib/libssl.so.1.1 ../lib/libssl.so.old
		fi 
		if [ -f "../lib/libcrypto.so.1.1" ]; then
			mv ../lib/libcrypto.so.1.1 ../lib/libcrypto.so.old
		fi
	fi
	#Only available in alpine builds. 
	if [ -f "../lib/libuuid.so.1.3.0" ]; then
		ln -s ../lib/libuuid.so.1.3.0 ../lib/libuuid.so
		ln -s ../lib/libuuid.so.1.3.0 ../lib/libuuid.so.1
	fi 
	if [ -f "../lib/libnghttp2.so.14.19.0" ]; then
		ln -s ../lib/libnghttp2.so.14.19.0 ../lib/libnghttp2.so
		ln -s ../lib/libnghttp2.so.14.19.0 ../lib/libnghttp2.so.14
	fi 
	#if libexecinfo is not present, add it. 
	if [ ! -f "/usr/lib/libexecinfo.so.1" ]; then
		ln -s ${PWD}/../lib/libexecinfo.so.1 /usr/lib/libexecinfo.so.1
	fi
	if [ -z "$appName" ]; then
		echo "Using application name $defAppName. Use apminsight.conf file to change appname"
	else
		echo "Using application name $defAppName"
	fi
	case "$cloud_setup" in
		FALSE)
		echo "Setting apm host $defhost" 
		#Todo Include https true/false.
		./installer -opType configure -license $options -appName "$defAppName" -apmHost "$defhost" -useHttps $defprotocol
		;;
		TRUE)
		./installer -opType configure -license $options -appName "$defAppName" 
		;;
	esac
	mkdir -p -m 777 /opt/zpa/logs/crash
	chmod -R 777 /opt/zpa/logs/crash
	if [ -n "$sysctl_loc" ] && [ -z "$dock_loc" ] ; then
	  # install zpdp only as systemd service
	  # Old init.d services are deprecated. 
	  cp ./zpdpsvc.service /etc/systemd/system/
	  systemctl enable zpdpsvc.service
	  systemctl daemon-reload
	  echo "Registered as systemd service."
	elif [ -n "$updaterc_loc" ]; then
	  # init.d service, in case systemd is not available. 
	  cp zpdpsvc.sh /etc/init.d/zpdpsvc
	  chmod +x /etc/init.d/zpdpsvc
	  update-rc.d zpdpsvc defaults
	  echo "Registered as init.d service."
	#For Centos, and other RHEL distributions
	elif [ -n "$chkconfig_loc" ]; then
	  cp zpdpsvc.sh /etc/init.d/zpdpsvc
	  chmod +x /etc/init.d/zpdpsvc
	  chkconfig zpdpsvc on
	  echo "Registered as init.d service (RHEL)."
	fi
	error_handle
}

start_uninstall()
{	
	if [ -n "$sysctl_loc" ] && [ -z "$dock_loc" ] ; then
		# remove any systemd reference
		echo "Stopping services"
		systemctl stop zpdpsvc.service
		systemctl disable zpdpsvc.service
		systemctl daemon-reload
		rm /etc/systemd/system/zpdpsvc.service
	elif [ -n "$updaterc_loc" ]; then
		echo "Stopping init.d services"
		service zpdpsvc stop
		update-rc.d -f zpdpsvc remove
		rm /etc/init.d/zpdpsvc
	#For Centos, and other RHEL distributions
	elif [ -n "$chkconfig_loc" ]; then
		echo "Stopping init.d services"
		service zpdpsvc stop
		chkconfig zpdpsvc off
		rm /etc/init.d/zpdpsvc
	fi
	echo "Removing symbolic links"
	# Remove symbolic links created earlier.
	if [ -f "../lib/libcurl.so.4" ]; then
		rm ../lib/libcurl.so.4
	fi
	
	if [ -f "../lib/libssl.so" ]; then
		rm ../lib/libssl.so
	fi
	#Only available in alpine builds. 
	if [ -f "../lib/libuuid.so" ]; then
		rm ../lib/libuuid.so
		rm ../lib/libuuid.so.1
	fi 
	if [ -f "../lib/libnghttp2.so" ]; then
		rm ../lib/libnghttp2.so
		rm ../lib/libnghttp2.so.14
	fi 
	#if grep -q "zpa/bin/../lib/" <<< "$libexecinfo_link"; then
	#	rm /usr/lib/libexecinfo.so.1
	#fi
	case "$libexecinfo_link" in
        *zpa/bin/../lib*) rm /usr/lib/libexecinfo.so.1 ;;
    esac
	chmod 771 installer
	./installer -opType uninstall
	exit 0
}

start_process()
{
	if [ -n "$sysctl_loc" ] && [ -z "$dock_loc" ] ; then
	#  # Use systemd commands instead of scripts.
		systemctl start zpdpsvc.service
	elif [ -n "$updaterc_loc" ]; then
		service zpdpsvc start
	elif [ -n "$chkconfig_loc" ]; then
		service zpdpsvc start
	else
		echo "Could not register agent service. Starting agent manually. To stop use 'sh run.sh stop'"
		./run.sh start
	fi
		
	error_handle
}

set_permission()
{
	# Security issue fix. 
	# Only admins can read/write conf. 
	chmod 651 ../conf/apminsight.conf
	# Execute permissions. 
	chmod +x installer zpdp upgrade run.sh 
	error_handle
}

print_usage()
{
	echo "Argument missing"
	case "$cloud_setup" in
		TRUE)
    	echo "For installation try <sh configure.sh WRITE_YOUR_LICENSE_KEY_HERE OPTIONAL_APP_NAME>" ;;
		FALSE)
		echo "For installation try <sh configure.sh WRITE_YOUR_LICENSE_KEY_HERE WRITE_YOUR_HOSTNAME OPTIONAL_APP_NAME>" ;;
	esac
    echo "For Uninstallation try <sh configure.sh uninstall>"
    exit 0
}

check_root
check_php

if [ $# = 0 ] ; then
    print_usage
fi

if [ "$options" = "uninstall" ] ; then
	start_uninstall
fi

case "$cloud_setup" in
	TRUE)
	appName=$2
	defAppName="${appName:-PHP-Application}"
	;;
	
	FALSE)
	if [ $# -lt "2" ] ; then
		print_usage
	fi
	host=$2
	appName=$3
	useHttps=$4
	defhost="${host:-localhost}"
	defAppName="${appName:-PHP-Application}" 
	defprotocol="${useHttps:-false}" 
	;;
esac

set_permission
start_install $options
start_process
echo "Please restart the Web Server"
