#!/bin/sh

# Copyright 2004-2025 Citrix Systems, Inc. All rights reserved.
# This software and documentation contain valuable trade
# secrets and proprietary property belonging to Citrix Systems, Inc.
# None o1f this software and documentation may be copied,
# duplicated or disclosed without the express
# written permission of Citrix Systems, Inc.

unameOut="$(uname -s)"
case "${unameOut}" in
    Linux*)       machine=Linux;;
    FreeBSD*)     machine=FreeBSD;;
esac

. /var/mastools/scripts/admautoreg/admautoregd.conf

MONITRC=/etc/monitrc
CONFIG_FILE=/nsconfig/admparam.conf
MASTOOLS_CONFIGFILE=/var/mastools/conf/agent.conf
MASTOOLS_UPGRADE_DAEMON_FILE=mastools_upgrade.py
SVM_ADMAUTOREG_STATE_FILE=/mpsconfig/admautoreg.state
ADMAUTOREG_STATE_FILE=/nsconfig/admautoreg.state
INTERNAL_AUTO_REG_FILE=autoreg_internal_job.py
MASTOOLSLOGSPATH=/var/mastools/logs
MASTOOLSCONFPATH=/var/mastools/conf
BLX_ENVRON_FILE=/root/.blx/environ

STATE_TRUE_EXIT_CODE=1
STATE_FALSE_EXIT_CODE=2

is_sdx=false
sdx_auto_reg=false

# Create the conf and logs directory.
if [ ! -d "${MASTOOLSCONFPATH}" ]; then
	mkdir -p "${MASTOOLSCONFPATH}"
fi
if [ ! -d "${MASTOOLSLOGSPATH}" ]; then
	mkdir -p "${MASTOOLSLOGSPATH}"
fi

timestamp=date
echo  `${timestamp}` "start adm autoregd ctl"  >> /var/mastools/logs/adm_ctl.log
#platform_descr=`sysctl netscaler.descr`
SVM_MPS_LIB_DIR=/mps/lib
if [ -d "$SVM_MPS_LIB_DIR" ]; then
	    echo `$timestamp` "run in SDX platform" >> /var/mastools/logs/adm_ctl.log
		CONFIG_FILE=/mpsconfig/admparam.conf
		is_sdx=true
		sdx_autoreg_cmd='/usr/local/bin/python /var/mastools/scripts/mastools_util.py -get_auto_reg'
		$sdx_autoreg_cmd
		ret_val=$?
		echo `$timestamp` "get auto reg from db returns" $ret_val >> /var/mastools/logs/adm_ctl.log
		if [ $ret_val -eq ${STATE_TRUE_EXIT_CODE} ] ; then
		    sdx_auto_reg=true
		fi
fi
# Do not change error-code here. NS code dependency
ERRCODE_MASTOOLS_RUNNING=79
ERRCODE_ENABLED=80
ERRCODE_DISABLED=81
ERRCODE_NOT_SUPPORTED=82
ERRCODE_INTERNAL_NS=83

GATEWAY_CONNECTOR_SYSCTL=netscaler.is_ngs_connector

usage()
{
	echo "This script is used to start and stop admautoregd, and/or enable or disable"
	echo "its monitoring by monit."
	echo "The normal options are:"
	echo "/bin/sh /etc/admautoregd_ctl start - starts admautoregd."
	echo "/bin/sh /etc/admautoregd_ctl start_monit_admautoregd - tell monit to keep track of admautoregd."
	echo "/bin/sh /etc/admautoregd_ctl full_start - start admautoregd, then tell monit to monitor it."
	echo "/bin/sh /etc/admautoregd_ctl stop - stops admautoregd."
	echo "/bin/sh /etc/admautoregd_ctl stop_monit_admautoregd - tell monit to stop keeping track of admautoregd."
	echo "/bin/sh /etc/admautoregd_ctl full_stop - tells monit to ignore admautoregd, then stops admautoregd."
	echo "/bin/sh /etc/admautoregd_ctl restart_if_running - restarts admautoregd if it is already running."
	echo "/bin/sh /etc/admautoregd_ctl status - tells status of admautoregd (if it is running or not)."
}

