#!/bin/sh

# processes kernel commandline arguments relevent to nfsroot and whatnot

# generates variables similar to those used by udhcpc

. /etc/lessdisks/mkinitrd/initrd-netboot.conf

if [ -z "$cmdline_opts" ]; then
  tempfile=/tmp/cmdline_opts.conf
  echo "WARNING: cmdline_opts not set, setting to default... $tempfile"
else
  tempfile="$cmdline_opts"
fi

test -z "$cmdline" && cmdline=/proc/cmdline

test -r "$cmdline" || exit 1

cmdline_options=$(cat $cmdline)

get_field() {
  opts="$3"
  if [ -z "$opts" ]; then
    # only use lines with delimeter, use : as delimeter
    opts="-s -d :"
  fi
  echo $1 | cut $opts -f $2
}

parse_ip(){
  stuff=${1##ip=}
  # nfsaddrs is an alias for ip, but the syntax is the same.
  stuff=${stuff##nfsaddrs=}
  # ip=x.x.x.x or ip=x.x.x.x:x.x.x.x:x.x.x.x:... are valid formats
  # the first doesn't use a colon, other options require the colon
  ip=$(get_field $stuff 1 "-d :")
  if [ -z "$siaddr" ]; then
    siaddr=$(get_field $stuff 2)
  fi
  gw_ip=$(get_field $stuff 3)
  subnet=$(get_field $stuff 4)
  hostname=$(get_field $stuff 5)
  interface=$(get_field $stuff 6)
  autoconf_type=$(get_field $stuff 7)
}

for opt in $cmdline_options ; do
  case $opt in
    ip=dhcp|nfsaddrs=dhcp) autoconf_type=dhcp ; ip="" ;;
    ip=bootp|nfsaddrs=bootp) autoconf_type=bootp ; ip="" ;;
    # nfsaddrs is older style
    ip=*|nfsaddrs=*) parse_ip $opt ;;
    root=*) rootdev="${opt##root=}" ;;
    nfsroot=*) opt="${opt##nfsroot=}" 
      nfspath="$(echo $opt | cut -d : -f 2 | cut -d , -f 1)" 
      t="$(echo $opt | cut -s -d : -f 1)"
      if [ -z "$siaddr" ] && [ -n "$t" ]; then
        siaddr="$t"
        echo "setting siaddr $siaddr"
      fi
      t="$(echo $opt | cut -s -d , -f 2,3,4,5,6,7,8,9,10,11,12,13,14)"
      test -n $t && nfs_opts="$t"
    ;;
  esac
done

# need write access to /tmp
test -w /tmp/ || mount -nt tmpfs tmpfs /tmp

test -n "$nfspath" && echo nfspath=$nfspath > $tempfile
test -n "$siaddr" && echo siaddr=$siaddr >> $tempfile
test -n "$nfs_opts" && echo nfs_opts=\"$nfs_opts\" >> $tempfile
test -n "$rootdev" && echo rootdev=$rootdev >> $tempfile
# FIXME: init scripts appear to export kernel commandline values derived from
# /proc/cmdline
echo ip=$ip >> $tempfile
test -n "$gw_ip" && echo gw_ip=$gw_ip >> $tempfile
test -n "$subnet" && echo subnet=$subnet>> $tempfile
test -n "$hostname" && echo hostname=$hostname >> $tempfile
test -n "$interface" && echo interface=$interface >> $tempfile
test -n "$autoconf_type" && echo autoconf_type=$autoconf_type >> $tempfile
