#!/bin/sh
#
# $Id$
#
# This script sets up the network + NFS environment if needed.
#


# number of ping
ipcount=3

# Get info from config file
ipdev=`grep nfs-dev /tmp/mondo-restore.cfg 2> /dev/null | cut -d' ' -f2-`
ipaddress=`grep nfs-client-ipaddr /tmp/mondo-restore.cfg 2> /dev/null | cut -d' ' -f2-`
ipnetmask=`grep nfs-client-netmask /tmp/mondo-restore.cfg 2> /dev/null | cut -d' ' -f2-`
ipbroadcast=`grep nfs-client-broadcast /tmp/mondo-restore.cfg 2> /dev/null | cut -d' ' -f2-`
ipgateway=`grep nfs-client-defgw /tmp/mondo-restore.cfg 2> /dev/null | cut -d' ' -f2-`
ipconf=""
export nfsmount=`grep nfs-server-mount /tmp/mondo-restore.cfg 2> /dev/null | cut -d' ' -f2-`
export imgname=`grep iso-prefix /tmp/mondo-restore.cfg 2> /dev/null | cut -d' ' -f2-`
if [ "$imgname" = "" ]; then
	export imgname="mondorescue"
fi
export dirimg=`grep nfs-server-path /tmp/mondo-restore.cfg 2> /dev/null | cut -d' ' -f2-`
if [ "$dirimg" = "" ]; then
	export dirimg="/"
fi

# info from cmdline are predominent
for i in `cat /proc/cmdline` ; do
	echo $i | grep -qi ping= && ipcount=`echo $i | cut -d= -f2`
	echo $i | grep -qi ipconf= && ipconf=`echo $i | cut -d= -f2`
	echo $i | grep -qi nfsmount= && export nfsmount=`echo $i | cut -d= -f2`
	echo $i | grep -qi prefix= && export imgname=`echo $i | cut -d= -f2`
done

if [ "$ipdev" != "" ] || [ "$ipconf" != "" ]; then
	# Network configuration stored during archive
	# or on cmdline so network wanted => starting it
	LogIt "Starting Network..."

	# Activate loobback
	ifconfig lo 127.0.0.1

	echo "$ipconf" | grep -q "dhcp"
	if [ $? -eq 0 ]; then
		ipdev=`echo $ipconf | cut -d: -f1`
		LogIt "Making DHCP request on $ipdev"
		udhcpc -i $ipdev
	else
		if [ "$ipconf" != "" ]; then
			ipdev=`echo $ipconf | cut -d: -f1`
			ipaddress=`echo $ipconf | cut -d: -f2`
			ipnetmask=`echo $ipconf | cut -d: -f3`
			ipbroadcast=`echo $ipconf | cut -d: -f4`
			ipgateway=`echo $ipconf | cut -d: -f5`
		fi
		LogIt "Configuring $ipdev statically ($ipaddress/$ipnetmask)"
		ifconfig $ipdev $ipaddress netmask $ipnetmask broadcast $ipbroadcast
		route add default gw $ipgateway
	fi

	# ping server helps waking interface up
	LogIt "Pinging NFS server..."
	nfs_server_ipaddr=`echo $nfsmount | cut -d: -f1`
	ping -c $ipcount $nfs_server_ipaddr 

	# Finally mounts the NFS share
	LogIt "Mounting NFS share ($nfsmount) on /tmp/isodir..."
	touch /etc/mtab
	mount -t nfs -o nolock,ro $nfsmount /tmp/isodir
	
	LogIt "Mounting NFS image ${imgname}-1.iso in $dirimg on /mnt/cdrom in loopback"
	mount -o ro,loop -t iso9660 /tmp/isodir/$dirimg/${imgname}-1.iso /mnt/cdrom
fi