start_admautoregd()
{
	stop_admautoregd;
	echo -n 'admAutoReg '
	/var/python/bin/python ${DAEMON_BASEDIR}/${DAEMON_FILE} &
	echo -n $! > ${PID_DIR}/${PID_FILE}
	if [ "$is_sdx" = true ] ; then
		echo -n "admAutoReg Internal SDX Daemon"
		/var/python/bin/python ${DAEMON_BASEDIR}/${INTERNAL_AUTO_REG_FILE} &
		echo -n "Done"
	else
		add_nameserver;
	fi
}

stop_admautoregd()
{
	autoreg_pid=`ps -axww | awk '/adm_auto_reg_daemon.py/ && !/awk/ {print $1}'`
    if [ "$autoreg_pid" != "" ]; then
        kill -9 ${autoreg_pid}
    fi
	rm -f ${PID_DIR}/${PID_FILE}
	if [ "$is_sdx" = true ] ; then
		pid=`ps -axww | awk '/autoreg_internal_job/ && !/awk/ {print $1}'`
		if [ "$pid" != "" ]; then
			kill -9 $pid
		fi
	fi
}

set_autoconnect_status()
{
	if [ -f "${CONFIG_FILE}" ]; then
		# remove autoconnect_status from conf file
		grep -v autoconnect_status ${CONFIG_FILE} > ${CONFIG_FILE}.bak
		chmod 644 ${CONFIG_FILE}.bak
		mv ${CONFIG_FILE}.bak ${CONFIG_FILE}
	else
		touch ${CONFIG_FILE}
		chmod 644 ${CONFIG_FILE}
		echo "first_login=1" >> $CONFIG_FILE
		echo "initial_wait=1800" >> $CONFIG_FILE
	fi
	echo "autoconnect_status=$1" >> $CONFIG_FILE
}

enable_autoconnect_status()
{
	set_autoconnect_status "1";
}

disable_autoconnect_status()
{
	set_autoconnect_status "0";
}

full_start()
{
	enable_autoconnect_status;
	start_admautoregd;
	start_monit_on_admautoregd;
}

full_stop()
{
	disable_autoconnect_status;
	stop_monit_on_admautoregd;
	stop_admautoregd;
}

# Called by CLI 'set admparameter -autoconnect ENABLED'
autoconnect_enable()
{
	# Autoconnect enable/disable not supported for gateway connector
	IS_GATEWAY_CONNECTOR=$(is_gateway_connector)
	if [ "$IS_GATEWAY_CONNECTOR" -eq 1 ]; then
		exit ${ERRCODE_NOT_SUPPORTED}
	fi

	enable_autoconnect_status;
	# Start admautoregd if it is not running
	admautoregd_pid=$(ps -ax | grep ${DAEMON_FILE} | grep "python" | grep -v "grep" | awk '{print $1}')
	if [ "$admautoregd_pid" = "" ]; then
		start_admautoregd;
		start_monit_on_admautoregd;
	fi

	mastools_upgraded_pid=$(ps -ax | grep ${MASTOOLS_UPGRADE_DAEMON_FILE}| grep -v "grep" | awk '{print $1}')
	if [ "$mastools_upgraded_pid" = "" ]; then
		# Start mastools upgrade daemon if it not running and if mastools is not enabled
		# (i.e. if agent.conf file doesn't exist)
		if [ -f "${MASTOOLS_CONFIGFILE}" ]; then
		    if [ "$machine" = "Linux" ];then
		        :
		    fi
			#mastools is running
		else
			echo `$timestamp` 'autoconnect_enable:: starting mastools'  >> /var/mastools/logs/adm_ctl.log
			/bin/sh /var/mastools/scripts/mastoolsd start
		fi
	fi
}

