#!/bin/sh

# Copyright (c) 2017 Control Products Inc.
# All rights reserved
#
# Author: Michael Borntrager, 2017
#
# Description: Monitor state of ethernet, if it comes up and doesn't have an IP address
# run dhcp.

interface="eth0"

if [[ ! -z $1 ]]; then
	interface=$1
fi

old_operstate="up"

#remove file if exists prior to creating the first one
rm /var/run/udhcpc.$interface.pid

while [[ 1 ]]; do
	operstate=$(cat /sys/class/net/$interface/operstate)

	if [[ "$operstate" == "up" ]]; then
		if [[ "$operstate" != "$old_operstate" ]]; then

			if cat /etc/network/interfaces | grep "$interface inet dhcp"; then
				#dhcp
				kill -9 $(cat /var/run/udhcpc.$interface.pid)
				udhcpc -R -n -p /var/run/udhcpc.$interface.pid -i $interface
			fi
		fi
	fi

	old_operstate="$operstate"

	sleep 5
done
