#!/bin/ksh -p
#pragma ident "@(#)jdupdate	1.8 96/11/25 SMI"
#
# Copyright 11/25/96 Sun Microsystems, Inc. All Rights Reserved
#
# Synopsis: jdupdate

[[ $(id) == uid=0\(root\)* ]] || {
	print "Must be run as root"
	exit 1
}

fullname=$(whence $0)
dirname=${fullname%/*}
export PATH=$dirname:$PATH
export FPATH=${dirname%%/bin*}/lib

# Add boottype to JavaDesktop entries that don't have it

bootparams=/etc/bootparams
[[ -f $bootparams ]] && {
	trap "rm -f $bootparams.$$" EXIT
 
	nawk -f - $bootparams > $bootparams.$$ <<-FINIS
	/:\/export\/root\/JavaDesktop\$/  { print \$0, "boottype=:js"; next }
					  { print }
	FINIS

	cp $bootparams.$$ $bootparams
 
	rm -f $bootparams.$$
 
	trap - EXIT
}

# Convert from BOOTP to DHCP

# Comment out bootpd in /etc/inetd.conf if it's there

inetd=/etc/inetd.conf
[ -f $inetd ] || {
	print "$inetd does not exist"
	exit 1
}

trap "rm -f $inetd.$$" 0

nawk -f - $inetd > $inetd.$$ <<-FINIS
BEGIN			{ OFS = "" }
\$1 == "bootps"		{ print "#", \$0
			  next
                        }
			{ print }
FINIS
cp $inetd.$$ $inetd
rm -f $inetd.$$

trap 0

ps -e | nawk '/inetd/	{ system("kill -HUP " $1) }'

# Delete bootptab entries and make equivalent DHCP entries and
# move bootptab someplace where it won't be used

bootptab=/etc/bootptab
[[ -f $bootptab ]] && {

	print "Converting from BOOTP to DHCP"

	# Convert global variables

	args=$(nawk '
	BEGIN			{ FS = ":"
				  dn = "-"
				  ds = "-"
				  sm = "-"
				  gw = "-"
				  yd = "-"
				}
	$1 == ".JavaDesktop"	{ found = 1; next }
	! found			{ next }
	$2 ~ "dn="		{ dn = substr($2, 4) }
	$2 ~ "ds="		{ ds = substr($2, 4) }
	$2 ~ "sm="		{ sm = substr($2, 4) }
	$2 ~ "gw="		{ gw = substr($2, 4) }
	$2 ~ "yd="		{ yd = substr($2, 4) }
				{ if (substr($0, length(), 1) != "\\")
					found = 0
				}
	END			{ print dn " " ds " " sm " " gw " " yd }
	' $bootptab
	)

	[[ -n $args ]] && {
		set $args 
		jdhostgbl $@
	}

	# Find each JavaStation in /etc/bootptab and add it to DHCP table

	stations=$(nawk -F: '
		$1 ~ "#"	    {next}
		/:tc=.JavaDesktop/  {print $1}
	' $bootptab)
	ps -e | nawk '/bootpd/	{ system("kill " $1) }'
	mv $bootptab $bootptab.old
	print "$bootptab renamed $bootptab.old -- you may remove it if"
	print "\tdesired since DHCP doesn't use it"

	[[ -z $stations ]] && exit 0

	for js in $stations
	do
		ip=$(name_to_ip $js)
		net=$(net_number $ip)
		cid=$(client_id $(name_to_enet $js))
		pntadm -A $ip -c JavaStation -e -1 -f 'MANUAL+PERMANENT' \
			-i $cid -m $js $net
		ec=$?
		(( $ec < 4 )) || {
			print -n -- "pntadm -A $ip -c JavaStation -e -1 "
			print -- "-f 'MANUAL+PERMANENT' -i $cid -m $js $net"
			print -n "FAILED with error $ec -- DHCP configuration "
			print "must be completed manually."
			print -n "Some or all of the following hosts need to "
			print "be added to DHCP database:"
			for i in $stations
			do
				print "\t$i"
			done
			print "see pntadm(1m) for more information"
			exit 1
		}
	done

	print "DHCP conversion successful"
}

exit 0
