#!/bin/sh
NEWROOT=$3

XCATMASTER=$XCAT

if [ ! -z "$imgurl" ]; then
	if [ xhttp = x${imgurl%:*} ]; then
		NFS=0
		FILENAME=${imgurl##*/}
		while [ ! -r "$FILENAME" ]; do
			echo Getting $imgurl...
			if ! wget $imgurl; then
				rm -f $FILENAME
				sleep 27
			fi
		done
	elif [ xnfs = x${imgurl%:*} ]; then
		NFS=1
		SERVER=${imgurl#nfs:}
		SERVER=${SERVER#/}
		SERVER=${SERVER#/}
		ROOTDIR=$SERVER
		SERVER=${SERVER%%/*}
		SERVER=${SERVER%:}
		ROOTDIR=/${ROOTDIR#*/} 
	fi
fi
#echo 0 > /proc/sys/vm/zone_reclaim_mode #Avoid kernel bug

if [ -r /rootimg.sfs ]; then
  echo Setting up squashfs with ram overlay.
  mknod /dev/loop0 b 7 0
  mkdir -p /ro
  mkdir -p /rw
  mount -t squashfs /rootimg.sfs /ro
  mount -t tmpfs rw /rw
  mount -t aufs -o dirs=/rw:/ro mergedroot $NEWROOT
  mkdir -p $NEWROOT/ro
  mkdir -p $NEWROOT/rw
  mount --move /ro $NEWROOT/ro
  mount --move /rw $NEWROOT/rw
elif [ -r /rootimg.gz ]; then
  echo Setting up RAM-root tmpfs.
  mount -t tmpfs rootfs $NEWROOT
  cd $NEWROOT
  echo -n "Extracting root filesystem:"
  if [ -x /bin/cpio ]; then
    gzip -cd /rootimg.gz |/bin/cpio -idum
  else
    gzip -cd /rootimg.gz |cpio -idum
  fi
  echo Done
else
  echo -n Failed to download image, panicing in 5...
  for i in 4 3 2 1 0; do
    /bin/sleep 1
    echo -n $i...
  done
  echo
  echo "You're dead.  rpower nodename reset to play again.

* Did you packimage with -m cpio, -m squashfs, or -m nfs?
* If using -m squashfs did you include aufs.ko with geninitrd?
  e.g.:  -n tg3,squashfs,aufs,loop
* If using -m nfs did you export NFS and sync rootimg?  And
  did you include the aufs and nfs modules in the proper order:
  e.g.:  -n tg3,aufs,loop,sunrpc,lockd,nfs_acl,nfs

"
  /bin/dash
  exit
fi
cd /
for lf in /tmp/dhclient.*.lease; do
    netif=${lf#*.}
    netif=${netif%.*}
    cp $lf  "$NEWROOT/var/lib/dhclient/dhclient-$netif.leases"
done
cp /etc/resolv.conf "$NEWROOT/etc/"

if [ -d "$NEWROOT/etc/sysconfig" -a ! -e "$NEWROOT/etc/sysconfig/selinux" ]; then
	echo "SELINUX=disabled" >> "$NEWROOT/etc/sysconfig/selinux"
fi

# inject new exit_if_exists
echo 'settle_exit_if_exists="--exit-if-exists=/dev/root"; rm "$job"' > /initqueue/xcat.sh
# force udevsettle to break
> /initqueue/work
