#!/bin/sh
#
# stop the sc_daemons an clear the leases file of dhcpd, then start the sc_daemons
#
# $Id: sc_restart_daemons 5787 2008-09-03 15:33:31Z joergs $
#

. /etc/sysconfig/dhcpd
. /etc/smartclient/leases2ldap

sc_daemons_list="/usr/sbin/rcsc_controld /usr/sbin/rcsc_ldap2dnsdhcpd"
sleep_time=3

# stop the daemons
for script in $sc_daemons_list; do
	$script stop
	sleep $sleep_time
	if [ -z "$sc_daemons_rev_list" ]; then
		sc_daemons_rev_list="$script"
	else
		sc_daemons_rev_list="$script $sc_daemons_rev_list"
	fi
done

# clear the IPC Shared Memory Segment and Semaphore Array
awkout=`ipcs | awk '
	BEGIN {
		shmbeg = 0
		sembeg = 0
		shmkey = ""
		semkey = ""
	}
	{
		if (shmbeg == 1) {
			if ($0 !~ /^$/) {
				if ($3 == "scadmin") {
					shmkey = $1
				}
			}
			else {
				shmbeg=0
			}
		}
		if (sembeg == 1) {
			if ($0 !~ /^$/) {
				if ($3 == "scadmin") {
					semkey = $1
				}
			}
			else {
				sembeg=0
			}
		}
	}
	/Shared Memory Segments/ && shmbeg == 0 {shmbeg = 1}
	/Semaphore Arrays/ && sembeg == 0 {sembeg = 1}
	END {
		printf "shmkey=\"%s\";semkey=\"%s\"", shmkey, semkey
	}'`
eval $awkout
if [ -n "$shmkey" ]; then
	echo "Clearing IPC Shared Memory Segment of sc_ldap2dnsdhcpd/sc_controld (owner scadmin)"
	ipcrm -M $shmkey
fi
if [ -n "$semkey" ]; then
	echo "Clearing IPC Semaphore Array of sc_ldap2dnsdhcpd/sc_controld (owner scadmin)"
	ipcrm -S $semkey
fi

$LEASES2LDAP_STOP_DHCPD
# clear the leases file of dhcpd
echo -n "Clearing Leases-File of DCHPD (this could take a while) ..."
/usr/sbin/sc_cleardhcpdleases.pl $LEASES2LDAP_LEASES_FILE $LEASES2LDAP_CLEARED_LEASES_FILE
echo " done"
$LEASES2LDAP_START_DHCPD

# start the daemons
for script in $sc_daemons_rev_list; do
	$script start
	sleep $sleep_time
done

exit 0
