#!/bin/bash
#check_dhcp_ext v0.3

NMAP="/usr/bin/nmap"
SUDO="/usr/bin/sudo"

if [ $# -ge 1 ]
then
	#check if exists where we expect it
	if  [ -e $SUDO ]
	then
   		#check if nmap exists where we expect it
		if [ -e $NMAP ]
   		then
			#check if we have 2 arguments and if the first one is dhcpdiscover
			if [[ $# -eq 2 && "$1" =~ "DHCPDISCOVER" ]];
			then
	        		RESULTTEMP=$($SUDO $NMAP -sU -p67 --script=dhcp-discover --script-args='dhcptype=DHCPDISCOVER' $2 \
				 | /bin/grep "IP Offered\|IP Address\|DHCP\|Server\|Subnet\|Router\|Domain\|NetBIOS\|MAC")

				#Re-arrange order of answers for consistency with other scan types
				RESULTONE=$(echo $RESULTTEMP | cut -d '|' -f 3,4) 
				RESULTTWO=$(echo $RESULTTEMP | cut -d '|' -f 2,5-)
				RESULT="${RESULTONE}|${RESULTTWO}" 

			else
				RESULT=$($SUDO $NMAP -sU -p67 --script=dhcp-discover $1 | /bin/grep "DHCPACK\|Server\|Router\|Domain\|Netbios\|MAC")
				RESULT=${RESULT:3}
			fi

			#Clean up results
			#remove a _ at end (only end one incase some info contains _
			RESULT=${RESULT/|_/|}
			#replace all | with -
			RESULT=${RESULT//|/-}
			#separate MAC section with - like all other sections
			RESULT=${RESULT/MAC/- MAC}
			#replace first - with | for nagios status / data sections
			RESULT=${RESULT/-/|}

			#Check if result is valid
		        if  [[ ($RESULT =~ 'IP Offered' || $RESULT =~ 'DHCPACK') && $RESULT =~ 'MAC' ]];
		        then
		        echo "DHCP OK:" $RESULT
			else
			#double adding result for nagios status / data sections
			echo "DHCP Not OK: No valid DHCP response, got" $RESULT " | " $RESULT
		        fi
		else
		echo "Script Input Error : Unknown NMAP location, Aborting."
		fi
	else
	echo "Script Error : Run script as root for NMAP priviledges."
	fi
else
echo "Script Error : Script needs a hostname to run against."
echo $0 "<dhcp-server-hostname>"
echo $0 "DHCPDISCOVER <dhcp-server-hostname>"
fi
