#!/usr/bin/env bash
#MISE description="Converge a region's management hosts with ansible/mgmt (root via the TF provisioning key from 1Password). REGION selects the inventory."
set -euo pipefail
ROOT=$(git rev-parse --show-toplevel)
REGION="${REGION:-htz-fsn1}"
INV="$ROOT/ansible/mgmt/inventories/$REGION"

# Per-region: only run where an inventory exists (keeps the prod matrix happy).
if [ ! -d "$INV" ]; then
  echo "mgmt:ansible: no ansible/mgmt inventory for region '$REGION' — skipping."
  exit 0
fi

# Generate the inventory (hosts, host_vars, users) from Terraform's SoT.
mise run mgmt:render-inventory

# op creds: CI provides a (read-scoped) SA token in OP_SERVICE_ACCOUNT_TOKEN;
# locally we sign in to team-futo. Reads only — no write escalation needed.
ACCT=(); [ -z "${OP_SERVICE_ACCOUNT_TOKEN:-}" ] && ACCT=(--account "${OP_ACCOUNT:-team-futo}")

# Provisioning private key (root login) -> 0600 temp file. Item name is
# region-derived: htz-fsn1 -> HTZ_FSN1_PROVISIONING_SSH_PRIVATE_KEY (set by mgmt.tf).
KEY_ITEM="$(printf '%s' "$REGION" | tr 'a-z-' 'A-Z_')_PROVISIONING_SSH_PRIVATE_KEY"
KEYF=$(mktemp); chmod 600 "$KEYF"; trap 'rm -f "$KEYF"' EXIT
op read "${ACCT[@]}" "op://yucca_tf_prod/$KEY_ITEM/password" > "$KEYF"

# NetBird "mgmt" setup key (auto_groups=["mgmt"]) — joins the node to the overlay
# as a route peer. Region-derived item: htz-fsn1 -> NETBIRD_YUCCA_PROD_HTZ_FSN1_MGMT_SETUP_KEY.
NB_KEY_ITEM="NETBIRD_YUCCA_PROD_$(printf '%s' "$REGION" | tr 'a-z-' 'A-Z_')_MGMT_SETUP_KEY"
NB_SETUP_KEY=$(op read "${ACCT[@]}" "op://yucca_tf_prod/$NB_KEY_ITEM/password")

cd "$ROOT/ansible/mgmt"
ansible-galaxy collection install -r requirements.yml >/dev/null
ansible-playbook -i "inventories/$REGION" site.yml \
  --private-key "$KEYF" \
  --extra-vars "mgmt_netbird_setup_key=$NB_SETUP_KEY" "$@"
