#!/bin/sh

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

leases_file=/var/lib/dhcp/dhclient.leases

getServer() {
  leases_file="$2"
  if [ -z "$leases_file" ]; then
    leases_file=/var/lib/dhcp/dhclient.leases
  fi
  # TODO replace "head -n 1" with something more flexible?
  grep "$1" "$leases_file" | tr -s "\t" " " | cut -d " " -f 4 | tr -d ";" | head -n 1
}

# TODO how to get it to actually work just using "next-server" ??
for try_type in next-server tftp-server-name dhcp-server-identifier; do
  server=$(getServer $try_type $leases_file)
  if [ -n "$server" ]; then
    break
  fi
done

if [ -z "$server" ]; then
  exit 1
fi

server=$(echo $server | tr -d '\"')

nfsroot=$(grep "root-path" "$leases_file" | tr -s "\t" " " | cut -d " " -f 4 | tr -d "\"" | tr -d ";" | head -n 1)
fs_type=nfs
fs_options=ro,async,nolock

echo "attempting to mount NFS filesystem..."

modprobe nfs

command="mount -nt $fs_type -o $fs_options $server:$nfsroot /mnt"
echo "$command"
$command
status="$?"
if [ "0" != "$status" ]; then
  # call a shell up for debugging, since we couldn't mount NFS root...
  /bin/sh
fi

chroot /mnt mount -nt devfs devfs dev
umount /var/lib/dhcp