# Called by CLI 'set admparameter -autoconnect DISABLED'
autoconnect_disable()
{
	# Autoconnect enable/disable not supported for gateway connector
	IS_GATEWAY_CONNECTOR=$(is_gateway_connector)
	if [ "$IS_GATEWAY_CONNECTOR" -eq 1 ]; then
		exit ${ERRCODE_NOT_SUPPORTED}
	fi

	internal_autoreg_cmd='/var/python/bin/python /var/mastools/scripts/admautoreg/check_internal.py'
	$internal_autoreg_cmd
	ret_val=$?
	if [ $ret_val -eq 1 ]; then
		# If an internal system reject the disable command.
		enable_autoconnect_status;
		echo "autoconnect cannot be disabled for Citrix Internal NetScalers" 1>&2
		exit ${ERRCODE_INTERNAL_NS}
	fi

	admautoregd_pid=$(ps -ax | grep ${DAEMON_FILE} | grep "python" | grep -v "grep" | awk '{print $1}')
	mastools_upgraded_pid=$(ps -ax | grep ${MASTOOLS_UPGRADE_DAEMON_FILE}| grep -v "grep" | awk '{print $1}')

	# Error out if mastools is running
	if [ -f "${MASTOOLS_CONFIGFILE}" ]; then
		echo "autoconnect cannot be disabled because mastools is running" 1>&2
		exit ${ERRCODE_MASTOOLS_RUNNING}
	fi

	disable_autoconnect_status;
	stop_monit_on_admautoregd;
	# If admautoregd is running
	if [ "$admautoregd_pid" != "" ]; then
		stop_admautoregd;
	fi

	# if mastool upgrade daemon is running
    if [ "$mastools_upgraded_pid" != "" ]; then
		/bin/sh /var/mastools/scripts/mastoolsd stop
	fi
}

# Called by CLI 'show admparameter'
# Called to get value of autoconnect in CONFIG_FILE.
# Exits with exit-code ERRCODE_ENABLED when autoconnect=1
# Exits with exit-code ERRCODE_DISABLED otherwise
get_autoconnect_status()
{
	if [ -f "${CONFIG_FILE}" ]; then
		. $CONFIG_FILE
		if [ $autoconnect_status = 1 ]; then
			exit ${ERRCODE_ENABLED}
		fi
	fi
	exit ${ERRCODE_DISABLED}
}

#Called by nsstartpe.sh at startup
startup_admautoregd()
{
    if [ "$is_sdx" = true ] ; then
        stop_admautoregd;
        stop_monit_on_admautoregd;
    	/bin/sh /var/mastools/scripts/mastoolsd stop
		if [ "$sdx_auto_reg" = true ]; then
		    # If enabled start admautoregd and mastools
            echo `$timestamp` 'sdx setup, auto reg state is true'  >> /var/mastools/logs/adm_ctl.log
			start_admautoregd;
			start_monit_on_admautoregd;
			# Start Mastools.
			# Only upgrade daemon will start if mastools is not enabled
			/bin/sh /var/mastools/scripts/mastoolsd start
		else
		    # If disabled do not start admautoregd
		    # Check for internal system
		    internal_autoreg_cmd='/var/python/bin/python /var/mastools/scripts/admautoreg/check_internal.py'
		    $internal_autoreg_cmd
		    ret_val=$?
		    if [ $ret_val -eq 1 ]; then
			# If an internal system then start mastools and sdx internal script
			/bin/sh /var/mastools/scripts/mastoolsd start
			echo -n "admAutoReg Internal SDX Daemon"
			/var/python/bin/python ${DAEMON_BASEDIR}/${INTERNAL_AUTO_REG_FILE} &
			echo -n "Done"
		    fi
		    # If disabled do not start admautoregd
            echo `$timestamp` 'sdx setup, auto reg state is false'  >> /var/mastools/logs/adm_ctl.log
			pid=`ps -axww | awk '/adm_auto_reg_daemon/ && !/awk/ {print $1}'`
			if [ "$pid" != "" ]; then
			    kill -9 $pid
			fi
		fi
		return
    fi

	# Kill admautoregd if it is already running
	stop_admautoregd;
	stop_monit_on_admautoregd;

	#Disable by default for gateway connector
	if [ "$machine" != "Linux" ];then
	    IS_GATEWAY_CONNECTOR=$(is_gateway_connector)
	    if [ "$IS_GATEWAY_CONNECTOR" -eq 1 ]; then
		    disable_autoconnect_status;
		    return
	    fi
	fi
	
	add_nameserver;

	if [ -f "${CONFIG_FILE}" ]; then
		. $CONFIG_FILE
		if [ $autoconnect_status = 1 ]; then
			# If enabled start admautoregd and mastool
			start_admautoregd;
			start_monit_on_admautoregd;
			# Start Mastools.
			# Only upgrade daemon will start if mastools is not enabled
			/bin/sh /var/mastools/scripts/mastoolsd restart
		# Condition check to enable Console Advisory Connect and mastool if agent file is available
		elif [ -f "${MASTOOLS_CONFIGFILE}" ]; then
			# If enabled start admautoregd and mastool
			enable_autoconnect_status;
			start_admautoregd;
			start_monit_on_admautoregd;
			# Start Mastools.
			/bin/sh /var/mastools/scripts/mastoolsd restart
		else
		    if [ "$machine" = "Linux" ];then
		        :
		    fi
		        # If disabled do not start admautoregd
		fi
	else
		# It is first-time boot: start admautoregd and mastool
		enable_autoconnect_status;
		start_admautoregd;
		start_monit_on_admautoregd;
		# Start Mastools.
		# Only upgrade daemon will start if mastools is not enabled
		/bin/sh /var/mastools/scripts/mastoolsd restart
	fi
}

