#!/usr/bin/env bash
#MISE description="terragrunt plan for a prod deployment stack (builds providers, renders creds from 1Password). SITE selects the stack."
set -euo pipefail
ROOT=$(git rev-parse --show-toplevel)

# OpenTofu's Go binary doesn't read the macOS keychain, so the OVH S3 backend's
# cert fails to verify locally ("unknown authority"). Point it at the system CA
# bundle on macOS; Linux/CI reads its trust store fine and is left alone.
if [ -z "${SSL_CERT_FILE:-}" ] && [ "$(uname -s)" = "Darwin" ] && [ -f /etc/ssl/cert.pem ]; then
  export SSL_CERT_FILE=/etc/ssl/cert.pem AWS_CA_BUNDLE=/etc/ssl/cert.pem
fi

mise run infra:providers

# Resolve a (read-scoped) service-account token. CI provides one in
# OP_SERVICE_ACCOUNT_TOKEN; locally we read it from the vault via an interactive
# team-futo sign-in. Exporting it makes every downstream `op`/`op run` use that
# SA (and the right account) — plan stays read-only, so no write escalation.
if [ -z "${OP_SERVICE_ACCOUNT_TOKEN:-}" ]; then
  OP_SERVICE_ACCOUNT_TOKEN=$(op read --account "${OP_ACCOUNT:-team-futo}" \
    "op://yucca_tf_prod/yucca_futo_1pass_service_account/password")
  export OP_SERVICE_ACCOUNT_TOKEN
fi

# Render the NETCONF SSH key from 1Password to a 0600 temp file (op run can't
# write files).
KEYF=$(mktemp); chmod 600 "$KEYF"; trap 'rm -f "$KEYF"' EXIT
op read "op://yucca_tf_prod/NET_SWITCHES_TERRAFORM_SSH_PRIVATE_KEY/password" > "$KEYF"

export TF_VAR_netconf_ssh_key_path="$KEYF"
export TF_CLI_CONFIG_FILE="$ROOT/tf/.terraformrc.local"
SITE="${SITE:-htz-fsn1}"
# With a service-account token in the env, drop OP_ACCOUNT — the onepassword
# provider rejects having both set ("service_account_token and account are set").
unset OP_ACCOUNT

# When CI sets TG_PLAN, persist the diff to that (absolute) path so the gated
# apply can consume the EXACT reviewed plan (terragrunt runs tofu inside a
# .terragrunt-cache dir, so a relative -out would be unreachable -- pass an
# absolute path). Local `tf:plan` leaves TG_PLAN unset -> a plain read-only plan.
PLAN_OUT=()
[ -n "${TG_PLAN:-}" ] && PLAN_OUT=(-out="$TG_PLAN")

# jeremmfr/junos is concurrency-safe; the device NETCONF connection-limit is 250.
OP_ENV_FILE=tf/.env.prod "$ROOT/tf/op-run.sh" terragrunt --working-dir "tf/deployment/prod/$SITE/fabric" plan -parallelism=4 "${PLAN_OUT[@]}" "$@"
