#!/bin/bash
# Begin services/dhclient

# Origianlly based upon lfs-bootscripts-1.12 $NETWORK_DEVICES/if{down,up}
# Rewritten by Nathan Coulson <nathan@linuxfromscratch.org>
# Adapted for dhclient by DJ Lucas <dj@linuxfromscratch.org>
# Update for LFS 7.0 by Ken Moffat <ken@linuxfromscratch.org>

# Call with: IFCONFIG=<filename> /lib/services/dhclient <IFACE> <up | down>

#$LastChangedBy: bdubbs $
#$Date: 2012-04-09 19:48:51 +0000 (Mon, 09 Apr 2012) $

. /lib/lsb/init-functions
. $IFCONFIG

getipstats()
{
   # Print the last 16 lines of dhclient.leases
   sed -e :a -e '$q;N;17,$D;ba' /var/state/dhclient.leases
}

case "$2" in
   up)
      log_info_msg "\nStarting dhclient on the $1 interface..."

      /sbin/dhclient $1 $DHCP_START

      if [ "$?" != "0" ]; then 
        log_failure_msg2
        exit 1
      fi

      # Print the assigned settings if requested
      if [ is_true "$PRINTIP"  -o is_true "$PRINTALL" ]; then
        # Get info from dhclient.leases file
        
        IPADDR=`getipstats | grep "fixed-address" | \
          sed 's/ fixed-address //' | \
          sed 's/\;//'`
        
        NETMASK=`getipstats | grep "subnet-mask" | \
          sed 's/ option subnet-mask //' | \
          sed 's/\;//'`
      
        GATEWAY=`getipstats | grep "routers" | \
          sed 's/ option routers //' | \
          sed 's/\;//'`
      
        DNS=`getipstats | grep "domain-name-servers" | \
          sed 's/ option domain-name-servers //' | \
          sed 's/\;//' | sed 's/,/ and /'`

        if [ "$PRINTALL" = "yes" ]; then
           # This is messy, the messages are on one very long
           # line on the screen and in the log
           log_info_msg "           DHCP Assigned Settings for $1:"
           log_info_msg "           IP Address:      $IPADDR"
           log_info_msg "           Subnet Mask:     $NETMASK"
           log_info_msg "           Default Gateway: $GATEWAY"
           log_info_msg "           DNS Server:      $DNS"
        else
           log_info_msg " IP Addresss:""$IPADDR"
        fi
      fi

      log_success_msg2
   ;;

   down)
      log_info_msg "Stopping dhclient on the $1 interface..."

      if [ -z "$DHCP_STOP" ]; then
         # This breaks multiple interfaces please provide
         # the correct stop arguments.
         killproc dhclient
      else
         /sbin/dhclient $1 $DHCP_STOP
         evaluate_retval
      fi
   ;;

   *)
      echo "Usage: $0 [interface] {up|down}"
      exit 1
   ;;
esac

# End services/dhclient
