#!/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: krejzi $
#$Date: 2012-08-14 22:00:47 +0000 (Tue, 14 Aug 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/lib/dhclient/dhclient-$1.leases
}

# Make compatible with older versions of init-functions
unset is_true

is_true()
{
   [ "$1" = "1" ] || [ "$1" = "yes" ] || [ "$1" = "true" ] ||
   [ "$1" = "y" ] || [ "$1" = "t" ]
}

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

      exec /sbin/dhclient -lf /var/lib/dhclient/dhclient-$1.leases -pf /var/run/dhclient-$1.pid $DHCP_START $1

      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..."

      exec /sbin/dhclient -r -lf /var/lib/dhclient/dhclient-$1.leases -pf /var/run/dhclient-$1.pid $DHCP_STOP $1
      evaluate_retval
   ;;

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

# End services/dhclient
