#!/bin/bash
#set -x

readonly INPUT_DATE="$1"
readonly INPUT_HOUR="$2"
readonly INPUT_END_COUNT="$3"
readonly PROGNAME="$(basename $0)"
readonly INPUT_DATE_NEW=$(date +%Y%m%d)
# 新代码：自动生成当天日期，入参只读时次、预报时长

#readonly SRC_BASE_URL="https://noaa-gfs-bdp-pds.s3.amazonaws.com/"
readonly SRC_BASE_URL="https://nomads.ncep.noaa.gov/pub/data/nccf/com/gfs/prod"
readonly ARMOS_PATH="gfs.${INPUT_DATE_NEW}/${INPUT_HOUR}/atmos"
readonly SAVE_PATH="/data/public/Goldwind/gfs/"
readonly ARIA2C="/usr/bin/aria2c"
readonly PGRB_PREFIX="gfs.t"
readonly PGRB_SUFFIX="z.pgrb2.0p25.f"
readonly TIMES=$(seq 123 3 $INPUT_END_COUNT)
readonly RETRYS=10
readonly CHECK_FILE_SIZE="400000000"

download(){
    local src_path="$1"
    local dst_path="$2"
    local dst_file="$3"
    
    echo "download $src_path starting..."
    #$ARIA2C -c -x 4 -s 4 $src_path -d $dst_path -o $dst_file
    wget --no-check-certificate -q -c -O $dst_path/$dst_file $src_path
    #$RCLONE copyurl $src_path $dst_path --multi-thread-cutoff 100M --multi-thread-streams 4

}

download_gfs_pgrb(){
    local hour="$1"
    local tim="$2"
    local dst_path="$3"
    local src_file_name="${PGRB_PREFIX}${hour}${PGRB_SUFFIX}${tim}"
    local src_file_url="${SRC_BASE_URL}/${ARMOS_PATH}/${src_file_name}"
    local dst_file_path="${dst_path}/${src_file_name}"
    
    if [[ ! -f $dst_file_path ]]
    then
        download $src_file_url $dst_path $src_file_name
    fi

    # check file size, defualt check 3 times, if false exit 1
    for i in $(seq $RETRYS)
    do 
        fs=$(stat -c %s $dst_file_path)
        if [[ $fs -lt $CHECK_FILE_SIZE ]]
        then
            sleep 60
            echo "retry $i download $src_file_url"
            download $src_file_url $dst_path $src_file_name
        else
            break
        fi
    done
}

download_gfs_pgrbs(){
    local ymd="$1"
    local hour="$2"
    local dst_path="${SAVE_PATH}/${ARMOS_PATH}"

    [[ -d $dst_path ]] || mkdir -pv $dst_path
    
    for t in $TIMES
    do
       tim=$(printf "%03d" $t)
       download_gfs_pgrb $hour $tim $dst_path
    done 
}

check_download_status(){
    local hour="$1"
    local dst_path="${SAVE_PATH}/${ARMOS_PATH}"
    local status_code=0

    for t in $TIMES
    do
        tim=$(printf "%03d" $t)
        file_name="${PGRB_PREFIX}${hour}${PGRB_SUFFIX}${tim}"
        dst_file="${dst_path}/${file_name}"
        if [[ ! -f "$dst_file" ]]
        then
            let status_code++
        fi

        fs=$(stat -c %s $dst_file)
        if [[ $fs -lt $CHECK_FILE_SIZE ]]
        then
            let status_code++
        fi
    done
    echo $status_code
}

main(){
    if [[ "$INPUT_DATE" != "" && "$INPUT_HOUR" != "" && "$INPUT_END_COUNT" != "" ]]
    then
        download_gfs_pgrbs $INPUT_DATE_NEW $INPUT_HOUR
        status=$(check_download_status $INPUT_HOUR)
        exit $status
    else
         echo "please input date"
        echo "eg: $PROGNAME 20231013 00 72"
        exit 1
    fi
}

main
