#!/bin/sh

if [ $# -lt 1 ]; then
    echo "usage: $0 <value>"
    echo "value:"
    echo "       system       query system version"
    echo "       app appname  query app versioin"
    echo "       upmode       query ota update mode"
    echo "       upflag       query ota update flag"
    echo "       partstatus   query ota partitions status"
    echo "       progress     query current ota update progress"
    echo "       checksuccess query current ota update result"
    exit 1
fi

value=$1

if [ x"$value" = x"system" ];then
    version=`hbipc-utils run "cat /etc/version"`
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "file /etc/version not exist"
        exit 1
    else
        echo "$version"
        exit 0
    fi
elif [ x"$value" = x"app" ];then
    name=$2
    [ -z "$name" ] && echo "miss appname" && exit 1
    version=`hbipc-utils run "cat /app/$name/version"`
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "app $name version not exist"
        exit 1
    else
        echo "$version"
        exit 0
    fi
elif [ x"$value" = x"upmode" ];then
    upmode=`hbipc-utils run "hrut_otastatus g upmode"`
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "file hrut_otastatus not exist"
        exit 1
    else
        echo "$upmode"
        exit 0
    fi
elif [ x"$value" = x"upflag" ];then
    upflag=`hbipc-utils run "hrut_otastatus g upflag"`
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "file hrut_otastatus not exist"
        exit 1
    else
        echo "$upflag"
        exit 0
    fi
elif [ x"$value" = x"partstatus" ];then
    partstatus=`hbipc-utils run "hrut_otastatus g partstatus"`
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "file hrut_otastatus not exist"
        exit 1
    else
        echo "$partstatus"
        exit 0
    fi
elif [ x"$value" = x"progress" ];then
    hbipc-utils run "hrut_checkprogress l" > /tmp/out
    if [ $? -ne 0 ];then
        echo "X2 not ready yet"
        exit 1
    else
        cat /tmp/out | tail -n1
        exit 0
    fi
elif [ x"$value" = x"checksuccess" ];then
    hbipc-utils run hrut_checksuccess > /dev/null
    ret=$?
    if [ $ret -eq 255 ]; then
        echo "X2 not ready yet"
        exit 1
    elif [ $ret -eq 0 ]; then
        echo "update result in checking..."
        exit 1
    elif [ $ret -eq 1 ]; then
        echo "update success"
        exit 0
    else
        echo "update fail, error code $ret"
        exit 1
    fi
else
    echo "unsuppport command"
    exit 1
fi
