#!/bin/bash

check_vars () {
    local error=false
    for n in $*; do
        env | grep -q "^$n=" && continue
        echo "$n is not found" 
        error=true
    done
    if $error; then
	exit 1
    fi
}

SCRIPTDIR=$(dirname $0)
NFSROOT=$1

if [ -d ${NFSROOT} ]; then

	echo "--- Installing in ${NFSROOT}"

	mkdir -p ${NFSROOT}/alpha-pts/
	rm ${NFSROOT}/alpha-pts/*.sh &> /dev/null
	rm ${NFSROOT}/alpha-pts/bin/* &> /dev/null
	cp -Rvf ${SCRIPTDIR}/alpha-pts/  ${NFSROOT}/
	echo ""
	cp -v ${SCRIPTDIR}/S70apts ${NFSROOT}/etc/init.d/
	exit 0
	
else

	check_vars WRS_BASE_DIR WRS_OUTPUT_DIR

	echo "--- Wrapping test filesystem"

	DEVTAR="$WRS_BASE_DIR/../userspace/devices.tar.gz"
	rootfs_vanilla="$WRS_OUTPUT_DIR/build/buildroot-2011.11/output/target"
	rootfs_override="$WRS_BASE_DIR/../userspace/rootfs_override"

	ROOTFS_IMAGE_CPIO="$WRS_OUTPUT_DIR/images/wrs-image_test.cpio.gz"
	ROOTFS_IMAGE_TGZ="$WRS_OUTPUT_DIR/images/wrs-image_test.tar.gz"
	ROOTFS_IMAGE_JFFS2="$WRS_OUTPUT_DIR/images/wrs-image_test.jffs2"

	TMPFS=$(mktemp -d /tmp/rootfs.XXXXXX)
	TMPSCRIPT=$(mktemp /tmp/rootfs-script.XXXXXX)

	cat > $TMPSCRIPT << EOF
	mkdir -p $TMPFS/wr

	cp -r $rootfs_vanilla/* $TMPFS
	cp -r $WRS_OUTPUT_DIR/images/wr/* $TMPFS/wr
	cp -r $WRS_OUTPUT_DIR/images/lib/* $TMPFS/lib
	rm -f $TMPFS/etc/init.d/*
	cp -r $rootfs_override/* $TMPFS

	rm -rf $TMPFS/dev
	(cd $TMPFS && tar xzf $DEVTAR)
	(cd $TMPFS && ln -fs sbin/init .)

	mkdir -p $TMPFS/root/.ssh
	cat $HOME/.ssh/id_?sa.pub >> $TMPFS/root/.ssh/authorized_keys
	if [ -f $WRS_BASE_DIR/authorized_keys ]; then
		cat $WRS_BASE_DIR/authorized_keys >> $TMPFS/root/.ssh/authorized_keys
	fi
	chmod 600 $TMPFS/root/.ssh/authorized_keys
	chmod g-w $TMPFS/root $TMPFS/root/.ssh
	chown -R root:root $TMPFS/root
	chown -R root:root $TMPFS/etc/dropbear

	##Test Anchor
	mkdir -p ${NFSROOT}/alpha-pts/
	rm ${NFSROOT}/alpha-pts/*.sh &> /dev/null
	rm ${NFSROOT}/alpha-pts/bin/* &> /dev/null
	cp -Rvf ${SCRIPTDIR}/alpha-pts/  ${NFSROOT}/
	cp ${NFSROOT}/S70apts ${NFSROOT}/etc/init.d/

	(cd "$TMPFS" && find . | cpio -o -H newc | gzip) > $ROOTFS_IMAGE_CPIO
	(cd "$TMPFS" && tar cz .> $ROOTFS_IMAGE_TGZ)
	/usr/sbin/mkfs.jffs2 --little-endian --eraseblock=0x20000 -n --pad -d $TMPFS -o $ROOTFS_IMAGE_JFFS2.img
EOF


	fakeroot bash $X $TMPSCRIPT

	rm -rf $TMPFS
	rm -rf $TMPSCRIPT

fi 





echo "------------------------------------"
