#!/bin/bash
#
# Copyright (c) 2016 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#

#
# This script provides in-service patching restart for haproxy
#

# The patching subsystem provides a patch-functions bash source file
# with useful function and variable definitions.
#
if [ -e "/etc/patching/patch-functions" ] ; then
   . /etc/patching/patch-functions
fi

loginfo "----------------------------------------------"
loginfo "Haproxy No-Reboot Patching Restart Request"

#
# Declare an overall script return code
#
declare -i GLOBAL_RC=$PATCH_STATUS_OK

SM_RESTART_CMD="sm-restart-safe"
SM_QUERY_CMD="sm-query"
SM_ENABLED_ACTIVE="enabled-active"
DAEMON_NAME=haproxy
NEUTRON_RESTART_CMD="/bin/neutron-restart"

# check if SM managed haproxy process is running on the controllers
if is_controller 
then
   if [ ! -f $PATCH_FLAGDIR/$DAEMON_NAME.restarted ]
   then
      ${SM_QUERY_CMD} service ${DAEMON_NAME} | grep -q ${SM_ENABLED_ACTIVE}
      if [ $? -eq 0 ] 
      then
         # The daemon is running, so restart it
         loginfo "$0: Restarting ${DAEMON_NAME}"
         ${SM_RESTART_CMD} service "${DAEMON_NAME}"
         touch $PATCH_FLAGDIR/$DAEMON_NAME.restarted

         # Wait up to 10 seconds for service to recover
         let -i UNTIL=$SECONDS+10
         while [ $UNTIL -ge $SECONDS ]
         do
            # Check to make sure it's running
            ${SM_QUERY_CMD} service ${DAEMON_NAME} | grep -q ${SM_ENABLED_ACTIVE}
            if [ $? -eq 0 ]            
			then
               break
            fi

            # Not running  Let's wait a couple of seconds and check again
            loginfo "$0: ${DAEMON_NAME} is not running, wait for 2 seconds"
            sleep 2
         done

         ${SM_QUERY_CMD} service ${DAEMON_NAME} | grep -q ${SM_ENABLED_ACTIVE}
		 if [ $? -ne 0 ]          
		 then
            # Still not running! Clear the flag and mark the RC as failed
            GLOBAL_RC=$PATCH_STATUS_FAILED
            loginfo "$0: Failed to restart ${DAEMON_NAME}"
         fi
      fi
   fi
fi

# check if it is a CPE system or a compute node
if is_cpe || is_compute 
then
   # restart neutron-agent managed haproxy processes
   if [ ! -f $NEUTRON_RESTART_CMD ]
   then
      loginfo "$0: ${NEUTRON_RESTART_CMD} is not available for restarting ${DAEMON_NAME}"
      GLOBAL_RC=$PATCH_STATUS_FAILED
   else
      loginfo "$0: Restarting neutron agent managed ${DAEMON_NAME}"
      ${NEUTRON_RESTART_CMD} --agents-using-haproxy
      if [ $? -ne  $PATCH_STATUS_OK ]
      then
         loginfo "$0: Failed to restart neutron agent managed ${DAEMON_NAME}"
         GLOBAL_RC=$PATCH_STATUS_FAILED
      fi
   fi
fi

# Exit the script with the overall return code
#
exit $GLOBAL_RC