#!/bin/sh

# update_env.sh

boot_switch=$(fw_printenv -n my_boot_switch)
next_boot_switch=$((1 - ${boot_switch}))


if [ "$boot_switch" != 0 -a "$boot_switch" != 1 ]
then
	echo "ERROR: Unerwarteter Wert in U-Boot-Umgebungsvariable my_boot_switch: $boot_switch"
	exit 1
fi

if [ "$next_boot_switch" != 0 -a "$next_boot_switch" != 1 ]
then
	echo "ERROR: Unerwarteter berechneter neuer Wert fuer my_boot_switch: $next_boot_switch"
	exit 1
fi

if [ -f update_kernel.sh ]
then
	cv_board=$(fw_printenv -n CV_BOARD)
	echo "cv_board=${cv_board}"
	if [ "$cv_board" = "CV_34_39_500B" ]
	then
		kernel=uImage.CV_34_39_500B
	elif [ "$cv_board" = "CV_34_39_500" ]
	then
		kernel=uImage.CV_34_39_500
	else
		kernel=uImage.CV_34_39_500A
	fi

	if ! [ -f $kernel ]
	then
		echo "ERROR: update-tarball enthaelt update_kernel.sh, aber nicht $kernel"
		exit 1
	fi

	next_kernel_size=$(printf '%x' $(stat -L -c "%s" $kernel))
else
	last_kernel=/data/update/last_kernel${boot_switch}
	if ! [ -f $last_kernel ]
	then
		echo "ERROR: Kein alter Kernel vorhanden obwohl upate-tarball update_kernel.sh nicht enthaelt!"
		exit 1
	fi
	next_kernel_size=$(printf '%x' $(stat -L -c "%s" $last_kernel))
fi

echo "next_kernel_size is $next_kernel_size"

# if ! printf "my_boot_switch ${next_boot_switch}\nmy_boot_switch_dirty 1\nboot_os 0\nmy_fallback_allowed 1\nmy_kernel${next_boot_switch}_size $next_kernel_size\n" >/tmp/_update_fw_script.txt
if ! printf "my_boot_switch ${next_boot_switch}\nmy_boot_switch_dirty 1\nboot_os 0\nmy_kernel${next_boot_switch}_size $next_kernel_size\n" >/tmp/_update_fw_script.txt
then
	echo "ERROR: /tmp/_update_fw_script.txt nicht erstellt."
	exit 1
fi

if ! printf "bootcmd echo 'reset hmi'; gpio clear 42; gpio clear 43; sleep 0.2; gpio set 43; if mmc rescan; then if load mmc 0:1 $loadaddr /boot.scr; then source $loadaddr; fi; fi; run my_nand_boot;\n" >> /tmp/_update_fw_script.txt
then
	echo "ERROR: /tmp/_update_fw_script.txt nicht erstellt."
	exit 1
fi

if ! fw_setenv -s /tmp/_update_fw_script.txt
then
	echo "ERROR: /tmp/_update_fw_script.txt nicht mit fw_setenv ausgefuehrt."
	exit 1
fi

if ! rm /tmp/_update_fw_script.txt
then
	echo "ERROR: /tmp/_update_fw_script.txt nicht wieder aufgeraeumt."
	exit 1
fi


