#!/bin/sh

# dhcpcd doesn't support a config file, just command line options.
# ifup can set some  options (-h -i -I -l) but no others.
# This wrapper adds any other options set in /etc/dhcpc/config
# (and the hostname if not set by ifup or /etc/dhcpc/config)
# and then calls the dhcpcd binary, named dhcpcd-bin.
#
# Note that this wrapper _requires_ the interface name: it doesn't support
# the eth0 default that dhcpcd proper does.

# get interface
eval INTERFACE=\${$#}

# dhcpcd will fail to start if pid file exists, so delete it
# if there is no process around. Note that calling dhcpcd -k or dhcpcd -n
# both affect running processes, so skip this for those.
keeppid=no

# determine if we will add the option to send the current hostname
sendhost=yes
if [ "$SET_HOSTNAME" = "yes" ]; then
  sethost=yes
else
  sethost=no
fi

for o 
do
   if [ $o = "-k" ]; then
      keeppid=yes
   fi
   if [ $o = "-n" ]; then
      keeppid=yes
   fi
   if [ $o = "-h" ]; then
      sendhost=no
   fi
   if [ $o = "-H" ]; then
      sethost=yes
   fi
done

ps ax | grep -v grep | grep -s dhcpcd-bin | grep -q $INTERFACE
if [ $? = 0 ] &&
   [ $keeppid = no ] 
then
    echo "Dhcpcd is already running."
    exit 0
fi
     
if [ $keeppid = no ]; then
   rm -f /var/run/dhcpcd-$INTERFACE.pid
fi

# load configuration file
if [ -f /etc/dhcpc/config ] ; then
    . /etc/dhcpc/config
fi

# Note that in the absence of /etc/dhcpc/config we play safe and disallow
# changes to /etc/resolv.conf and friends.

if [ "$SET_DNS" != "yes" ]; then
  OPTIONS="-R $OPTIONS"
fi

if [ "$SET_DOMAIN" = "yes" ]; then
  OPTIONS="-D $OPTIONS"
fi

if [ "$SET_HOSTNAME" = "yes" ]; then
  OPTIONS="-H $OPTIONS"
fi

if [ "$SET_NTP" != "yes" ]; then
  OPTIONS="-N $OPTIONS"
fi

if [ "$SET_YP" != "yes" ]; then
  OPTIONS="-Y $OPTIONS"
fi

# We tell dhcpcd to send the hostname iff the option is not 
# already set by our caller, and the hostname will not be changed 
# by dhcpcd

if [ $sendhost = yes ] &&
   [ $sethost = no ] &&
   [ -x /bin/hostname ]
then
   name=`/bin/hostname`
   if [ ${#name} != 0 ]; then
      OPTIONS="-h $name $OPTIONS"
   fi
fi

exec /sbin/dhcpcd-bin $OPTIONS $*
