#!/bin/bash

# check variables, like all scripts herein do
WRS_SCRIPT_NAME=$(basename $0)

if [ -z "$WRS_BASE_DIR" ]; then
    echo "$0: Plesae set WRS_BASE_DIR" >& 2
    exit 1
fi
. ${WRS_BASE_DIR}/scripts/wrs_functions

wrs_check_vars WRS_OUTPUT_DIR WRS_DOWNLOAD_DIR CROSS_COMPILE

wrs_echo "--- Wrapping filesystem"

# This builds an initramfs thing. The cpio archive is made from
# a real directory, and we have no device table support. So let's
# extract a tar file with devices, instead.

DEVTAR="$WRS_BASE_DIR/../userspace/devices.tar.gz"

TMPFS=$(mktemp -d /tmp/rootfs.XXXXXX)
chmod a+rx $TMPFS

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

TMPSCRIPT=$(mktemp /tmp/rootfs-script.XXXXXX)
ROOTFS_IMAGE_TGZ="$WRS_OUTPUT_DIR/images/wrs-image.tar.gz"

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 .)

if [ ! -z "$CONFIG_NTP_SERVER" ]; then
    echo "ntpserver $CONFIG_NTP_SERVER" > $TMPFS/wr/etc/wr_date.conf
fi

if [ ! -z "$CONFIG_DNS_SERVER" ]; then
    rm $TMPFS/etc/resolv.conf
    echo "nameserver $CONFIG_DNS_SERVER" > $TMPFS/etc/resolv.conf
    if [ ! -z "$CONFIG_DNS_DOMAIN" ]; then
        echo "domain $CONFIG_DNS_DOMAIN" >> $TMPFS/etc/resolv.conf
    fi
fi

if [ "$CONFIG_REMOTE_SYSLOG_UDP" = "y" ]; then
    sed -i 's/@@remote-host/@remote-host/' $TMPFS/etc/rsyslog.conf
fi
if [ ! -z "$CONFIG_REMOTE_SYSLOG_SERVER" ]; then
    sed -i '/remote-host/ s/^##//' $TMPFS/etc/rsyslog.conf
    sed -i 's/remote-host/$CONFIG_REMOTE_SYSLOG_SERVER/' $TMPFS/etc/rsyslog.conf
fi

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
    chmod 600 $TMPFS/root/.ssh/authorized_keys
fi
chmod g-w $TMPFS/root $TMPFS/root/.ssh
chown -R root:root $TMPFS/root
chown -R root:root $TMPFS/etc/dropbear
chmod a+rx $TMPFS

##Test Anchor
(cd "$TMPFS" && tar cz .> $ROOTFS_IMAGE_TGZ)
EOF

fakeroot bash $WRS_SH_OPTIONS $TMPSCRIPT

if [ -z "$CONFIG_KEEP_ROOTFS" ]; then
    rm -rf $TMPFS
    rm -rf $TMPSCRIPT
else
    wrs_echo "Image FS is in $TMPFS/"
    wrs_echo "Gerenated by $TMPSCRIPT"
fi
