#!/bin/sh
# Copyright (C) 2013 OpenWrt.org
newboot=6ffc3416e32f1c8e0723bc0e854df92f
newbootpath=/rom/sbin/$newboot

compare_uboot() {
	dd if=/dev/mtd4 of=/tmp/now_uboot bs=1024 count=128
	dd if=$newbootpath of=/tmp/new_uboot bs=1024 count=128
	now_uboot_md5=$(md5sum /tmp/now_uboot | cut -d ' ' -f1)
	new_uboot_md5=$(md5sum /tmp/new_uboot | cut -d ' ' -f1)
	if [ "$now_uboot_md5" = "$new_uboot_md5" ]; then
		uci set system.@system[0].ubootStatus='success'
	elif [ -z "$new_uboot_md5" ]; then
		uci set system.@system[0].ubootStatus="no new boot on firmware"
	else
		uci set system.@system[0].ubootStatus="uboot upgrade fail[$now_uboot_md5:$new_uboot_md5]"
	fi
	uci commit system
	rm /tmp/now_uboot
	rm /tmp/new_uboot
}

upgrade_uboot() {
	if [ -f $newbootpath ]; then
		echo "upgrading uboot!" > /dev/console
		mtd erase /dev/mtd4
		mtd write $newbootpath /dev/mtd4
		fw_setenv ubootversion $newboot
	fi
	compare_uboot
}

security_upgrade=$(cat /proc/cmdline | grep uboot=)
if [ -z "$security_upgrade" ]; then
	echo "do not support uboot upgrade!"  > /dev/console
	compare_uboot
else
	oldboot=$(fw_printenv ubootversion | grep ubootversion= | awk -F"=" '{print $2}')
	if [ "$oldboot" != "$newboot" ]; then
		compare_uboot
		ubootStatus=$(uci -q get system.@system[0].ubootStatus)
	else
		ubootStatus=$(uci -q get system.@system[0].ubootStatus)
		if [ "$ubootStatus" != "success" ]; then
			ubootStatus=success
			uci set system.@system[0].ubootStatus='success'
			uci commit system
		fi
	fi
	
	if [ "$ubootStatus" != "success" ]; then
		upgrade_uboot
	fi
fi
