#!/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 doesn't read the macOS keychain, so the OVH S3 backend cert fails to
# verify locally — point at the system CA bundle; Linux/CI is fine untouched.
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

# Read-scoped SA token: CI provides OP_SERVICE_ACCOUNT_TOKEN; locally read it
# via a team-futo sign-in. Exported so every downstream `op` uses that SA — plan
# is read-only, 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

# NETCONF SSH key from 1P to a 0600 temp file (op run can't write files).
# DETERMINISTIC path: it's recorded in the saved plan, so the gated apply must
# render the identical path or tofu rejects the plan ("Mismatch between input
# and plan variable value").
KEYF="${RUNNER_TEMP:-${TMPDIR:-/tmp}}/netconf-terraform-key"
rm -f "$KEYF"; ( umask 077; : > "$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

# TG_PLAN (CI): persist the diff to that ABSOLUTE path for the gated apply
# (terragrunt runs tofu inside .terragrunt-cache — a relative -out is
# unreachable). Unset locally -> 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[@]}" "$@"
