#!/bin/sh

# We don't have any prerequisites
case $1 in
prereqs)
	exit 0
	;;
esac

for x in $(cat /proc/cmdline); do
	case $x in
		nbdroot*)
			nbdroot="${x}"
			;;
		root=/dev/nbd*)
			nbdrootdev="${x#root=}"
			nbdbasedev="${x#root=/dev/}"
			;;
	esac
done

# if nbd root is not requested exit early and silently
if [ -z "${nbdroot}" ]; then
	exit 0
fi

. /scripts/functions

log_begin_msg "Setting up nbd-client"

configure_networking

x="$nbdroot"
# Support setting stuff using DHCP by overloading 'option root-path'
case $x in
	nbdroot=dhcp)
		x="$ROOTPATH"
		;;
esac

case $x in
	nbdroot=*,*,*)
		nbdroot="${x#nbdroot=}"
		nbdsrv="${nbdroot%%,*}"
		nbdport="${nbdroot%,*}"
		nbdport="${nbdport##*,}"
		# root= parameter overrides three-option nbdroot= parameter
		if [ -z "$nbdrootdev" ]
		then
			nbdbasedev="${nbdroot##*,}"
			nbdrootdev=/dev/$nbdbasedev
		fi
		;;
	nbdroot=*,*)
		nbdroot="${x#nbdroot=}"
		nbdsrv="${nbdroot%,*}"
		nbdport="${nbdroot#*,}"
		;;
esac

nbdrootdev=${nbdrootdev%p*}
nbdbasedev=${nbdbasedev%p*}

if [ -z "$nbdport" -o -z "$nbdrootdev" ]
then
	log_failure_msg "Insufficient information to set up nbd, quitting (nbdsrv=$nbdsrv nbdport=$nbdport nbdroot=$nbdroot root=$nbdrootdev)"
	exit 0
fi

nondigits=$(echo $nbdport | sed -e 's/[0-9]//g')
if [ ! -z "$nondigits" ]
then
	# non-numeric characters, assume a name rather than a port
	nbdport="-N $nbdport"
fi

# Support setting the server's IP address by overloading 'option
# root-server'. This is separate from the "ROOTPATH" grabbing above, in
# that here we only specify the server's IP address through DHCP, but
# expect everything else to be set through the kernel's command line.
# Netbooting is a can of worms.
if [ "$nbdsrv" = "dhcp" ]
then
	nbdsrv=$ROOTSERVER
fi

if [ -z "$nbdsrv" ]
then
	log_failure_msg "Insufficient information to set up nbd, quitting (nbdsrv=$nbdsrv nbdport=$nbdport nbdroot=$nbdroot root=$nbdrootdev)"
	exit 0
fi

/sbin/nbd-client $nbdsrv $nbdport $nbdrootdev -persist
# This should be removed once the cfq scheduler no longer deadlocks nbd
# devices
if grep '\[cfq\]' /sys/block/$nbdbasedev/queue/scheduler >/dev/null
then
	echo deadline > /sys/block/$nbdbasedev/queue/scheduler
fi
