#!/bin/bash

readonly INPUT_CDATE="$1"
readonly PROGNAME="$(basename $0)"
readonly SRC_BASE_URL="https://nomads.ncep.noaa.gov/pub/data/nccf/com/cfs/v2.3"
readonly SAVE_PATH="/data/public/scsio-ldn/real_time/cfs"
readonly CHECK_FILE_SIZE="400000000"
readonly TIME_RANGE=("00" "06" "12" "18")

download(){
    local src_path="$1"
    local dst_path="$2"
    
    echo "download $src_path starting..."
    echo "wget --no-check-certificate -q -c -O $dst_path $src_path"
    wget --no-check-certificate -q -c -O $dst_path $src_path
}

downloads(){
    local ymd="$1"
    local nymd="$2"

    for ts in ${TIME_RANGE[@]}
    do
        local file_name="flxf${nymd}${ts}.01.${ymd}00.grb2"
        local src_url="${SRC_BASE_URL}/cfs.${ymd}/00/6hrly_grib_01/${file_name}"
        local dst_path="${SAVE_PATH}/cfs.${ymd}/00/6hrly_grib_01"
        local dst_file="${dst_path}/${file_name}"

        if [[ ! -d $dst_path ]]
        then
          mkdir -pv $dst_path
        fi

        if [[ ! -f $dst_file ]]
        then
            download $src_url $dst_file
        fi

        fs=$(stat -c %s $dst_file)
        if [[ $fs -lt $CHECK_FILE_SIZE ]]
        then
            download $src_url $dst_file
        fi 
    done   
}

download_days(){
    local ymd="$1"

    for n in {0..6}
    do
        nymd=$(date -d "$ymd +${n}day" +"%Y%m%d")
        downloads $ymd $nymd
    done
}

main(){
    if [[ "$INPUT_CDATE" != ""  ]]
    then
        download_days $INPUT_CDATE 
    else
        echo "please input date"
        echo "eg: $PROGNAME  20240816"
        exit 1
    fi
}

main
