#!/bin/bash

if [[ $# != 1 ]];then
    echo -e "Usage: ./$0 file"
    exit 1
fi

dest=$1
filename=$(basename $dest)
dirname=$(dirname $dest)

if [[ -f $dest || ! -e $dest ]];then
    :
else
    echo "'$dest' is not a regular file"
    exit 1
fi

n=30
while [[ $n -gt 1 ]]
do
    if [[ `ps -ef |grep -c wget` -gt 1 ]];then
        sleep 1
    else
        break
    fi
    n=$(($n+1))
done

md5=`curl -s http://softlib.service.ucloud.cn/usa/vmzone/Templateimg/md5sum.txt|grep "$filename$"|awk '{ print $1 }'`

echo "check md5: $dest"
if [[ $md5 == `md5sum $dest|awk '{ print $1 }'` ]];then
    echo "pass"
    exit 0
else
    echo "md5 not equal, downloading..."
    rm -f $dest
    wget http://softlib.service.ucloud.cn/usa/vmzone/Templateimg/$filename -P $dirname
fi

echo "check md5: $dest"
if [[ $md5 == `md5sum $dest|awk '{ print $1 }'` ]];then
    echo "pass"
    exit 0
fi

echo "failed, exit 1"
exit 1
