#!/bin/bash

. /etc/tos/scripts/scripts

WGET_CONF=/etc/tos/wget.conf
PUBLIC_REALPATH=$(readlink -f /mnt/public)
[ -z "$PUBLIC_REALPATH" ] && exit 1

make_local(){
    local PAR=$(dirname "$PUBLIC_REALPATH")
    local appdir=$PAR/application
    [ ! -d $appdir ] && mkdir -m 777 -p $appdir >/dev/null
    ln -fsn $appdir /usr/local >/dev/null
    echo $appdir
}

if [ ! -L /usr/local ]; then
    rm -fr /usr/local
    appdir=`make_local`
else
    appdir=`readlink -f /usr/local`
    [ -z "$appdir" ] && appdir=`make_local`
fi

pkgdir=$appdir/pkgs
releasedir=$appdir/uninstall
versiondir=$appdir/version
selfpid=$$
logfile=""
savepath=""
if [ ! -d $pkgdir ]; then
    mkdir -m 777 -p $pkgdir
fi
if [ ! -d $releasedir ]; then
    mkdir -m 777 -p $releasedir
fi
# add the new version
if [ ! -d $versiondir ]; then
    mkdir -m 777 -p $versiondir
fi

tpk_handle(){
    local id=$1
    local pkg_path=$2
    local json_pkg=${pkgdir}/${id}.bz2
    local json_string=`dd if=$pkg_path bs=1024 count=1 2>/dev/null`
    local json_id=`echo "$json_string" | jq -r .id 2>/dev/null`
    local json_platform=`echo "$json_string" | jq -r .platform 2>/dev/null`
    local json_md5=`echo "$json_string" | jq -r .md5 2>/dev/null`
    if [ "$json_platform" != "$(uname -m)" ]; then
        return 1
    fi
    if [ "$json_id" != "$id" ]; then
        return 1
    fi
    dd if=$pkg_path of=${json_pkg} bs=1024 skip=10 2>/dev/null
    local temp_md5=`md5sum ${json_pkg} | awk '{print $1}'`
    if [ "$temp_md5" != "$json_md5" ]; then
        rm -f "${json_pkg}" >/dev/null
        return 1
    fi
    echo $json_pkg
    return 0
}

make_log(){
    local msg=$1
    local jsonfile=$2
    echo "{\"now\":\"0\",\"total\":\"100\",\"complete\":\"0\",\"reboot\":\"0\",\"error\":\"$msg\",\"step\":\"\",\"description\":\"\"}" > $jsonfile
}

app_install(){
    local id=$1
    local pkg_path="$2"
    local jsonfile=/tmp/databack/json-${id}
    local ret=`ps -ef | grep pkgs/${id}/install | grep -v grep`
    if [ ! -z "$ret" ]; then
        return 1
    fi
    make_log "" $jsonfile
    if [ -z "$pkg_path" -o ! -e "$pkg_path" ]; then
        make_log "$pkg_path is not exist!" $jsonfile
        return 1
    fi
    local listFile=${releasedir}/${id}
    local tarpath=${pkgdir}/${id}
    local fileType="bz2"
    [ ! -e "$tarpath" ] && mkdir -p $tarpath
    # is .tpk
    echo "$pkg_path" | grep ".tpk$" > /dev/null
    if [ $? -eq 0 ]; then
        fileType="tpk"
        local json_pkg=`tpk_handle "$id" "$pkg_path"`
        if [ $? -ne 0 ]; then
            make_log "$id $pkg_path is not same" $jsonfile
            return 1
        fi
        tar -xf $json_pkg -C $tarpath/
        rm -f "${json_pkg}"
    else
        tar -xf $pkg_path -C $tarpath/
    fi
    # upload by handle
    echo "$pkg_path" | grep "/upload/" >/dev/null
    if [ $? -eq 0 ]; then
        mv "$pkg_path" /usr/local/pkgs/${id}.${fileType} -f
    fi
    # wait remove process...
    while [ 1 ]; do
        [ ! -e "$listFile" ] && break  
        sleep 1
    done
    local install="$tarpath/install"
    if [ ! -f "$install" ];then
        make_log "$install is not exist" $jsonfile
        return 1
    else
        $install >/dev/null &
        # sleep for wait install...
        sleep 1
        return 0
    fi
}

app_download(){
    local id=$1
    local download_url=$2
    local hash=$3
    local WGET=/usr/bin/wget
    if [  -z "$id" -o -z "$download_url" -o -z "$hash" ]; then
        return 1
    fi
    logfile="/tmp/wget-${id}"
    savepath="${pkgdir}/${id}.bz2"
    echo "$download_url" | grep ".tpk$" >/dev/null
    if [ $? -eq 0 ]; then
        savepath="${pkgdir}/${id}.tpk"
    fi
    local md5=""
    [ -e "$savepath" ] && md5=`md5sum "$savepath" | awk '{print $1}'`
    if [ "$hash" != "$md5" ]; then
        rm -f $logfile "$savepath" "${savepath}_downloading" >/dev/null 2>&1
        local ssl=""
        echo $url | grep 'https://' > /dev/null
        [ $? -eq 0 ] && ssl="--no-check-certificate"
        if [ -e /usr/bin/ter_wget ]; then
            WGET=/usr/bin/ter_wget
        fi
        $WGET $ssl -S -c "$download_url" -O "${savepath}_downloading" --config=${WGET_CONF} -b -o ${logfile} >/dev/null 2>&1
        return 2
    fi
    return 0
}

