#!/bin/sh
#===============================================================================
#
#  Copyright (C) 2021-2023 by Digi International Inc.
#  All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License version 2 as published by
#  the Free Software Foundation.
#
#
#  !Description: Verifies successful boot
#
#===============================================================================

dualboot_init () {
	ACTIVE_SYSTEM="$(fw_printenv -n active_system 2>/dev/null)"
	if [ -z "${ACTIVE_SYSTEM}" ]; then
		# Check if the rootfs is ubifs to determine if it is a nand or emmc device
		NANDROOTFS="$(grep -qs '[[:blank:]]\+/[[:blank:]]\+ubifs.*' /proc/mounts 2>/dev/null && echo 1)"
		if [ -z "${NANDROOTFS}" ]; then
			BOOT_PART="$(fw_printenv -n mmcpart 2>/dev/null)"
			BOOT_DEV="$(fw_printenv -n mmcbootdev 2>/dev/null)"
			CURRENT_PART="$(sed -ne 's,PARTNAME=,,g;T;p' /sys/class/block/mmcblk"${BOOT_DEV}"p"${BOOT_PART}"/uevent)"
			fw_setenv active_system "${CURRENT_PART}"
		else
			MTD_BOOT_PART="$(fw_printenv -n mtdbootpart 2>/dev/null)"
			fw_setenv active_system "${MTD_BOOT_PART}"
		fi
	fi
}

case "$1" in
	start)
		if [ "$(fw_printenv -n dualboot 2>/dev/null)" = "yes" ]; then
			echo -n "Starting dualboot check: "
			dualboot_init
			echo "done."
		fi
		;;
	stop)
		;;
	restart)
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac
