#!/bin/bash

# Parse the /var/lib/dhcp/dhclient.leases file for one of the following options:

#  fixed-address		(Returns IP Address assigned by DHCP server, ex: 192.168.0.140)
#  subnet-mask 			(Returns IP Address, ex: 255.255.255.0)
#  tftp-server-name 		(Returns IP Address, ex: 192.168.0.106)
#  dhcp-server-identifier 	(Returns IP Address, ex: 192.168.0.133)

# Find the right leases file for parameters

LFILE=/var/lib/dhcp/dhclient.leases
DHCLIENT_PS=(`ps -C dhclient -o args --no-header`)
for SUBSCRIPT in ${!DHCLIENT_PS[*]}; do
	if [ -z "${DHCLIENT_PS[$SUBSCRIPT]/%*leases/}" ]; then
		LFILE=${DHCLIENT_PS[$SUBSCRIPT]}
		break
	fi
done

DHCP_OPTION=$1

# Parse the information from last lease, handle cases with not information provided by DHCP
TEMP=`sed -n -e :a -e '/\(;\|{\)$/N; s/\n//;ta' -e '$!d' -e "s/.*${DHCP_OPTION}\s\+\(.*\)/\1/;T" -e "s/\(.*\);\s\+option\1\(.*\)/\1/p" $LFILE`
/usr/local/bin/dhcp_option2string "$DHCP_OPTION" "$TEMP"