restart_if_running()
{
	if [ "$is_sdx" = true ] ; then
		sdx_db_exist_cmd='/usr/local/bin/python /var/mastools/scripts/mastools_util.py -is_auto_conn_db_exist'
		$sdx_db_exist_cmd
		ret_val=$?
		echo `$timestamp` "get auto reg table exists from db returns" $ret_val >> /var/mastools/logs/adm_ctl.log
		# This is to handle a corner case, when the user install 13.0-61.x RTM, we need to check
		# in mastools upgrade, if sdx db table exists, if not, we will just return without doing
		# anything
		if [ $ret_val -eq ${STATE_FALSE_EXIT_CODE} ] ; then
		    return
        fi

		if [ "$sdx_auto_reg" = true ]; then
		    stop_monit_on_admautoregd;
		    echo "Restarting admautoregd in sdx"
		    start_admautoregd;
		    start_monit_on_admautoregd;
		else 
			echo -n "admAutoReg Internal SDX Daemon"
			/var/python/bin/python ${DAEMON_BASEDIR}/${INTERNAL_AUTO_REG_FILE} &
			echo -n "Done"
		fi
	elif [ -f "${CONFIG_FILE}" ]; then
		. $CONFIG_FILE
		if [ $autoconnect_status = 1 ]; then
			stop_monit_on_admautoregd;
			echo "Restarting admautoregd"
			start_admautoregd;
			start_monit_on_admautoregd;
		fi
	fi
}

show_status()
{
	if [ -f "${PID_DIR}/${PID_FILE}" ]; then
		echo "AdmAutoReg deamon is running"
		cat ${PID_DIR}/${PID_FILE} | xargs ps -p
	else
		echo "AdmAutoReg deamon is not running"
	fi
}

start_monit_on_admautoregd()
{
	if [ "$machine" = "Linux" ];then
	# already started during bootup. check status by running systemctl status blx-admautoregd-monit.service
		return
	fi
	CHECK_ADMAUTOREGD_PROCESS="check process admautoregd with pidfile /var/run/admautoregd.pid every 10 cycles"

	if test "`grep \"$CHECK_ADMAUTOREGD_PROCESS\" $MONITRC`"
	then
		return
	fi

	echo "## Check admautoregd, a netscaler daemon" >> $MONITRC
	echo $CHECK_ADMAUTOREGD_PROCESS >> $MONITRC
	echo "  start program  \"/bin/sh /var/mastools/scripts/admautoreg/admautoregd_ctl start\"" >> $MONITRC
	echo "  stop program   \"/bin/sh /var/mastools/scripts/admautoreg/admautoregd_ctl stop\"" >> $MONITRC
	echo "  if 3 restarts within 30 cycles then timeout # stop monitoring admautoregd process if failing to restart after 30 cycles " >> $MONITRC

	killall -HUP monit
}

stop_monit_on_admautoregd()
{
	grep -v admautoregd ${MONITRC} > ${MONITRC}.bak
	chmod 600 ${MONITRC}.bak
	mv ${MONITRC}.bak ${MONITRC}
	if [ "$machine" = "Linux" ];then
	    pkill -HUP monit
	else
	    killall -HUP monit
	fi
}

# Called by CLI 'show admparameter'
# Called to get value of adc_lodestone_enable in admautoreg.state file.
get_onboardenable_status() {
	pattern=adc_lodestone_enable
	if [ "$is_sdx" = true ] ; then
		file=${SVM_ADMAUTOREG_STATE_FILE}
	else
		file=${ADMAUTOREG_STATE_FILE}
	fi
	read_state_status $pattern $file
}

