#!/bin/bash
PATH="${PATH}:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
export TF_VAR_FD_UPDATE_ALL=true
export TF_VAR_FD_UPDATE_INVENTORY=true
export TF_VAR_FD_UPDATE_MONITORING=true
export TF_VAR_FD_UPDATE_NSA=true
USAGE="
${0} <action>
action:
  - apply
  - console
  - destroy
  - env           (0.13 only)
  - fmt
  - force-unlock
  - get
  - graph
  - import
  - init
  - login
  - logout
  - metadata      (1.x only)
  - output
  - plan
  - providers
  - push          (0.13 only)
  - refresh
  - show
  - state
  - taint
  - test          (1.x only)
  - untaint
  - validate
  - version
  - workspace
"
ARGS_LIST=(
  "no-update-all"
  "no-update-inventory"
  "no-update-monitoring"
  "no-update-nsa"
)
TF_OPTS=()
OPTS=()
for OPT in "${@}"
do
    shift
    if [[ "${OPT:0:2}" == "--" ]] || [[ "${OPT:0:1}" != "-" ]];
    then
         set -- "${@}" "${OPT}"
         continue
    fi
    TF_OPTS+=("${OPT}")
done
opts=$(getopt \
  --longoptions "$(printf "%s," "${ARGS_LIST[@]}")" \
  --name "$(basename "${0}")" \
  --options "" \
  -- "${@}"
)
if [ "${?}" -ne 0 ];
then
      echo "${USAGE}" >&2
      exit 1
fi
eval set --${opts}
while [[ $# -gt 0 ]]; do
  case "${1}" in
    --no-update-all)
      export TF_VAR_FD_UPDATE_INVENTORY=false
      export TF_VAR_FD_UPDATE_MONITORING=false
      export TF_VAR_FD_UPDATE_NSA=false
      shift 1
      ;;
    --no-update-inventory)
      export TF_VAR_FD_UPDATE_INVENTORY=false
      shift 1
      ;;
    --no-update-monitoring)
      export TF_VAR_FD_UPDATE_MONITORING=false
      shift 1
      ;;
    --no-update-nsa)
      export TF_VAR_FD_UPDATE_NSA=false
      shift 1
      ;;
    *)
      break
      ;;
  esac
done
if [[ "${@:${OPTIND}:1}" == "--" ]];
then
    shift 1
fi
case "${1}" in
    apply|console|destroy|env|fmt|force-unlock|get|graph|import|init|\
login|logout|metadata|output|plan|providers|push|refresh|show|state|\
taint|test|untaint|validate|version|workspace)
        TF_COMMAND="${1}"
        shift 1
        # Capturer tous les arguments restants (sous-commandes et args positionnels)
        TF_EXTRA_ARGS=("${@}")
    ;;
    *)
        echo "${USAGE}" >&2
        exit 1
    ;;
esac
# Charge secrets
fd-thallium -n "${FD_TERRA_THALLIUM_KEY_NAME:-${THALLIUM_KEY_NAME}}" -a thallium-configure -V -t
# Résoudre les binaires avant le passage à fd-thallium
# Mémoriser si TERRAFORM_BIN était explicitement défini par l'utilisateur
TERRAFORM_BIN_EXPLICIT=0
if [ -n "${TERRAFORM_BIN}" ]; then
    TERRAFORM_BIN_EXPLICIT=1
else
    TERRAFORM_BIN="$(which terraform)"
fi
if [ -z "${TERRAGRUNT_BIN}" ]; then
    TERRAGRUNT_BIN="$(which terragrunt)"
fi
export TERRAFORM_BIN
export TERRAGRUNT_BIN
# --terragrunt-tfpath est supporté depuis terragrunt 0.19+
# Ne le passer que si TERRAFORM_BIN était explicitement défini —
# sinon on laisserait terragrunt.hcl définir terraform_binary (ex: stacks OVH avec tofu)
TERRAGRUNT_SUPPORTS_TFPATH=0
if [ "${TERRAFORM_BIN_EXPLICIT}" -eq 1 ] && "${TERRAGRUNT_BIN}" --help 2>&1 | grep -q "terragrunt-tfpath"; then
    TERRAGRUNT_SUPPORTS_TFPATH=1
fi

# Assume sts role
# TF_OPTS contient les flags -x (ex: -auto-approve, -no-color)
# Ils doivent passer APRÈS les args positionnels (sous-commandes)
# ex: state replace-provider -auto-approve ... et non state -auto-approve replace-provider ...
if [ "${TERRAGRUNT_SUPPORTS_TFPATH}" -eq 1 ]; then
    THALLIUM_KEY_NAME="tf.fjord" \
    fd-thallium -n "tf.fjord" -a terragrunt -V -e -t -- \
      --terragrunt-tfpath "${TERRAFORM_BIN}" \
      ${TF_COMMAND} "${TF_EXTRA_ARGS[@]}" ${TF_OPTS[@]}
else
    THALLIUM_KEY_NAME="tf.fjord" \
    fd-thallium -n "tf.fjord" -a terragrunt -V -e -t -- \
      ${TF_COMMAND} "${TF_EXTRA_ARGS[@]}" ${TF_OPTS[@]}
fi
exit ${?}
