#!/bin/sh
#
# FlyRouter Team (c) 2004-2007 | http://www.flyrouter.net
# Upgrade firmware script
# Version 0.2c 20070808

. /bin/midge_functions

SITE=${SITE:=http://flyrouter.net/downloads/software/flyrouter/firmware}

test -f /etc/midge.conf && . /etc/midge.conf || exit 1

if [ "x$1" = x ]; then
        echo "Usage: $0 [-c] <type>"
        exit
fi


case $1 in
  -c) 
        clear_datafs=1;
        shift
        ;;

esac

image_name=$1
url=$SITE/${image_name}.bin
if echo ${image_name} | grep http:// 2>&1 >/dev/null; then
  url=${image_name}
fi 

echo "Download new Firmware..." 
    wget $url -O /tmp/rootimage || exit 1
    echo "Checking image header..."
    image_header=`dd if=/tmp/rootimage bs=4 count=1`
    [ "$image_header" = "hsqs" ] || die "Warning, bad image header :("
    [ -z "$INITFS_PARTITION_SIZE" ] && die "Warning, unknown partition size :("
    echo "Checking file size..."
    image_size=`dd if=/tmp/rootimage of=/dev/null bs=1024 2>&1 | cut -f1 -d+ | tail -n 1`
    part_size=$(($INITFS_PARTITION_SIZE/1024))
    if [ $image_size -le $part_size ]; then
        echo "Write new Firmware. Plase wait..."
        dd if=/tmp/rootimage of=$INITFS_PARTITION bs=64k
        if [ "$clear_datafs" = 1 ]; then
            echo "Clearing datafs partition..."
            dd if=/dev/zero of=$DATAFS_PARTITION bs=1k count=1
        fi
    else
        die "Image/partition size mistmatch"
    fi
