#!/bin/sh

export PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
UPDATE_TARBALL=update.tar.gz

echo "Update Script started"
pre_vers=`head -n 1 /etc/cabversion`

path=$PWD

cd /
tar xzf ${path}/${UPDATE_TARBALL}

cd ${path}

for file in /root/uImage-*; do
	test -r ${file} || continue
	size=$(stat -c %s ${file})
	test ${size:-0} -gt 2000000 || continue
	## Disable watchdog
	pic -w 0
	## Partition size: 5242880 Bytes
	## Write the whole partition, pad with 0 after the kernel
	fill=$((5242880-${size}))
	dd if=/dev/zero of=/tmp/zero bs=${fill} count=1
	cat ${file} /tmp/zero > /tmp/newpart
	echo "Installing new kernel: $(basename ${file})"
	dd if=/tmp/newpart of=/dev/mtdblock2
	sync
	break
done

echo "Update finished."

post_vers=`head -n 1 /etc/cabversion`
echo "Updated from ${pre_vers} to ${post_vers}"

echo "The config file /etc/cablynx.conf was untouched."
echo "Please use the new config file in /etc/cablynx.conf.${post_vers#*: }"

