#!/bin/sh

root_url=http://dl.ranfs.com/pub
APP_NAME=rfsd
dl_dir=tmp
z=7z

if dirname "$0" 1>/dev/null 2>/dev/null; then
    SH_DIR="$(cd "$(dirname "$0")";pwd)"
    cd $SH_DIR
fi

init_func()
{
    . ./$APP_NAME-inc.sh
    init_env
    set_sys_env
    $sudoprefix chmod 755 ./${APP_NAME}

    tval=$(./$APP_NAME -q -s "show_app_info=1" | grep plat)
    plat=${tval#*=}
    tval=$(./$APP_NAME -q -s "show_app_info=1" | grep arch)
    arch=${tval#*=}

    ver_url=$root_url/$APP_NAME/all/update.ini
    pkg_url=$root_url/$APP_NAME/allz/$APP_NAME-$plat-$arch.7z
    z_url=$root_url/tools/7zdec/7zdec-$plat-$arch

    ./$APP_NAME -q -s "update_check_url=$ver_url" -s "update_stability_minute=360"
    laset_eno=$?
    if [ $laset_eno -eq 2 ]; then
        echo "start update ..."
        update_func
    elif [ $laset_eno -eq 0 ]; then
       echo "This is the latest version."
    else
       : #echo "Get [$ver_url] Failed eno=$?"
    fi
    exit $?
}

update_func()
{
    $sudoprefix mkdir $dl_dir 2>/dev/null

    echo "get $z_url ..."
    $sudoprefix ./$APP_NAME -q -s "if=$z_url" -s "of=$dl_dir/$z"
    if [ $? -ne 0 ]; then
        echo "get $z_url failed"
        return
    fi

    echo "get $pkg_url ..."
    $sudoprefix ./$APP_NAME -q -s "if=$pkg_url" -s "of=$dl_dir/$APP_NAME.7z"
    if [ $? -ne 0 ]; then
        echo "get $pkg_url failed"
        return
    fi

    cd $dl_dir
    $sudoprefix chmod 755 ./$z
    $sudoprefix ./$z x $APP_NAME.7z 1>/dev/null
    if [ $? -ne 0 ]; then
        echo "unpack $APP_NAME.7z error"
        return
    fi

    $sudoprefix rm $z $APP_NAME.7z
    $sudoprefix rm $APP_NAME.ini $APP_NAME.crt $APP_NAME.key

    ../$APP_NAME-stop.sh
    $sudoprefix cp -r * ..  >/dev/null
    ../$APP_NAME-start.sh >/dev/null

    cd ..
    $sudoprefix rm -rf $dl_dir >/dev/null
    #start error ...?
    stty sane 2>/dev/null
}

init_func

