#!/bin/sh

fail(){
        echo -e "$1"
        /bin/bash
}

# mount /proc
mount -t proc proc /proc
mount -t sysfs sysfs /sys

# create a writable fs to then create our mountpoints
TMP_MNT=/tmp/mnt
/bin/mkdir -p $TMP_MNT
/bin/mount -t tmpfs inittemp $TMP_MNT
if [ $? -ne 0 ]; then
    fail "ERROR: could not create a temporary filesystem to mount the base filesystems for overlayfs"
fi

#already mounted from ramfs
UID_DIR=/mnt/uid
STORAGE_DIR=/mnt/storage
SYSTEM_DIR=/mnt/system

/bin/mount -o ro,remount ${UID_DIR}

factory_reset_storage() {
    echo "NOTE: Factory reset storage"

    rm -rf /mnt/storage/config/*
    rm -rf /mnt/storage/permanent/logo/*
    rm -rf /mnt/storage/firmware/config/dofactoryreset

    if [ -e /version.xml ]
    then
        cp -f /version.xml /mnt/storage/config
    else
        echo "WARNING: /version.xml does not exist"
    fi
}

cancel_scheduled_setman_action() {
    # Deleting or modifying scheduled setman action is allowed here only because the execution is not yet
    # started.

    /usr/lib/lwr/setman/setman-action is-active
    if [ $? -eq 0 ]; then
        scheduled_action=$(/usr/lib/lwr/setman/setman-action read)
        echo "NOTE: cancelling previously scheduled configuration action: ${scheduled_action}"
        /usr/lib/lwr/setman/setman-action delete
    fi
}

if [ -e /mnt/storage/firmware/config/dofactoryreset ] || grep -q 'factorydefaults' '/proc/cmdline'; then
    cancel_scheduled_setman_action

    /usr/lib/lwr/setman/setman-action write default
fi

if [ -e /mnt/storage/firmware/upload-finished ]; then
#FIXME: Maybe all these stufs should be in update.sh (and deleting upload-finished also)
    cancel_scheduled_setman_action

    #Deleting md5sum file, so next time updating to the same tar.xz it really flashes it.
    rm -f "/mnt/system/boot/md5sum"

    localBackupPath="/mnt/storage/permanent/backup/local"

    if [ -d "${localBackupPath}" ]; then
        restoreParams="/mnt/storage/permanent/backup/local"
    fi
    # Based on Canonical Documentation this should be `/tmp/update/config` later on
    if [ -d /mnt/storage/firmware/config/backup ]; then
        restoreParams="/mnt/storage/firmware/config/backup ${restoreParams} --force"
    fi

    if [ -z ${restoreParams+x} ]; then
        echo "NOTE: Update without restore, schedule default"
        /usr/lib/lwr/setman/setman-action write default
    else
        echo "NOTE: Restore after firmware update: restore ${restoreParams}"
        mkdir -p /mnt/storage/permanent
        /usr/lib/lwr/setman/setman-action write restore ${restoreParams}
        if [ $? -ne 0 ]; then
            fail "ERROR: could not schedule configuration restore"
        fi
    fi
fi

scheduled_setman_action=$(/usr/lib/lwr/setman/setman-action read-action)
if [[ "${scheduled_setman_action}" == "restore" ]] || [[ "${scheduled_setman_action}" == "default" ]]; then
    factory_reset_storage
fi
/usr/lib/lwr/setman/setman-action is-active
if [ $? -eq 0 ]; then
    scheduled_action=$(/usr/lib/lwr/setman/setman-action read)
    echo "NOTE: configuration action: ${scheduled_action}"
fi

/bin/mkdir -p ${STORAGE_DIR}/config/overlayfs-upper
/bin/mkdir -p ${STORAGE_DIR}/config/overlayfs-worker
/bin/mkdir -p ${STORAGE_DIR}/permanent
/bin/mkdir -p ${STORAGE_DIR}/permanent/log
/bin/mkdir -p ${STORAGE_DIR}/permanent/backup
USER_STORAGE_DIR=${STORAGE_DIR}/config/user-storage
/bin/mkdir -p ${USER_STORAGE_DIR}
/bin/chown root:user-storage ${USER_STORAGE_DIR}
/bin/chmod 2775 ${USER_STORAGE_DIR}
/bin/mkdir -p ${TMP_MNT}/variant-rootfs
/bin/mkdir -p ${TMP_MNT}/newroot

PARTNUMBER=$(/bin/cat ${UID_DIR}/PartNumber)
VARIANTDIR=/mnt/system/variants/${PARTNUMBER}
/bin/echo "PARTNUMBER: ${PARTNUMBER} VARIANTDIR: ${VARIANTDIR}"


if [ ! -z "$PARTNUMBER" ] && [ -d "$VARIANTDIR" ]; then
    /bin/echo "Variant dir found, mount overlayfs /mnt/variant-rootfs"
    /bin/mount -t overlay -o lowerdir=${SYSTEM_DIR}/rootfs,upperdir=${VARIANTDIR},workdir=${SYSTEM_DIR}/overlayfs-worker overlayfs-root ${TMP_MNT}/variant-rootfs
    if [ $? -ne 0 ]; then
        fail "ERROR: could not mount /mnt/variant-rootfs"
    fi
else
    /bin/echo "Variant not found, mount default rootfs to /mnt/variant-rootfs"
    /bin/mount --bind ${SYSTEM_DIR}/rootfs ${TMP_MNT}/variant-rootfs
    if [ $? -ne 0 ]; then
        fail "ERROR: could not mount /mnt/variant-rootfs"
    fi
fi

/bin/mount -t overlay -o lowerdir=${TMP_MNT}/variant-rootfs,upperdir=${STORAGE_DIR}/config/overlayfs-upper,workdir=${STORAGE_DIR}/config/overlayfs-worker overlayfs-root ${TMP_MNT}/newroot
if [ $? -ne 0 ]; then
    fail "ERROR: could not mount overlayFS"
fi

echo "Move mountpoint to new root"
/bin/mount --move ${SYSTEM_DIR}/ ${TMP_MNT}/newroot/mnt/system
/bin/mount --move ${STORAGE_DIR}/ ${TMP_MNT}/newroot/mnt/storage
/bin/mount --move ${TMP_MNT}/variant-rootfs ${TMP_MNT}/newroot/mnt/variant-rootfs
/bin/mount --move ${UID_DIR}/ ${TMP_MNT}/newroot/uid

/bin/mkdir -p ${TMP_MNT}/newroot/old-root

cd ${TMP_MNT}/newroot

echo "pivot_root"
/sbin/pivot_root ${TMP_MNT}/newroot  ${TMP_MNT}/newroot/old-root
echo "chroot"
exec chroot . /bin/sh -c 'umount /old-root/tmp/mnt; umount /old-root/dev; umount /old-root/sys; umount /old-root/proc; umount /old-root; rm -r /old-root; exec /sbin/init'

if [ $? -ne 0 ]; then
    fail "ERROR: chroot"
fi

