#!/bin/sh
set -e

. /opt/fwu/ipmodule-functions

echo -n "started" > ${FWU_STATUS_FILE}

parse_arguments $1 $2 $3

TAR_DIRS="rfs_regular_directories.tar"
TAR_SYMS="rfs_regular_symlinks.tar"
TAR_DEVS="rfs_regular_devices.tar"

EXTRA_DIRS="extra_packages_directories.tar"
EXTRA_SYMS="extra_packages_symlinks.tar"

TARPIPE_PRESCRIPT="tarpipe_prescript.sh"
RAWPIPE_PRESCRIPT="rawpipe_prescript.sh"

check_executable ${MOUNT}
check_executable ${UNMOUNT}

check_file ${TAR_DIRS}
check_file ${TAR_SYMS}
check_file ${TAR_DEVS}

umount_all
identify_offline
erase_offline
mount_offline_system

echo "Preparing directories..."
tar xf ${TAR_DIRS} -C ${OFFLINE_SYSTEM_DIR}

if [ -e "${EXTRA_DIRS}" ]
then
	tar xf ${EXTRA_DIRS} -C ${OFFLINE_SYSTEM_DIR}
	rm -f ${EXTRA_DIRS}
else
	echo "No extra directories, skipping."
fi

echo "Preparing symlinks..."
tar xf ${TAR_SYMS} -C ${OFFLINE_SYSTEM_DIR}

if [ -e "${EXTRA_SYMS}" ]
then
	tar xf ${EXTRA_SYMS} -C ${OFFLINE_SYSTEM_DIR}
	rm -f ${EXTRA_SYMS}
else
	echo "No extra symlinks, skipping."
fi

echo "Preparing devices..."
tar xf ${TAR_DEVS} -C ${OFFLINE_SYSTEM_DIR}/dev

if [ -e "${TARPIPE_PRESCRIPT}" ]
then
	echo "Executing tarpipe prescript."
	chmod +x "${TARPIPE_PRESCRIPT}"
	nohup "./${TARPIPE_PRESCRIPT}" &>/dev/null
else
	echo "No tarpipe pre-script, skipping."
fi

if [ -e "${RAWPIPE_PRESCRIPT}" ]
then
        echo "Executing rawpipe prescript."
        chmod +x "${RAWPIPE_PRESCRIPT}"
        nohup "./${RAWPIPE_PRESCRIPT}" &>/dev/null
else
        echo "No rawpipe pre-script, skipping."
fi

echo -n "stopped" > ${FWU_STATUS_FILE}
echo "The pre-script has successfully done it's job and will now exit with return code 0."
exit 0
