# NFS filesystem mounting			-*- shell-script -*-

# NBD root mounting
mountroot()
{
	[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/nfs-top"
	run_scripts /scripts/nfs-top
	[ "$quiet" != "y" ] && log_end_msg

    if [ -n "$dhcpport" ]; then
        DHCPPORT="$dhcpport"
    fi


	# For DHCP
	modprobe -q af_packet

	case ${IPOPTS} in
		none|off)
			# Do nothing
			;;
		""|on|any)
			# Bring up device
			ipconfig ${DEVICE}
			;;
		dhcp|bootp|rarp|both)
            if [ ${IPOPTS} == "dhcp"] && [ -n "$DHCPPORT" ]; then
            IPOPTS="${IPOPTS} -p ${DHCPPORT}"
            fi
			
            ipconfig -c ${IPOPTS} -d ${DEVICE}
			;;
		*)
			ipconfig -d $IPOPTS

			# grab device entry from ip option
			NEW_DEVICE=${IPOPTS#*:*:*:*:*:*}
			if [ "${NEW_DEVICE}" != "${IPOPTS}" ]; then
				NEW_DEVICE=${NEW_DEVICE%:*}
			else
				# wrong parse, possibly only a partial string
				NEW_DEVICE=
			fi
			if [ -n "${NEW_DEVICE}" ]; then
				DEVICE="${NEW_DEVICE}"
			fi
			;;
	esac

	# command line parsing
	for x in $(cat /proc/cmdline); do
	    case $x in
	    wol=*)
	    WOLADDRESS="${x#wol=}"
	    ;;
	    overlay=*)
	    OVERLAY="${x#overlay=}"
	    ;;
	    overlaykey=*)
	    OVERLAYKEY="${x#overlaykey=}"
	    ;;
	    minram=*)
	    MINRAM="${x#minram=}"
	    ;;
	    union=*)
	    UNIONTYPE="${x#union=}"
	    ;;
        hostnameoverride=*)
        HOSTNAMEOVERRIDE="${x#hostnameoverride=}"
        ;;

        esac
	done

	# source relevant ipconfig output
	. /tmp/net-${DEVICE}.conf

    if [ -n "${nbdroot}" ]; then
               NBD_ROOT_SERVER=$( echo "${nbdroot}" | sed 's/:.*//')
               NBD_ROOT_PORT=$( echo "${nbdroot}" | sed 's/.*://')
               if [ -z "$NBD_ROOT_PORT" ] || [ "$NBD_ROOT_SERVER" = "$NBD_ROOT_PORT" ]; then
                   NBD_ROOT_PORT="2000"
               fi
       else
               NBD_ROOT_SERVER="${ROOTSERVER}"
               NBD_ROOT_PORT=${nbdport:-"2000"}
       fi
       if [ -n "${nbdswap}" ]; then
               NBD_SWAP_SERVER=$( echo "${nbdswap}" | sed 's/:.*//')
               NBD_SWAP_PORT=$( echo "${nbdswap}" | sed 's/.*://')
               if [ -z "$NBD_SWAP_PORT" ] ||  [ "$NBD_SWAP_SERVER" = "$NBD_SWAP_PORT" ]; then
                   NBD_ROOT_PORT="9572"
               fi

       else
               NBD_SWAP_SERVER="${ROOTSERVER}"
               NBD_SWAP_PORT=${nbdswapport:-"9572"}
    fi

    
    if [ -n "$WOLADDRESS" ]  && [ -x /sbin/etherwake ]; then
	[ "$quiet" != "y" ] && log_begin_msg "WOL: waking up $WOLADDRESS (using etherwake)"
	etherwake -i $DEVICE $WOLADDRESS 
	[ "$quiet" != "y" ] && log_end_msg
    fi

    # try to get swap from the server if we dont have enough ram (less than 48M)
    if [ -n "$MINRAM" ]; then
        min_ram="$MINRAM"
    else
        min_ram=49152
    fi

    real_ram=$(cat /proc/meminfo |grep MemTotal|tr -d " [a-z][A-Z]:")

    if [ ${real_ram} -lt ${min_ram} ];then
        [ "$quiet" != "y" ] && log_begin_msg "Only found ${real_ram}k main ram, trying network swap."
        nbd-client ${NBD_SWAP_SERVER} ${NBD_SWAP_PORT} /dev/nbd1 || true
        mkswap /dev/nbd1 || true
        swapon /dev/nbd1 || true
        [ "$quiet" != "y" ] && log_end_msg
    fi

    mkdir -p /cow
    mkdir -p /rofs


    # mount the readonly root
    
    # borrowed from scripts/nfs (initramfs-tools package)
    if [ -z "${ROOTDELAY}" ]; then
        delay=180
    else
	delay=${ROOTDELAY}
    fi
    retry_nr=0

    while [ ${retry_nr} -lt ${delay} ] && [ ! -e /rofs${init} ]; do
	[ ${retry_nr} -gt 0 ] && \
	[ "$quiet" != "y" ] && log_begin_msg "Retrying nbd mount"
	# FIXME: what happens if nbd-client has already mounted /dev/nbd0 ?!
	nbd-client ${NBD_ROOT_SERVER} ${NBD_ROOT_PORT} /dev/nbd0 && mount -o ro -t squashfs /dev/nbd0 /rofs
	retry_nr=$(( ${retry_nr} + 1 ))
	[ ! -e /rofs${init} ] && /bin/sleep 1
	[ ${retry_nr} -gt 0 ] && [ "$quiet" != "y" ] && log_end_msg
    done
    

    # mount the overlay file system
    if [ ! "x$OVERLAY" = "xtmpfs" ]; then
		
		if [ "x$OVERLAYKEY" = "xMAC" ]; then
	    	# thanks to Scorpi for pointing me to this file
	    	# Note: we strip colons from the MAC address 
	    	KEY=`cat /sys/class/net/${DEVICE}/address | tr -d :`
		elif [ "x$OVERLAYKEY" = "xHOSTNAME" ]; then
	    	# $HOSTNAME is provided by ipconfig
	    	# It's set via DHCP or via the ip= boot option
	    	# Maybe we should try to get that via /etc/hostname
	    	# but that might come from a static environment (squashfs),
	    	# so I'll leave it out for the moment
	    	KEY="$HOSTNAME"
        else
	    	KEY="$OVERLAYKEY"
		fi

        if [ "x$HOSTNAMEOVERRIDE" = "xtrue" ]; then
            hostname "$KEY"
        fi

		case "$OVERLAY" in
		    # either specify the share using nfs=
		    # or say NFS or nfs to enable auto-detection
		    nfs=*|NFS|nfs)
		    OL="${OVERLAY#nfs=}"
		    
		    # defaults are used if OL=""
		    if [ "$OL" == "NFS" ] || [ "$OL" == "nfs" ]; then
			OL=""
		    fi
		    	    
			# Sorry if this is a bit messy, but I don't want to overwrite variables
		
			# borrowed from scripts/nfs (initramfs-tools package)
        	if [ -z "${NFSOPTS}" ]; then
                	NFSOPTS="-o retrans=10"
        	fi

        	OVERLAYSERVER=$( echo "${OL}" | sed 's/:.*//')
        	OVERLAYPATH=$( echo "${OL}" | sed 's/.*://')
        	if [ ! -n "$OVERLAYSERVER" ]; then
            		OVERLAYSERVER="${NBD_ROOT_SERVER}"
        	fi
        	if [ ! -n "$OVERLAYPATH" ]; then
            		# is this the correct path?
            		OVERLAYPATH="/var/cache/mythbuntu-diskless/overlay/"
        	fi
        	SHARE="${OVERLAYSERVER}:${OVERLAYPATH}"
        	# I wish this could be wrapped in a while loop like nbd-client
        	# But I can't think of a good way to check if the file system was successfully mounted
	       	nfsmount -o rw -o nolock ${NFSOPTS} ${SHARE} /cow
		;;
		   *)
			mount ${OVERLAY} /cow
		;;
		esac
	
	
		if [ ! -d /cow/${KEY} ]; then
	    	mkdir /cow/${KEY}
		fi
    
	else
		KEY=""
		mount -t tmpfs tmpfs /cow
    fi


    # merge ro and rw file systems
    if [ "x$UNIONTYPE" = "xaufs" ]; then
		mount -t aufs -o br:/cow/${KEY}=rw:/rofs=ro aufsroot ${rootmnt}
    else
		mount -t unionfs -o dirs=/cow/${KEY}=rw:/rofs=ro,debug=1 unionfs ${rootmnt}
    fi
 
     
 
    # make the filesystems accessible
    mkdir -p ${rootmnt}/cow
    # note: this line also applies to default tmpfs/unionfs setup from ltsp
    # use of ${KEY} might be problematic there, but that doesn't matter for 
    # mythbuntu-diskless
    mount -o bind /cow/${KEY} ${rootmnt}/cow

    mkdir -p ${rootmnt}/rofs
    mount -o move /rofs ${rootmnt}/rofs

    # get the lts.conf via tftp
    tftpath=$(echo ${filename%/*}|tr -d '"')
    (echo "get ${tftpath}/lts.conf"|tftp ${ROOTSERVER} >/dev/null 2>&1)
    if [ -s ./lts.conf ];then
        cp ./lts.conf ${rootmnt}/etc/
    fi

    if [ -n "$IPV4DNS0" ] && [ ! "$IPV4DNS0" = "0.0.0.0" ]; then
        echo "# created by mythbuntu-diskless initramfs script" > ${rootmnt}/etc/resolv.conf
        echo "nameserver $IPV4DNS0" >> ${rootmnt}/etc/resolv.conf
    fi
    
    if [ -n "$IPV4DNS1" ] && [ ! "$IPV4DNS1" = "0.0.0.0" ]; then
        echo "nameserver $IPV4DNS1" >> ${rootmnt}/etc/resolv.conf
    fi
        

	[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/nfs-bottom"
	run_scripts /scripts/nfs-bottom
	[ "$quiet" != "y" ] && log_end_msg
}
