#!/opt/psh/bin/psh

#
# Copyright (c) 1998 Sun Microsystems, Inc.
# 
# This software is provided by Sun ``AS IS'' and any express or implied
# warranties, including, but not limited to, the implied warranties of
# merchantability and fitness for a particular purpose are disclaimed.
# In no event shall Sun Microsystems be liable for any direct, indirect,
# incidental, special, exemplary, or consequential damages.
# 
# This software is not a product, and is provided for evaluation purposes
# only.
# 
# This software may not be resold without the express permission of
# Sun Microsystems.
# 
#ident	"@(#)inform	1.2	98/07/14 SMI"
#

set bootpc	68
set bootps	67
set srv_timeout 15000;		# msec
set slp_timeout 10;		# sec
set xid		42;

proc dhcp_client_add { cl_ethaddr srv_ipaddr } {

	global argv0 bootpc bootps srv_timeout cl_ipaddr xid

	# make all the packets we'll need up front
	foreach i { inform ack } {
		pinit bootpc $i - - $i
	}

	popen socket ep inet dgram udp
	ep.bind $cl_ipaddr/$bootpc

	# initialize INFORM packet
	eval pset inform bootpc chaddr	$cl_ethaddr
	pset inform bootpc xid		0xbaadcafe
	eval pset inform bootpc ciaddr	$cl_ipaddr
	
	puts "$argv0: sending INFORM packet to $srv_ipaddr, port $bootps"
	puts "$argv0: using IP address $cl_ipaddr in INFORM ciaddr"

	ep.sendto inform 0 $srv_ipaddr/$bootps
	if { [ep.recvfrom ack 0 $srv_timeout] == "timeout" } {
		puts "$argv0: no response to INFORM packet"
		return;
	}
	puts "$argv0: received response to INFORM packet from $srv_ipaddr"
	puts [plist ack]
	
	# free all the packets
	foreach i { inform ack } {
		pfree $i
	}
}

#
# if no one passed us an ether addr, try to find one
#

if { [expr $argc < 2] } {
	puts "$argv0: no client ethernet address given, trying to find one..."

	regsub -all ":" [lindex [exec ifconfig -a | grep BROADCAST] 0] "" i
	regsub -all ":|^" [lindex [exec ifconfig $i ether | tail +2] 1] " 0x" \
	    cl_ethaddr
	set srv_ipaddr "255.255.255.255"
} else {
	regsub -all ":|^" [lindex $argv 0]" " 0x" cl_ethaddr 
	set srv_ipaddr [lindex $argv 1]
}

set cl_ipaddr [lindex [exec ifconfig -a | egrep inet | egrep -v 127.0.0.1] 1]

puts "$argv0: using (ethernet addr `$cl_ethaddr')"
dhcp_client_add "$cl_ethaddr" "$srv_ipaddr"
