#!/bin/sh
# Description: Script to be executed during a liveburner upgrade
# at the end of the process (after eMMC format, installation of
# the KerOS firmware and the other packages), just before rebooting.

EMMC_DEVICE="NOT_SUPPORTED"
SAFEZONE_MOUNTPOINT="/tmp/safezone"
LOGFILE="${SAFEZONE_MOUNTPOINT}/upgrade.log"
USER_LOGFILE=".upgrade.log"
USER_LOGFILE_ARCHIVE="${SAFEZONE_MOUNTPOINT}/upgrade_logs.tar.gz"


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

	# Parse the opkg logs of installation
	# Extracted information: Status of installation and list of packages
	awk 'BEGIN{package="";status="OK"}
	/^Installing .* on root\./ {
		if (package!="")
			{printf "__install_date__ -- Update from %s: %s\n", package, status}
		{package=$2;status="OK"}}
	/Not downgrading/ {status="ERROR (10)"}
	/errors/ {status="ERROR (11)"}
	/dependencies/ {status="ERROR (12)"}
	/^Not selecting [^ ]+ [^ ]+ due to incompatible architecture/ {status="ERROR (13)";package=$3}
	/conffile/ {status="PARTIAL (50)"}
	END{
		if (package!="")
			{printf "__install_date__ -- Update from %s: %s\n", package, status}
		{package=$2;status="OK"}}' /tmp/opkg.log > /tmp/update.log

	# Parse the opkg database
	# Extracted information: Status of installation and installation date
	awk 'BEGIN{package="";status="";install_date="__install_date__"} 
	/^Package: / {package=$2}
	/^Status: / {
		if ($2=="install" && $4=="installed")
			{status="OK"}
		else
			{status="PARTIAL (255)"}}
	/^Installed-Time: / {install_date=$2}
	/^$/{
		if (package!="")
			{printf "%s -- Update from %s: %s\n", install_date, package, status}
		{package="";status="";install_date="__install_date__"}}' /user/.opkg_status > /tmp/opkg_status.log

	# Parse the list of packages in the burner
	# Extracted information: filename of the packages 
	for ipk_file in /burner/*.ipk
	do
		package=$(opkg info $ipk_file | awk '/^Package: / {print $2}')
		ipk_filename=$(basename $ipk_file)
		echo "$package=$ipk_filename" >> /tmp/package_list
	done

	# Update the installation journal
	for package in $(awk '{gsub(":","",$5);print $5}' /tmp/update.log)
	do
		# Define the final status of the package
		opkg_status1=$(grep $package /tmp/opkg_status.log | awk '{printf "%s %s", $6, $7}')
		opkg_status2=$(grep $package /tmp/update.log| awk '{printf "%s %s", $6, $7}')
		status="OK"
		[ ! -z "${opkg_status1}" -a "${opkg_status1%% }" != "OK" ] && status="${opkg_status1}"
		[ ! -z "${opkg_status2}" -a "${opkg_status2%% }" != "OK" ] && status="${opkg_status2}"

		# Extract other information
		ipk_filename=$(grep $package /tmp/package_list| cut -d'=' -f2)
		install_timestamp=$(grep $package /tmp/opkg_status.log | awk '{print $1}')
		if [ -z "${install_timestamp}" -o "${install_timestamp}" = "__install_date__" ];
		then
			install_date=$(date '+%f')
		else
			install_date=$(date -d @$install_timestamp '+%f')
		fi

		# Update the entry in update log
		sed -i -E "s/^__install_date__ -- Update from ${package}:.*/${install_date} -- Update from ${ipk_filename}: ${status}/" /tmp/update.log
	done

	# Generate the final status line
	awk 'BEGIN{
		ok=0
		failed=0
		partial=0
		status="OK"
		date_cmd="date '+\%f'"
		date_cmd | getline date_install
		close(date_cmd)}
	/OK$/ {ok+=1}
	/PARTIAL (\d*)/ {partial+=1}
	/ERROR (\d*)/ {failed+=1}
	END{
		if (failed>0)
			{status="FAILURE"}
		else if (partial>0)
			{status="PARTIAL"}
		printf("%s -- Update Status : updated %d, failed %d , partial %d result : %s\n", date_install, ok, failed, partial, status)}' /tmp/update.log >> /tmp/update.log

	# Move the update journal at final place
	cp -f /tmp/update.log /user/.update

	# Clean
	rm -f /user/.opkg_status

	echo "Done"
}

# Append this upgrade in the upgrade journal in /user
#
update_user_logfile()
{
	echo "Updating ${USER_LOGFILE}..."
	[ -f ${USER_LOGFILE_ARCHIVE} ] && tar -xvzf ${USER_LOGFILE_ARCHIVE} -C /user
	cat ${LOGFILE} >> /user/${USER_LOGFILE}
	echo "Done"
}

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

detect_emmc
mount_safezone

echo -e "\n== Start of PREREBOOT 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}/*  /user/

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