# Generic code to get boolean state file values
# Exits with exit-code ERRCODE_ENABLED when pattern=1
# Exits with exit-code ERRCODE_DISABLED when pattern=0
# $1 -> pattern $2 ->file path
read_state_status(){
	pattern=$1
	file=$2
	if [ -f "$file" ]; then
		state_status=$(awk -F "=" '/'${pattern}'/ {print $2}' $file);
		if [ $state_status = True ]; then
			exit ${ERRCODE_ENABLED}
		elif [ $state_status = False ]; then
			exit ${ERRCODE_DISABLED}
		else
		    if [ "$machine" = "Linux" ];then
		        :
		    fi
			# Will return the code 0 from the cli end
		fi
		
	fi
}

add_nameserver(){
	internal_autoreg_cmd='/var/python/bin/python /var/mastools/scripts/admautoreg/check_internal.py'
	$internal_autoreg_cmd
	ret_val=$?

	if [ "$ret_val" -eq 1 ]; then
		# If internal start admautoregd
		enable_autoconnect_status;
		if [ -f "${BLX_ENVRON_FILE}" ]; then
			NS_APPLIANCE=$(grep '^NS_APPLIANCE=' "${BLX_ENVRON_FILE}" | head -n 1 | cut -d= -f2 | tr -d '[:space:]')
			VPX_ON_CLOUD=$(grep '^VPX_ON_CLOUD=' "${BLX_ENVRON_FILE}" | head -n 1 | cut -d= -f2 | tr -d '[:space:]')
		fi

		if [ "$NS_APPLIANCE" -eq 1 ]; then
			if [ -n "$VPX_ON_CLOUD" ]; then
				is_vpx_on_cloud="$VPX_ON_CLOUD"
			fi
		else
			sysctl_val=$(sysctl -n netscaler.vpx_on_cloud)
			if [ -n "$sysctl_val" ]; then 
				is_vpx_on_cloud="$sysctl_val"
			fi
		fi

		# Add nameserver for OnPrem and OpenStack
		if [ "$is_vpx_on_cloud" -eq 0 ] || [ "$is_vpx_on_cloud" -eq 2 ]; then
			if [ -e "/nsconfig/.nameserverexception" ]; then
				echo "$timestamp Adding nameserver 8.8.8.8 skipped." >> /var/mastools/logs/adm_ctl.log
			else
				addnameserv_cmd=$(/netscaler/nsremotexec 127.0.0.1 -exec "add nameServer 8.8.8.8 -state ENABLED")
				nameserv_result=$(echo "$addnameserv_cmd" | sed -n '2p')
				echo `$timestamp` "Adding nameserver 8.8.8.8:" $nameserv_result >> /var/mastools/logs/adm_ctl.log
			fi
		fi
	fi
}

is_gateway_connector(){
	is_ngs_connector=0
	if [ "$machine" != "Linux" ]; then
		sysctl_val=$(sysctl -n netscaler.is_ngs_connector)
		if [ -n "$sysctl_val" ]; then
			is_ngs_connector=$((sysctl_val))
		fi
	else
		if [ -n "$IS_NGS_CONNECTOR" ]; then
			is_ngs_connector=$((IS_NGS_CONNECTOR))
		fi
	fi

	echo "$is_ngs_connector"
}

echo  `$timestamp` $1 >> /var/mastools/logs/adm_ctl.log

case $1 in
start)
		enable_autoconnect_status;
		start_admautoregd;
		;;
stop)
		disable_autoconnect_status;
		stop_admautoregd;
		;;
full_start)
		full_start;
		;;
full_stop)
		full_stop;
		;;
restart_if_running)
		restart_if_running;
		;;
start_monit_admautoregd)
		start_monit_on_admautoregd;
		;;
stop_monit_admautoregd)
		stop_monit_on_admautoregd;
		;;
status)
		show_status;
		;;
startup)
		startup_admautoregd;
		;;
autoconnect_enable)
		autoconnect_enable;
		;;
autoconnect_disable)
		autoconnect_disable;
		;;
get_autoconnect_status)
		get_autoconnect_status
		;;
stop_autoreg)
		stop_admautoregd;
		;;
get_onboardenable_status)
		get_onboardenable_status;
		;;
help)
		usage;
		;;
*)
		echo "admautoregd_ctl: no argument";
;;
esac
