#!/bin/bash
# Restart script for ISC DHCP running on BDDS.

if [ -z $1 ]
then
	# if no argument provided we need to reload the configuration
	# Note: if dhcp is running ok we will simply call reconfig
	# else we need to stop and start the service
	/bin/systemctl status dhcpd >> /dev/null
	retVal=$?

	# Check if the output of PsmClient indicates that dhcp-failover-enable is 0
	failover_enable_status=$(/usr/local/bluecat/PsmClient node get dhcp-failover-enable | grep -oP '(?<=dhcp-failover-enable=)\d')

	if [ "$failover_enable_status" -eq 0 ]; then
		# Check if "failover peer" is found in the dhcpd.conf file
		if grep -q "failover peer" /replicated/etc/dhcpd.conf; then
			# If failover peer is found in the conf and dhcp-failover-enable is 0,
			# we are going to need to make sure that the correct ports will be opened.        
			/usr/local/bluecat/PsmClient node set dhcp-failover-enable=1
			# Set retVal to indicate that a real restart is needed
			retVal=1
		fi
	fi

	if [ $retVal -eq 0 ]; then
		/usr/local/bluecat/PsmClient dhcpd reconfig
	else
		/usr/local/bluecat/PsmClient node set dhcp-enable=0
		/usr/local/bluecat/PsmClient node set dhcp-enable=1
	fi

	exit $?
fi

case "$1" in
	"-config")
		/usr/local/sbin/dhcpd -cf /replicated/etc/dhcpd.conf -lf /replicated/var/state/dhcp/dhcpd.leases -t
		exitCode=$?
		if [ $exitCode -eq 0 ]
		then
			/usr/local/bluecat/bcn-nsupdate-super.py -c
			exit $?
		else
			exit $exitCode
		fi
	;;

	"start")
		/usr/local/bluecat/PsmClient node set dhcp-enable=1
		exit $?
	;;

	"stop")
		/usr/local/bluecat/PsmClient node set dhcp-enable=0
		exit $?
	;;

	*)	# assume this is status
		/bin/systemctl status dhcpd >> /dev/null
		exit $?
	;;
esac
