#!/bin/sh

who=$(id -u)
if [ $who -ne 0 ]; then
  echo 'Exit. System update must be run as root.'
  exit 1
fi

system=$(awk '/system type/ { print $5 }' /proc/cpuinfo 2>/dev/null)

if [ -x /sbin/mtd ];then
	if [ "$system" == "AR7" ];then
		updatecmd="dd bs=16 skip=3 | mtd -r write - linux"
	else
		updatecmd="mtd -r write - linux"
	fi
else
	updatecmd="gunzip -c | tar -xf -"
fi


check_exit() {
	if [ $? -ne 0 ];then
		echo "Update failed."
		exit 1
	fi
}

prepare() {
	cd /
	if [ -x /sbin/cfgfs ];then
		mount -o bind /tmp/.cfgfs/root /etc
		check_exit
		mount -o remount,rw /etc
		check_exit
	fi
	mount -o remount,rw /
	check_exit
	if [ "$system" == "RB532" ];then
		mount -t yaffs2 /dev/mtdblock0 /boot
	elif [ "$system" == "AR7130" ];then
		mount -t yaffs2 /dev/mtdblock1 /boot
	elif [ "$system" == "FOXG20" ];then
		mount -t vfat /dev/mmcblk0p1 /boot
	fi
}

extract_from_file() {
	prepare
        cat $1 | eval $updatecmd
	check_exit
}

extract_from_ssh() {
	prepare
        ssh $1 "cat $2" | eval $updatecmd
	check_exit
}

extract_from_http() {
	prepare
        wget -O - $1 | eval $updatecmd
	check_exit
}
                
case $1 in
        file://*|/*)
                url=$(echo $1|sed -e "s#file://##")
		echo "Updating system from $1"
                extract_from_file $url
                ;;
        ssh://*)
                host=$(echo $1|sed -e "s#ssh://\(.*\):.*#\1#")
                file=$(echo $1|sed -e "s#ssh://.*:\(.*\)#\1#")
		echo "Updating system from $1"
                extract_from_ssh $host $file
                ;;
        http://*|ftp://*)
		echo "Updating system from $1"
                extract_from_http $1
                ;;
        *)
                echo "No or wrong uri given. exit."
		echo "Use one of the following uri:"
		echo "http://myserver/myupdate.tar.gz"
		echo "ssh://myuser@myserver:/my/path/myupdate.tar.gz"
		echo "file:///mypath/myupdate.tar.gz"
                exit 1
                ;;
esac

# fix permissions
if [ -f /usr/bin/sudo ];then
	chmod 4755 /usr/bin/sudo
fi
if [ -f /usr/bin/Xorg ];then
	chmod 4755 /usr/bin/Xorg
fi

sync
if [ -x /sbin/cfgfs ];then
	umount /etc
fi
if [ "$system" == "RB532" ];then
	umount -f /boot
elif [ "$system" == "AR7130" ];then
	umount -f /boot
elif [ "$system" == "FOXG20" ];then
	umount -f /boot
fi

echo "Update sucessful. You should reboot now."