#!/bin/bash
logger $0 called with $1
#echo $0 called with#$1#$2#$3#
#exit
LOGFILE="/opt/log/heartbeat.log"
DUCSERVICESCONF=/opt/conf/ducServices.conf
#
function ducServices {
  ACTION="$1"
  if [ "$ACTION" == start -o "$ACTION" == stop ]; then
    if [ -r $DUCSERVICESCONF ]; then
      while read DUC; do
	if [[ ! "${DUC}" =~ ^[[:space:]]*# ]]; then
          systemctl $ACTION duc@${DUC}
	fi
      done < $DUCSERVICESCONF
    fi
  fi
}
#
case "$1" in
start)
        # start treloproxy
        echo "start treloProxy service" >> "$LOGFILE"
        #/opt/protonyx-scripts/treloProxy-check-start.sh
        systemctl start treloProxy.service
	#echo "enabling treloProxy-check-start.sh in crontab..." >> "$LOGFILE"
        #sed -i 's/^##*\(.*treloProxy-check-start\.sh.*\)/\1/g' /var/spool/cron/root
        echo "treloProxy service has been started" >> "$LOGFILE"
        # reaactivate here
        echo "requesting a license reactivation from jetty" >> "$LOGFILE"
        # here is the "request"
        echo -n "HA slave wake up call" > /dev/shm/licenseReactivationRequest
        # and here is the wake up call
        echo -n "HA slave wake up call" > /dev/udp/127.0.0.1/54321
        # restart netBalancer
        echo "restarting NetBalancer service" >> "$LOGFILE"
        #/opt/protonyx-scripts/restartNetBalancerDaemonsWithoutReboot.sh
	systemctl restart balancer.service
	# start DUC services
	ducServices start
        ;;
stop)
        # do not stop netBalancer
        #echo "stopping NetBalancer service" >> "$LOGFILE"
        #/opt/protonyx-scripts/stopNetBalancerDaemons.sh
        # stop DUC services
	ducServices stop
        # stop treloproxy
        echo "stop treloProxy service" >> "$LOGFILE"
        systemctl stop treloProxy.service
	#echo "disabling treloProxy-check-start.sh in crontab..." >> "$LOGFILE"
        #sed -i 's/^[^#].*treloProxy-check-start\.sh.*/#&/g' /var/spool/cron/root
        #PIDS=`ps aux|grep java|grep -v "comboxManager"|grep combox|awk '{ print $2 }'`
        #while read PID; do
                # well, now the PID may be empty so to be on
                # the safe side, we require it to be a number
        #        re='^[0-9]+$'
        #        if [[ $PID =~ $re ]] ; then
        #                echo "Now running kill $PID" >> "$LOGFILE"
        #                kill $PID
        #        fi
        #done <<< "$PIDS"
        echo "treloProxy service has been stopped" >> "$LOGFILE"
        # clean the chains before populating them
        arptables -F HEARTBEAT_IN
        arptables -F HEARTBEAT_OUT
        ;;
esac

