#!/usr/bin/env bash
# NEMO operational update runner
# - If called with no arguments: uses today's date, ndays=6, do_prep=1
# - If called with 3 args (YYYY MM DD): uses those, ndays=3, do_prep=1
# Optional flags:
#   --no-prep     skip forcing preparation steps
#   --ndays N     override default ndays
#   --debug       enable bash tracing (set -x)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=main_scripts_N421/n421_env.sh
source "${SCRIPT_DIR}/n421_env.sh"

########################################
# Helpers
########################################
usage() {
  cat <<EOF
Usage:
  $0                    # run for today (ndays=6, do_prep=1)
  $0 YYYY MM DD         # run for given date (ndays=3, do_prep=1)
  [--no-prep] [--ndays N] [--debug]

Examples:
  $0 2025 09 02
  $0 --no-prep
  $0 2025 09 02 --ndays 5
EOF
}

msg() { printf "[%s] %s\n" "$(TZ=EET date '+%Y-%m-%d %H:%M:%S (utc%z)')" "$*"; }

########################################
# Defaults & paths
########################################
# Optional overrides:
#   N421_PROJECT_DIR
#   N421_SETUPDIR
#   N421_FORCING_ROOT
#   N421_RUN_ROOT
#   N421_RESTARTDIR
#   CMEMS_USERNAME / CMEMS_PASSWORD
# or an existing copernicusmarine login configuration.
do_prep=1
ndays_auto=6
ndays_manual=3
ndays=""
DEBUG=0

########################################
# Parse args
########################################
if [[ $# -eq 0 ]]; then
  ayy=$(date +%Y)
  amm=$(date +%m)
  add=$(date +%d)
  ndays=$ndays_auto
elif [[ $# -ge 3 ]]; then
  ayy="$1"; shift
  amm="$1"; shift
  add="$1"; shift
  ndays=$ndays_manual
else
  usage; exit 1
fi

# Optional flags
while [[ $# -gt 0 ]]; do
  case "$1" in
    --no-prep) do_prep=0; shift ;;
    --ndays)
      [[ $# -ge 2 ]] || { echo "Error: --ndays requires a value"; exit 1; }
      ndays="$2"; shift 2 ;;
    --debug) DEBUG=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown option: $1"; usage; exit 1 ;;
  esac
done

[[ -n "${ndays}" ]] || ndays="$ndays_auto"

if [[ "${DEBUG}" -eq 1 ]]; then
  set -x
fi

########################################
# Environment modules (if available)
########################################
if command -v module >/dev/null 2>&1; then
  module load prgenv/gnu python3 nco ecmwf-toolbox
  module load openmpi hdf5 netcdf4
  module load cdo/2.1.1
fi

########################################
# Run
########################################
start_epoch=$(date +%s)
export nemo_run_date="$(date +%Y%m%d)"

msg "Starting do_op_update"
msg "Target date: ${ayy}-${amm}-${add}    ndays=${ndays}    do_prep=${do_prep}"
msg "scrdir=${scrdir}"

# Forcing preparation
if [[ "${do_prep}" == "1" ]]; then
  msg "Preparing forcings…"
  #sbatch -W "${scrdir}/do_meteo_ecmwf.sh"       "${ayy}" "${amm}" "${add}" "${ndays}"
  #sbatch -W "${scrdir}/do_runoff.sh"            "${ayy}" "${amm}" "${add}"  
#  sbatch -W "${scrdir}/do_boundary_cmemsnrt.sh" "${ayy}${amm}${add}00" "${ndays}"
#  sbatch -W "${scrdir}/do_boundary_convert.sh"  "${ayy}${amm}${add}00" "${ndays}"
# "${scrdir}/do_boundary_convert.sh"  "${ayy}${amm}${add}00" "${ndays}"
else
  msg "Skipping forcing preparation (--no-prep)"
fi

# Previous-day restart date (GNU date)
start_date="${ayy}-${amm}-${add}"
restart_date_f=$(date --date "${start_date} 1 day ago" +"%Y-%m-%d")
yyrest=$(date +%Y -d "${restart_date_f}")
mmrest=$(date +%m -d "${restart_date_f}")
ddrest=$(date +%d -d "${restart_date_f}")
# If you need rebuild:
# sbatch -W "${scrdir}/do_rebuild_nemo_rest" "${yyrest}" "${mmrest}" "${ddrest}"

msg "Running NEMO…"
"${scrdir}/run_model_op.sh" "${ayy}" "${amm}" "${add}"
exit
#msg "Uploading outputs…"
#"${scrdir}/do_uploads.sh" "${ayy}" "${amm}" "${add}"

elapsed=$(( $(date +%s) - start_epoch ))
msg "do_op_update DONE (elapsed: ${elapsed}s)"
