#!/bin/sh
# geninitrd mod: nfs

# if we should init NFS at boot
have_nfs=no

# return true if node is nfs
# @param	string $node device node to be examined
# @access	public
is_nfs() {
	local node="$1"

	if is_yes "$(awk -vnode="$node" 'BEGIN { if (node ~ /^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:|\/dev\/nfs)/) print "yes" }')"; then
		return 0
	fi

	return 1
}

# find modules for for nfs
# @access	public
find_modules_nfs() {
	local devpath="$1"

	if [ ! -x /usr/bin/pcidev -a -z "$NFS_ETH_MODULES" ]; then
		die "root on NFS but /usr/bin/pcidev not found. Please install correct pci-database package and rerun $PROGRAM."
	fi

	if [ ! -f /proc/bus/pci/devices ]; then
		warn "Remember to add network card modules in /etc/sysconfig/geninitrd, example:"
		warn "BASICMODULES=\"e1000 ne2k-pci mii 8139too 3c59x\""
	else
		local m
		[ -z "$NFS_ETH_MODULES" ] && NFS_ETH_MODULES=$(/usr/bin/pcidev /m net | xargs)
		msg "NOTE: Network card(s) module(s) $NFS_ETH_MODULES is for this machine"
		for m in $NFS_ETH_MODULES; do
			find_module "$m"
		done
	fi
	find_module "-ipv4"
	find_module "nfs"

	have_nfs=yes
	warn "Remember to use \`root=/dev/ram0 init=/linuxrc' when starting kernel"
	warn "or you will have problems like init(xx) being child process of swapper(1)."
}

# generate initrd fragment
# @access	public
initrd_gen_nfs() {
	if ! is_yes "$have_nfs"; then
		return
	fi

	# use root=/dev/ram0 init=/linuxrc when starting kernel or you will
	# have problems like init(XX) being child process of swapper(1).
	verbose "Adding rootfs on NFS support to initrd (dhcp)"
	mknod -m 644 "$DESTDIR/dev/urandom" c 1 9
	mkdir "$DESTDIR/newroot"
	add_linuxrc <<-'EOF'
		ifconfig lo 127.0.0.1 up
		route add -net 127.0.0.0 mask 255.0.0.0 lo
		ifconfig eth0 up
		udhcpc -i eth0 -f -q -s /bin/setdhcp

		cd /newroot
		pivot_root . initrd
		[ -x /sbin/chroot ] && exec /sbin/chroot . /sbin/init -i < dev/console > dev/console 2>&1
	EOF

	cat <<-'EOF' > "$DESTDIR/bin/setdhcp"
		#!/bin/sh
		[ "$1" != "bound" ] && exit
		[ -n "$broadcast" ] && BROADCAST="broadcast $broadcast"
		[ -n "$subnet" ] && NETMASK="netmask $subnet"
		ifconfig $interface $ip $BROADCAST $NETMASK up
		if [ -n "$router" ]; then
			for r in $router; do
				route add default gw $r dev $interface
			done
		fi

		if [ -n "$hostname" ]; then
			hostname $hostname
		fi

		for o in $CMDLINE; do
			case $o in
			nfsroot=*)
				rootpath=${o#nfsroot=}
				;;
			esac
		done

		if [ -n "$rootpath" ]; then
			mount -n -t nfs -o ro,nolock,posix,tcp,wsize=8192,rsize=8192 $rootpath /newroot
		else
			echo "Missing rootpath in what DHCP server sent to us. Failing..."
			echo "All seen variables are listed below:"
			set
		fi
	EOF

	chmod 755 "$DESTDIR/bin/setdhcp"
}
