#!/bin/bash

# Assumes eth1 is the external interface connected to the modem

# Only print dhclient errors if it failed
dhclient eth1 > /tmp/redhcpd 2>&1
if [ $? -ne 0 ]; then
   cat /tmp/redhcpd
fi
rm /tmp/redhcpd

# Kill the old dhclient
ps -ef --sort=start_time | grep " dhclient eth1$" | grep -v grep | awk -- '{pids[$2]=$2; lastpid=$2;} END{delete pids[lastpid]; for(pid in pids)printf "kill %d\n",pids[pid];}' | bash

# Add the correct route, delete the wrong route
route add -net 192.168.1.0 netmask 255.255.255.0 eth1 2> /dev/null
route add default gw 192.168.1.1 2> /dev/null
netstat -nr | grep ^0 | awk -- '{printf "route del default %s\n",$2;}' | grep -v 192.168 | bash

# dhclient will overwrite /etc/resolv.conf, I use dnsmasq so this is no good for me,
# undo its changes.
cp /etc/resolv.orig /etc/resolv.conf

