#!/bin/sh
# Description: Script to be executed during a liveburner upgrade
# but after the installation of the application packages.
# It will mount the safezone and restore the files.

EMMC_DEVICE="NOT_SUPPORTED"
SAFEZONE_MOUNTPOINT="/tmp/safezone"
LOGFILE="${SAFEZONE_MOUNTPOINT}/upgrade.log"


fatal_error()
{
	echo "$1"
	exit 1
}


detect_emmc()
{
	for i in $(seq 0 9); do
		if [ -b "/dev/mmcblk${i}" ]; then
			EMMC_DEVICE="mmcblk${i}"
			break
		fi
	done

	if [ "${EMMC_DEVICE}" == "NOT_SUPPORTED" ]; then
		fatal_error "Emmc device not found. Kernel version: ${KERNEL_VERSION}. Please fix."
	fi
}


# Mount the safezone mountpoint in ${SAFEZONE_MOUNTPOINT}
#
mount_safezone()
{
	echo "Mounting safezone"
	echo 0 > /sys/block/${EMMC_DEVICE}boot0/force_ro
	mkdir -p ${SAFEZONE_MOUNTPOINT}
	mount /dev/${EMMC_DEVICE}boot0 ${SAFEZONE_MOUNTPOINT}
	echo "Safezone ready to use"
}


# Report status of the upgrade in the update journal (/user/.update)
#
report_update_file()
{
	echo "Report status in update journal..."
	[ -f /.update/opkg/status ] && cp -f /.update/opkg/status /user/.opkg_status
	echo "Done"
}

####################
# MAIN KEROS PART
####################

detect_emmc
mount_safezone

echo -e "\n== Start of POSTAPPS script ==\n" 2>&1 | tee -a ${LOGFILE}

# Report status of the upgrade
report_update_file 2>&1 | tee -a ${LOGFILE}

####################
# MAIN CUSTOMER PART
####################

# Example:
# cp -fR ${SAFEZONE_MOUNTPOINT}/*  /etc/

echo -e "\n== End of POSTAPPS script ==\n" 2>&1 | tee -a ${LOGFILE}
sync