download_status(){
    local error=`awk '/unable to resolve host/' $logfile`
    if [ ! -z "$error" ]; then
        rm -f "${savepath}_downloading" >/dev/null 2>&1
        return 1
    fi
    error=`awk '/ERROR/' $logfile`
    if [ ! -z "$error" ]; then
        rm -f "${savepath}_downloading" >/dev/null 2>&1
        return 1
    fi
    error=`awk '/error/' $logfile`
    if [ ! -z "$error" ]; then
        rm -f "${savepath}_downloading" >/dev/null 2>&1
        return 1
    fi
    error=`awk '/timed out/' $logfile`
    if [ ! -z "$error" ]; then
        rm -f "${savepath}_downloading" >/dev/null 2>&1
        return 1
    fi
    error=`awk '/Connection closed(.*)Giving up/' $logfile`
    if [ ! -z "$error" ]; then
        rm -f "${savepath}_downloading" >/dev/null 2>&1
        return 1
    fi
    local saved=`awk '/saved/' $logfile`
    local retrieving=`awk '/not retrieving/' $logfile`
    if [ ! -z "$saved" -o ! -z "$retrieving" ]; then
        rename_from_temppkg
        return 0
    fi
    local process=`awk '{gsub(/\./,"")} /([0-9]+%)/' $logfile | awk 'END{print $2}'`
    if [ ! -z "$process" ]; then
        process=${process%%\%*}
        if [ $process -ge 100 ]; then            
            rename_from_temppkg
            return 0
        fi
    fi
    return 2
}

rename_from_temppkg(){
    sleep 1
    if [ -e "${savepath}_downloading" ]; then            
        mv -f "${savepath}_downloading" "${savepath}"
    fi
}

case $1 in
    remove)
        shift
        [ -z "$1" ] && exit 1
        ID=$1
        lockname=remove-$ID
        script_get_lock "$lockname" > /dev/null
        [ $? -ne 0 ] && exit 1
        
        listFile=$releasedir/$ID
        [ ! -e "$listFile" ] && exit 1
        awk '/\/etc\/init.d\//' $listFile | while read line
        do
            $line stop > /dev/null 2>&1
            exec_name=`basename $line`
            [ -e /etc/sc.d/$exec_name ] && rm -f /etc/sc.d/$exec_name
        done
        #rm files ...
        while read line
        do
            [ ! -e "$line" ] && continue
            filename=`basename "$line"`
            [ "$filename" = "getent" ] && continue
            [ ! -e "$line" ] && continue
            if [ -d "$line" ]; then
                rm -fr "$line" > /dev/null
            else
                rm -f "$line" > /dev/null
            fi
        done < $listFile
        rm -f $listFile /tmp/.remove.$ID
        if [ -d $versiondir ]; then
            rm -f $versiondir/$ID > /dev/null
        fi
        script_put_lock "$lockname" > /dev/null
        exit 0
        ;;
    install)
        shift
        ID=$1
        PKG_PATH=$2
        
        [ -z "$ID" ] && exit 1
        lockname=install.$ID
        script_get_lock "$lockname" > /dev/null
        [ $? -ne 0 ] && exit 1
        
        app_install "$ID" "$PKG_PATH"
        
        if [ $? -eq 1 ]; then
            script_put_lock "$lockname" > /dev/null
            echo "Usage: `basename $0` [install] [ID] [PKG_PATH]"
            exit 1
        else
            sleep 1
            script_put_lock "$lockname" > /dev/null
            kill $selfpid
        fi
        exit 0
        ;;
    get)
        shift
        ID=$1
        DOWNLOAD_URL=$2
        HASH_VALUE=$3
        [ -z "$ID" -o -z "$DOWNLOAD_URL" ] && exit 1
        lockname=get.$ID
        script_get_lock "$lockname" > /dev/null
        [ $? -ne 0 ] && exit 1
        
        app_download "$ID" "$DOWNLOAD_URL" "$HASH_VALUE"
        result=$?
        if [ $result -eq 1 ]; then
            script_put_lock "$lockname" > /dev/null
            # parameter is error
            echo "Usage: `basename $0` get [ID] [URL] [HASH]"            
            exit 1
        elif [ $result -eq 2 ]; then
            # to check status of downloading
            next=0
            while [ 1 ]; do
                if [ ! -e "$logfile" ]; then
                    sleep 1
                    continue
                fi
                download_status
                ret=$?
                if [ $ret -eq 1 ]; then
                    next=1
                    break
                elif [ $ret -eq 0 ]; then
                    break            
                fi
                sleep 1
            done
            if [ $next -eq 0 ]; then
                app_install "$ID" "$savepath"
            fi
        elif [ ! -z "$savepath" -a -e "$savepath" ]; then
            # can install next ...
            app_install "$ID" "$savepath"
        else
            echo "unkown errors"
            script_put_lock "$lockname" > /dev/null
            exit 1
        fi
        script_put_lock "$lockname" > /dev/null
        exit 0
        ;;
    *)
        echo "Usage: `basename $0` {get|install|remove} {ID} {URL}"
        exit 1
        ;;
esac

