#! /bin/sh -e
#
# Script to be called by ipsetd when IP address has changed.
#

exec 2>/dev/console
#set -x

funcsf=/etc/init.d/functions.sh
[ -r $funcsf ] || {
	echo "$0: $funcsf not found" >&2
	exit 1
}
. $funcsf || {
	echo "0: failed to source $funcsf" >&2
	exit 1
}

[ "$IFNAME" ] || error "interface name missing"

dhcp4rcf=$RCLIB/sh/rc-dhcp.sh
[ -r $dhcp4rcf ] || error "$dhcp4rcf not found"
. $dhcp4rcf || error "failed to source $dhcp4rcf"

[ ! -r $RCLIB/sh/messages.sh ] || . $RCLIB/sh/messages.sh

max_dozeoff=60
dozeoff=$max_dozeoff
ival=1

# Need the parhand daemon started; check.
while [ $dozeoff -gt 0 ]; do
	[ -z "$(pidof parhand)" ] || break
	sleep $ival
	dozeoff=$(($dozeoff - $ival))
done
[ $dozeoff -gt 0 ] || error "the parhand daemon won't start"

# Parhand daemon just started; give it some time to initialize.
[ $dozeoff -eq $max_dozeoff ] || sleep $(($ival * 2))

# Handle locking
lockfn=$DHCP4_DAEMON.$IFNAME
create_lock_file $lockfn
trap 'remove_lock_file $lockfn' EXIT

# Need to make sure the dhcp client is dead.
if check_dhcp $IFNAME; then
	dozeoff=$max_dozeoff
	stop_dhcp $IFNAME || error "stop_dhcp shouldn't fail"

	while [ $dozeoff -gt 0 ]; do
		sleep $ival
		check_dhcp $IFNAME || break
		dozeoff=$(($dozeoff - $ival))
	done

	[ $dozeoff -gt 0 ] || error "the dhcp client won't die"
else
	warning "dhcp check failed"
fi

nsm=255.0.0.0
nb=$NEW_IP_ANET.255.255.255

all_in_one="root.Network.IPAddress=$NEW_IPADDR
root.Network.SubnetMask=$nsm
root.Network.Broadcast=$nb
root.Network.DefaultRouter=
root.Network.BootProto=none"
if echo "$all_in_one" | parhandclient --nosync setparams - sync; then
	logger -p daemon.info "$0: New IP address: '$NEW_IPADDR'"
else
	logger -p daemon.err 		"$0: Failed to change IP address to '$NEW_IPADDR'!"

	# Some parameters may have been changed. Let's at least sync...
	parhandclient sync
	# ...and start the dhcp client if needed.
	[ "$(parhandclient --nocgi get Network.BootProto - RAW)" != dhcp ] ||
		start_dhcp $IFNAME
	exit 1
fi

exit 0
