#!/bin/sh

# copyright 2004 vagrant@freegeek.org, distributed under the terms of the
# GNU General Public License version 2 or any later version.

if [ -z "$(/sbin/ifconfig eth0)" ]; then
  echo "not configuring DHCP, no ethernet card found..."
  exit 10
fi

network_script=/etc/lessdisks/mkinitrd/network_script

# need to write to /var/lib/dhcp/dhclient.leases
mount -nt tmpfs tmpfs /var/lib/dhcp

getDhclient() {
  /sbin/dhclient

  # kill dhclient so the initrd can get un-mounted
  killall dhclient 2> /dev/null || killall dhclient-2.2.x 2> /dev/null
}

getUdhcpc() {
  /sbin/udhcpc --foreground --quit --script=$network_script
}

getCmdline() {
  for option in $(cat /proc/cmdline); do
    case $option in
      nfsroot=*) nfspath=${option##nfsroot=} ;;
      ip=*) siaddr=$(echo $option | cut -d : -f 2)
        ip=$(echo $option | cut -d = -f 2 | cut -d : -f 1)
        subnet=$(echo $option | cut -d : -f 4) ;;
    esac
  done
  interface=eth0
  export nfspath siaddr ip subnet interface
  $network_script bound
}

if [ -x /sbin/udhcpc ]; then
  echo "attempting to configure DHCP with udhcpc"
  getUdhcpc
elif [ -x /sbin/dhclient ]; then
  echo "attempting to configure DHCP with dhclient"
  getDhclient
else
  echo "no DHCP client found, attempting to get values from /proc/cmdline"
  getCmdline
fi
