#!/bin/sh

# Don't do anything special if computer is already booted
if [ $$ -ne 1 ]
then
	exec /sbin/init.orig $*
	echo "FATAL ERROR: exec /sbin/init.orig failed" >&2
	exit 1
fi

# Don't do anything special if root is rw (ie master system).
if touch /test-rw
then
	rm /test-rw
	echo "WARNING: master system installed" >&2
	exec /sbin/init.orig $*
	echo "FATAL ERROR: exec /sbin/init.orig failed" >&2
	exit 1
fi

# Try and find configuration file
if [ -f /etc/diskless-image/config ]
then
	# Load config file
	. /etc/diskless-image/config

	# Get IP address, need to mount /proc first
	mount -n none /proc -t proc
	#IP=`cat /proc/cmdline | sed 's/^.*nfsaddrs=\([0-9\.]\+\).*$/\1/'`
	IP=`ifconfig | grep -A1 eth0 | grep -v eth0 | sed 's/^.*inet addr:\([0-9\.]\+\).*$/\1/'`
	echo "Client IP address is $IP"

	# Mount client's /etc directory
	echo -n "Mounting NFS-root directories..."
	mount -n $nfsserver:/$nfshostsdir/$IP/etc /etc -orw,nolock

	# Update entries in /etc/mtab
	rm -f /etc/mtab~ /etc/nologin
	: > /etc/mtab
	mount -o remount /
	mount -o remount /etc
	mount -o remount /proc

	# report success
	echo "done."
else
	echo "ERROR: Cannot find image config file"
	echo "       Not mounting NFS-root directories"
fi

# Only should get here if something went wrong
exec /sbin/init.orig $*
echo "FATAL ERROR: exec /sbin/init.orig failed" >&2
exit 1
