#!/bin/sh

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

OPTION_FORCE_FLASH=0

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

prepare_device()
{
    if ! ssh root@$PHONEIP 'cat /fs.ver' | grep '^troll v3\.[0123456789]*$' >/dev/null 2>&1; then
        echo "Incompatible root filesystem detected.  Update Greenphone with USB Flash image."
        echo "Refer to the Greenphone Quick Start Guide for flash instructions."
        exit 1
    fi

    ssh root@$PHONEIP 'updateqtopiahelper killqtopia' || die prepare_device updateqtopiahelper killqtopia
    ssh root@$PHONEIP 'updateqtopiahelper unmountqtopia' || die prepare_device updateqtopiahelper unmountqtopia

    scp $TEMPDIR/flash-status-flashing.gif root@$PHONEIP:/tmp || die prepare_device scp

    ssh root@$PHONEIP 'gifanim /tmp/flash-status-flashing.gif' || die prepare_device gifanim
    ssh root@$PHONEIP 'rm -f /tmp/flash-status-flashing.gif' || die prepare_device rm
}

extract_image()
{
    tar -C $TEMPDIR -xzf $QTOPIA_IMAGE
    if [ $? -ne 0 ]; then
        echo "Create qtopia-greenphone-update.tar.gz using greenphone-make-flash.sh --qtopia"
        die extract_image
    fi

    # check for flash.conf
    if [ -r $TEMPDIR/flash.conf ]; then
        echo "USB Flash image detected.  Refer to the Greenphone Quick Start Guide for flash instructions."
        echo "Create qtopia-greenphone-update.tar.gz using greenphone-make-flash.sh --qtopia"
        exit 1
    fi
}

upload_image()
{
    IMAGE_SIZE=0
    for file in $TEMPDIR/*; do
        IMAGE_SIZE=$(($IMAGE_SIZE + $(stat -c %s $file)))
    done
    IMAGE_SIZE=$(( (2 + ($IMAGE_SIZE / 1048576)) * 1048576 ))

    MNTPNT=$( ssh root@$PHONEIP "updateqtopiahelper createtemp $IMAGE_SIZE" )

    if [ -z $MNTPNT ]; then
        echo "Error creating temporary directory on Greenphone, aborting"
        exit 1
    fi

    scp $TEMPDIR/* root@$PHONEIP:$MNTPNT || die upload_image
}

install_image()
{
    OPTS="--no-questions"
    if [ $OPTION_FORCE_FLASH -eq 1 ]; then
        OPTS="$OPTS --force-flash"
    fi
    ssh root@$PHONEIP "updateqtopia $OPTS $MNTPNT"
    RESULT=$?
    ssh root@$PHONEIP "updateqtopiahelper deletetemp $MNTPNT" || die install_image updateqtopiahelper

    if [ $RESULT -ne 0 ]; then
        sleep 60
    fi
    ssh root@$PHONEIP "reboot" || die install_image reboot
    if [ $RESULT -ne 0 ]; then
        die install_image "\nThe image may be too big, corrupt, already installed, or incompatible with the root filesystem."
    fi
}

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

while [ $# -gt 0 ]; do
    case $1 in
        --force-flash)
            OPTION_FORCE_FLASH=1
            ;;
        --*)
            echo "Unknown option $1, aborting."
            exit 1
            ;;
    esac
    shift
done

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

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

TEMPDIR=$(mktemp -d /tmp/updatedevice.XXXXXX)
trap 'rm -rf $TEMPDIR' 0

# Flash Process
echo "Starting Flash process, please wait..."
extract_image
echo "extract stage complete."
prepare_device
echo "device prep stage complete."
upload_image
echo "uploading image stage complete."
echo
echo "Flashing begins..........please wait....."
install_image
echo "Image installed, phone will reset automatically and start Qtopia"
echo
echo

