#!/bin/sh
#

board_prepare_upgrade() {
	echo -1000 > /proc/$$/oom_score_adj

	if [ -f "/etc/init.d/hwnat" ] ;then
		/etc/init.d/hwnat stop 2>/dev/null
	fi

	if [ -f "/etc/init.d/sysapihttpd" ] ;then
		/etc/init.d/sysapihttpd stop 2>/dev/null
	fi

	ifdown wan
	sleep 5

	for i in /etc/rc.d/K*; do
		echo "$i" | grep -q '[0-9]\{1,100\}reboot-wdt$'
		if [ $? -eq 0 ]; then continue;	fi
		echo "$i" | grep -q '[0-9]\{1,100\}umount$'
		if [ $? -eq 0 ]; then continue; fi
		$i stop
	done
}

board_start_upgrade_led() {
	gpio 1 1
	gpio l 11 20 20 1 0 4000; sleep 1; gpio l 44 20 20 1 0 4000
}

board_system_upgrade() {
	mount -o remount,size=100% /tmp
	for i in `mount |grep squashfs | cut -d" " -f3`; do umount $i; done
	for i in `mount |grep jffs2 | cut -d" " -f3`; do umount $i; done
	sleep 1
	for i in `mount |grep squashfs | cut -d" " -f3`; do umount $i; done

	upgrade_write_mtd

	reboot
	sleep 30
	reboot -f
}

upgrade_write_mtd() {
	mtd -e ALL write /tmp/backup.bin ALL
}

# stop services
board_start_upgrade_led
board_prepare_upgrade

# start board-specific upgrading...
board_system_upgrade
