#!/bin/bash
set -x

readonly INPUT_CDATE="$1"
readonly PROGNAME="$(basename $0)"
readonly SRC_BASE_URL="https://www.ncei.noaa.gov/data/climate-forecast-system/access/operational-9-month-forecast/6-hourly-flux/"
readonly SAVE_PATH="/public5/home/sch5520/data/real_time/cfs/2024/"
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"

    year_month="${ymd:0:6}"
    # 截取年（前4位）
    year="${ymd:0:4}"
    for ts in ${TIME_RANGE[@]}
    do
        #./202401/20240106/2024010600/flxf2024010706.01.2024010600.grb2
        local file_name="flxf${nymd}${ts}.01.${ymd}00.grb2"
        local file_name="flxf${nymd}${ts}.01.${ymd}00.grb2"
        local src_url="${SRC_BASE_URL}/${year}/${year_month}/${ymd}/${ymd}00/${file_name}"
        #202401/20240101/2024010100/
        local dst_path="${SAVE_PATH}/${year_month}/${ymd}/${ymd}00/"
        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
