#!/bin/sh
stage2=/root

nfs_slice(){
if grep -q 'automatic=method:nfs'  /proc/cmdline ; then
	# mount overlays from nfs 
	ip=$(netstat -t --numeric-hosts | grep :2049 | head -n1 | \
		sed 's/  */ /g' | cut -d' ' -f5 | cut -d: -f1)
	mkdir -p $stage2/tmp/images
	if nfsmount -o nolock $ip:/srv/public/netinst/overlays-live $stage2/tmp/images &> /dev/null ; then
		sleep 1
		for image in $(find $stage2/tmp/images -name '*iso' | sort) ; do
			imgdir=$stage2/tmp/overlays/$(basename $image)
			mkdir -p $imgdir
			mount -o loop $image $imgdir
			mount -t aufs -o "remount,add:1:$imgdir/=rr+wh" none $stage2
		done
	fi
fi
}

disk_slice(){
# Automaitc rw live on flash
if grep -q 'automatic=method:disk,label:' /proc/cmdline && \
	 [ -f /sys/dev/block/$(mountpoint -d /image)/partition ] && \
	[ ! -h /dev/disk/by-label/alt-live-storage ] ; then
	partition=$(mountpoint -d /image)
	major=${partition%:*}
	minor=$((${partition#*:}& ~0xf))
	devlink=$(readlink /sys/dev/block/$major:$minor)
	device=/dev/${devlink##*/}
	before=$(fdisk -l $device | wc -l)
	fdisk $device << _EOF_
n
p



w
_EOF_
	after=$(fdisk -l $device | wc -l)
	if [ $after -gt $before ] ; then 
		partline=$(fdisk -l $device | tail -n1)
		startend=$(echo $partline | sed 's/  */ /g' | cut -d' ' -f2,4)
		number=$(echo $partline | cut -d' ' -f1| sed 's/[^0-9]*//')
		udevd --daemon
		addpart $device $number $startend && udevadm trigger
# wait for $device$number
		for n in seq 1 10; do
			[ -b $device$number ] && break
			sleep 1
		done
		mkfs.ext3 -L alt-live-storage $device$number &&	mount $device$number $stage2.rw
		udevadm control --exit
	fi
fi

if [ -h /dev/disk/by-label/alt-live-storage ] ; then
	mount /dev/disk/by-label/alt-live-storage $stage2.rw
fi
}

if grep -q 'stagename=live' /proc/cmdline ; then
echo "remounting / via aufs"
ln -s /proc/mounts /etc/mtab
/bin/mkdir -p $stage2.rw $stage2.ro
disk_slice
/bin/mountpoint -q $stage2.rw || /bin/mount -t tmpfs none $stage2.rw -o mode=755
/bin/mount $stage2 $stage2.ro --move
/bin/mount -t aufs none $stage2 -o dirs=$stage2.rw=rw:$stage2.ro=rr
nfs_slice
/bin/mkdir -p $stage2/.ro $stage2/.rw
/bin/mount $stage2.ro $stage2/.ro --move
/bin/mount $stage2.rw $stage2/.rw --move
/bin/rmdir $stage2.rw $stage2.ro

if grep -q propagator-debug /proc/cmdline ; then
        /bin/openvt -s -w -- /bin/sh
fi

fi
