#!/bin/sh /etc/rc.common

START=99

boot() {
	case $(board_name) in
	alfa-network,quad-e4g)
		[ -n "$(fw_printenv bootcount bootchanged 2>/dev/null)" ] &&\
			echo -e "bootcount\nbootchanged\n" | /usr/sbin/fw_setenv -s -
		;;
	beeline,smartbox-turbo|\
	beeline,smartbox-turbo-plus|\
	rostelecom,rt-sf-1)
		[[ $(hexdump -n 1 -e '/1 "%1d"' -s $((0x20001)) /dev/mtd3) == \
			$((0xff)) ]] || printf '\xff' | dd of=/dev/mtdblock3 \
			count=1 bs=1 seek=$((0x20001))
		;;
	jdcloud,re-cp-02)
		echo -e "bootcount 0\nbootlimit 5\nupgrade_available 1"  | /usr/sbin/fw_setenv -s -
		;;
	linksys,e5600|\
	linksys,ea6350-v4|\
	linksys,ea7300-v1|\
	linksys,ea7300-v2|\
	linksys,ea7500-v2|\
	linksys,ea8100-v1|\
	linksys,ea8100-v2)
		mtd resetbc s_env || true
		;;
	belkin,rt1800|\
	linksys,e7350|\
	samknows,whitebox-v8)
		fw_setenv bootcount 0
		;;
	dna,valokuitu-plus-ex400|\
	genexis,pulse-ex400)
		fw_setenv boot_cnt_primary 0
		fw_setenv boot_cnt_alt 0
		;;
	zyxel,lte3301-plus)
		[ $(printf %d $(fw_printenv -n DebugFlag)) -gt 0 ] || fw_setenv DebugFlag 1
		[ $(printf %d $(fw_printenv -n Image1Stable)) -gt 0 ] || fw_setenv Image1Stable 1
		[ $(printf %d $(fw_printenv -n Image1Try)) -gt 0 ] && fw_setenv Image1Try 0
		;;
	zyxel,lte5398-m904|\
	zyxel,lte7490-m904|\
	zyxel,nr7101)
		[ $(printf %d $(fw_printenv -n DebugFlag)) -gt 0 ] || fw_setenv DebugFlag 0x1
		[ $(printf %d $(fw_printenv -n Image1Stable)) -gt 0 ] || fw_setenv Image1Stable 1
		[ $(printf %d $(fw_printenv -n Image1Try)) -gt 0 ] && fw_setenv Image1Try 0
		;;
	teltonika,rutm11|\
	teltonika,rutm30|\
	teltonika,rutm50)
		#Bootloader expect successfull startup value after update, we need to write success value to bootconfig partition
		#otherwise bootloader will fallback to previous root partition
		. /lib/functions.sh
		local PART="$(cmdline_get_var ubi.mtd)"
		local MTD_INDEX=$(find_mtd_index bootconfig-a)

		case "$PART" in
		rutos-a)
			[ "$(md5sum /dev/mtd$MTD_INDEX | awk '{print $1}')" = "adc4a78e76efc6b4afdc41925e4017c6" ] || {
				logger -t "bootcount" "saving new failsafe boot config in /dev/mtd$MTD_INDEX bootconfig-a partition rutos-a"
				echo -ne "\xe1\xb0\xba\xba\x01\x00\xf9\x01\xf8\x01\xf0\x00\x3d\xd4\xfb\x95" | mtd -e bootconfig-a write - bootconfig-a
			}
			;;
		rutos-b)
			[ "$(md5sum /dev/mtd$MTD_INDEX | awk '{print $1}')" = "2904b3476604ef153d1925acdde062e8" ] || {
				logger -t "bootcount" "saving new failsafe boot config in /dev/mtd$MTD_INDEX bootconfig-a partition rutos-b"
				echo -ne "\xe1\xb0\xba\xba\x01\x01\xf7\x01\xf8\x00\xf0\x00\xce\xd4\x44\x08" | mtd -e bootconfig-a write - bootconfig-a
				}
			;;
		esac
		;;
	esac
}
