#!/usr/bin/env bash
set -euo pipefail

if [[ $# -ne 3 ]]; then
  echo "usage: $0 YYYY MM DD" >&2
  exit 2
fi

year=$1
month=$2
day=$3
case "$day" in
  01) member=01 ;;
  06) member=02 ;;
  11) member=03 ;;
  16) member=04 ;;
  21) member=05 ;;
  26) member=06 ;;
  *) echo "invalid cycle day: $day" >&2; exit 2 ;;
esac

raw_root=/home/tanpv/Data/562_VNU/0.25_VN/Operational/monthly
remap_root=/home/tanpv/Data/562_VNU/0.25_VN/For_BC_Ope
grid_file=/home/tanpv/Progs/Dr_VN_Ope/grid_VN_0.25.dat
destination="$remap_root/$year/$month"

for model in RegCM clWRF; do
  input="$raw_root/$year/$month/${model}_${member}.nc"
  [[ -s "$input" ]] || { echo "missing input: $input" >&2; exit 3; }
done
[[ -s "$grid_file" ]] || { echo "missing grid: $grid_file" >&2; exit 3; }

if ! command -v cdo >/dev/null 2>&1; then
  command -v module >/dev/null 2>&1 && module load cdo
fi
command -v cdo >/dev/null 2>&1 || { echo "cdo is unavailable" >&2; exit 4; }

mkdir -p "$destination"
for model in RegCM clWRF; do
  input="$raw_root/$year/$month/${model}_${member}.nc"
  output="$destination/${model}_${member}.nc"
  temporary="${output}.tmp.$$"
  if [[ -s "$output" && "$output" -nt "$input" ]]; then
    echo "remap already current: $output"
    continue
  fi
  trap 'rm -f "$temporary"' EXIT
  cdo -s remapbil,"$grid_file" "$input" "$temporary"
  mv -f "$temporary" "$output"
  trap - EXIT
  echo "remapped: $output"
done
