#!/bin/sh
#
# Copyright (c) 2019-2025 Citrix Systems, Inc. All rights reserved.
# This software and documentation contain valuable trade
# secrets and proprietary property belonging to Citrix Systems, Inc.
# None of this software and documentation may be copied,
# duplicated or disclosed without the express
# written permission of Citrix Systems, Inc.
#
# 08/14/25
#
# This file contains shell script code needed to manage power
# cycles after Mellanox NIC firmware downgrade.
#
# usage:  sh mellanox_fw_update_pwr_cycle_mgr
#

FW_UPDATE_SUBR="./mellanox_fw_update_subr"
SCRIPTS_DIR=/var/tmp/Mellanox/scripts
STATE_MACHINE_FILE=${SCRIPTS_DIR}/mellanox_fw_update_state_machine
STATE_FLAG_FILE_NAME=.mellanox_fw_downgrade_state_flag_file
STATE_FLAG_FILE=${SCRIPTS_DIR}/${STATE_FLAG_FILE_NAME}
NSCONFIG=/nsconfig
RC_LOCAL=${NSCONFIG}/rc.local
LOCAL_LOG_FILE="/var/log/mellanoxFw.log"

local_log_msg()
{
	echo "$*"
	echo "$*" >> $LOCAL_LOG_FILE
}

#
# Load the subroutine file
#
if [ -e ${FW_UPDATE_SUBR} ] &&
   [ -f ${FW_UPDATE_SUBR} ] &&
   [ -s ${FW_UPDATE_SUBR} ]
then
	. ${FW_UPDATE_SUBR}
else
	# delete these files in case they exist
	/bin/rm ${NSCONFIG}/.developer
	/bin/rm ${RC_LOCAL}
	/bin/rm ${STATE_FLAG_FILE}
	local_log_msg ">>> ${FW_UPDATE_SUBR} does not exist!"
	local_log_msg ">>> Two power cycles must be performed manually!"
	local_log_msg ">>> Not performing power cycles for firmware downgrade."
	sleep 1
fi

#
# Make sure the state machine script exists
#
if [ ! -e ${STATE_MACHINE_FILE} ] ||
   [ ! -f ${STATE_MACHINE_FILE} ] ||
   [ ! -s ${STATE_MACHINE_FILE} ]
then
	# delete these files in case they exist
	/bin/rm ${NSCONFIG}/.developer
	/bin/rm ${RC_LOCAL}
	/bin/rm ${STATE_FLAG_FILE}
	log_msg ">>> ${STATE_MACHINE_FILE} does not exist!"
	log_msg ">>> A second power cycle must be performed manually!"
	log_msg ">>> Performing only one power cycle for firmware downgrade..."
	sleep 1
	# power-cycle the NetScaler one time only
	cleanly_power_cycle_netscaler
fi

#
# If the state flag file exists, we have already power cycled once.
#
if [ -e ${STATE_FLAG_FILE} ]
then
	/bin/rm ${NSCONFIG}/.developer
	/bin/rm ${RC_LOCAL}
	/bin/rm ${STATE_FLAG_FILE}
	log_msg ">>> Performing second power cycle for firmware downgrade..."
	sleep 1
	# power-cycle the NetScaler for the second (final) time
	cleanly_power_cycle_netscaler
else
	# set state to indicate upcoming second power cycle
	touch ${STATE_FLAG_FILE}
	# reboot into developer mode
	touch /nsconfig/.developer
	# copy script to rc.local; it will be automatically invoked after reboot
	/bin/cp ${SCRIPTS_DIR}/mellanox_fw_update_state_machine ${RC_LOCAL}
	log_msg ">>> Performing initial power cycle for firmware downgrade..."
	sleep 1
	# power-cycle the NetScaler for the first time
	cleanly_power_cycle_netscaler
fi

