#!/bin/bash
# Monthly emissions replay for Linux/cron. Requires Bash and util-linux flock.
set -euo pipefail

ENV_FILE="${FINOPS_ENV_FILE:-$HOME/config/optiwise-batches.env}"
if [[ ! -r "$ENV_FILE" ]]; then
  printf 'Configuration illisible : %s\n' "$ENV_FILE" >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
source "$ENV_FILE"
set +a

export TZ="Europe/Paris"
export PATH="${PATH:-/usr/local/bin:/usr/bin:/bin}"
FINOPS_BIN="${FINOPS_BIN:-$HOME/bin/finops-batches}"
MONTHS="${CARBON_REPLAY_MONTHS:-3}"
STATE_DIR="${CARBON_STATE_DIR:-$HOME/.cache/optiwise}"

log() {
  printf '[%s] %s\n' "$(date '+%Y-%m-%dT%H:%M:%S%z')" "$*"
}

if [[ ! "$MONTHS" =~ ^([1-9]|1[0-2])$ ]]; then
  log 'ERREUR : CARBON_REPLAY_MONTHS doit être un entier entre 1 et 12.' >&2
  exit 1
fi
if [[ ! -x "$FINOPS_BIN" ]]; then
  log "ERREUR : exécutable introuvable : $FINOPS_BIN" >&2
  exit 1
fi
if ! command -v flock >/dev/null 2>&1; then
  log 'ERREUR : flock (util-linux) est nécessaire pour le verrou cron.' >&2
  exit 1
fi

mkdir -p "$STATE_DIR"
exec 9>"$STATE_DIR/carbon-monthly.lock"
if ! flock -n 9; then
  log 'ERREUR : un import carbone mensuel est déjà en cours.' >&2
  exit 75
fi

# Use calendar arithmetic anchored to the first day of the current month.
# No subtraction from dates such as March 31, and no GNU date dependency.
CURRENT_MONTH="$(date '+%Y-%m')"
YEAR="${CURRENT_MONTH%-*}"
MONTH="${CURRENT_MONTH#*-}"
ANCHOR=$((10#$YEAR * 12 + 10#$MONTH - 1))
FAILED=()

run_chain() {
  local provider="$1" business_date="$2" stage job
  for stage in bronze silver gold; do
    job="${provider}.carbon.${stage}.monthly"
    log "Lancement : $job @ $business_date"
    if "$FINOPS_BIN" run "$job" --business-date "$business_date"; then
      log "SUCCÈS : $job @ $business_date"
    else
      log "ÉCHEC : $job @ $business_date ; étapes suivantes ignorées pour cette chaîne." >&2
      return 1
    fi
  done
}

log "Début FinOps carbone : reprise des $MONTHS derniers mois terminés."
for ((OFFSET=MONTHS; OFFSET>=1; OFFSET--)); do
  INDEX=$((ANCHOR - OFFSET))
  printf -v BUSINESS_DATE '%04d-%02d-01' "$((INDEX / 12))" "$((INDEX % 12 + 1))"
  for PROVIDER in gcp azure; do
    if run_chain "$PROVIDER" "$BUSINESS_DATE"; then
      log "Mois terminé : $PROVIDER @ $BUSINESS_DATE"
    else
      FAILED+=("${PROVIDER}@${BUSINESS_DATE}")
    fi
  done
done

if ((${#FAILED[@]})); then
  log "Fin avec échec(s) : ${FAILED[*]}" >&2
  exit 1
fi
log 'FinOps carbone terminé avec succès.'
