#!/bin/sh

if [ -r /opt/Qtopia/SDK/scripts/functions ]; then
    . /opt/Qtopia/SDK/scripts/functions
    QPEVER=$(version)
fi
#echo $DEVICE

# TEMPDIR=$(mktemp -d /tmp/updatedevice.XXXXXX)


die()
{
    echo -n "updatedevice failed while doing: "
    echo $@
    exit 1
}

prepare_device()
{
    scp /opt/Qtopia/extras/flash-status-flashing.gif root@$PHONEIP:/tmp 
 #   ssh root@$PHONEIP "/usr/bin/fbv -c -e /tmp/flash-status-flashing.gif &" 
}

install_image()
{

cat $QTOPIA_IMAGE | ssh "root@$PHONEIP" '(set -x;rm -f /tmp/restart-qtopia;killall qpe;sleep 2; rm -rf /opt/Trolltech; rm -rf /opt/Qtopia/*; mkdir -p /opt/qtmoko; cd /opt/qtmoko;gunzip |tar xvf -  )'

 RESULT=$?

    if [ $RESULT -ne 0 ]; then
        sleep 60
    fi
}

restart_image()
{
   ssh root@$PHONEIP '/etc/init.d/qpe start &' || die install_image reboot
   ssh root@$PHONEIP "rm -f /tmp/flash-status-flashing.gif" 
   rm -rf $TEMPDIR
}

# Find default update image
if [ $# -eq 0 ] && [ -r /opt/Qtopia/extras/images/qtopia-${DEVICE}-update.tar.gz ]; then
    QTOPIA_IMAGE=/opt/Qtopia/extras/images/qtopia-${DEVICE}-update.tar.gz
elif [ $# -eq 1 ]; then    
    case "$1" in
        /*)
            QTOPIA_IMAGE="$1"
            ;;
        *)
            QTOPIA_IMAGE="$(pwd)/$1"
            ;;
    esac
else
    echo "usage: $0 [image]"
    exit 1
fi

# Check if network is up
if which sdk >/dev/null 2>&1; then
    # SDK 
    if ! sdk -net; then
        echo "Could not establish a network connection with Neo.  Check connection."
        exit 1
    fi
else
    # not SDK
    if [ -z $PHONEIP ]; then
        PHONEIP=192.168.0.202
    fi

    if ! ssh root@$PHONEIP /bin/true >/dev/null 2>&1; then
        echo "Could not establish a network connection with Neo at $PHONEIP.  Check connection."
        exit 1
    fi
fi


# Flash Process
echo "Starting Flash process, please wait..."

prepare_device
echo "device prep stage complete."

echo "Flashing begins..........please wait....."
install_image
restart_image
echo "Image installed, phone will automatically restart Qtopia"
echo
echo

