#!/bin/bash
#
# test-dhcp
#
# Usage:
#   test-dhcp IFACE [PEER_IPADDRESS [PEER_MAC]]
#
# Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL.
#
# History
# Jan-Aug 2003: Written by Thomas Hood <jdthood@yahoo.co.uk>

set -o errexit   # -e
set -o noglob    # -f

MYNAME="$(basename $0)"

# All the DHCP clients are in /sbin/ but which is under /usr/
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/share/ifupdown-roam/tests

report_err() { echo "${MYNAME}: Error: $*" >&2 ; }

test_peer()
{
	if [ ! "$PEER_IPADDRESS" ] || test-ping "$IFACE" "-" "$PEER_IPADDRESS" ${PEER_MAC:+"$PEER_MAC"} ; then
		exitstatus=0
	else
		exitstatus=1
	fi
}

IFACE="$1"
[ "$IFACE" ] || { report_err "Interface not specified.  Exiting." ; exit 1 ; }
PEER_IPADDRESS="$2"
PEER_MAC="$3"

if which dhclient > /dev/null ; then
	# TODO: Write a faster proxy script for the purposes of this test
	if dhclient -q -1 "$IFACE" >/dev/null 2>&1 ; then
		test_peer
	else
		exitstatus=1
	fi
	dhclient -q -r "$IFACE" >/dev/null 2>&1 || true
	exit "$exitstatus"
elif which pump > /dev/null ; then
	if pump --interface="$IFACE" --no-dns --no-resolvconf --script="" > /dev/null 2>&1 ; then
		test_peer
	else
		exitstatus=1
	fi
	pump -k --interface="$IFACE" > /dev/null 2>&1 || true
	exit "$exitstatus"
elif which dhcpcd > /dev/null ; then
	# Setting the proxy script to /dev/null seems to work :)
	if dhcpcd -c /dev/null "$IFACE" > /dev/null 2>&1 ; then
		test_peer
	else
		exitstatus=1
	fi
	dhcpcd -c /dev/null -k "$IFACE" > /dev/null 2>&1 || true
	[ "$exitstatus" != "0" ] || sleep 1
	exit "$exitstatus"
else
	report_err "No DHCP client found.  Exiting."
	exit 1
fi

