#!/bin/sh

. /etc/profile >/dev/null
. /etc/tos/scripts/scripts
if [ -z "$1" -o -z "$2" ]; then
    echo "`basename $0` {url} {hash}"
    exit 1
fi

script_get_lock
[ $? -ne 0 ] && exit 1
#download url
URL="$1"
#download file md5 check
HASH="$2"
#download method https or http
OPTS=""
echo "$URL" | grep "https://" >/dev/null
if [ $? -eq 0 ]; then
     OPTS="--no-check-certificate"
fi
DESTFILE=/root/initboot.tar
try=0
while [ $try -lt 30 ]; do
    rm -f $DESTFILE
    echo "TOS_TRY_DOWNLOAD:$try" > /tmp/initboot.log
    wget $OPTS --server-response -nc --referer="$URL" "$URL" -O $DESTFILE -T 60 -t 5 -o /tmp/initboot.log
    sync
    if [ -e $DESTFILE ]; then
        newhash=`md5sum $DESTFILE | awk '{print $1}'`
        if [ "$newhash" = "$HASH" ]; then
            tar -xf $DESTFILE -C /
            rm -f $DESTFILE
            break
        fi
    fi
    let try=try+1
done

script_put_lock
exit 0
