#!/usr/bin/env bash
#MISE description="Build the deployment stack's locally-built providers (hetzner) into a filesystem mirror + write its terraformrc"
set -euo pipefail
ROOT=$(git rev-parse --show-toplevel)
MIRROR="${PROVIDER_MIRROR:-$ROOT/.mise/.provider-mirror}"

# hetzner (mgmt-host reprovisioning) is the only provider not on a public registry,
# so it's built locally into the mirror. junos (switch fabric) now comes from the
# registry (jeremmfr/junos); everything else is a normal registry provider.
mise run mgmt:provider-build # hetzner

# Point TF/tofu at the mirror for the locally-built provider only, for both registry
# hosts (OpenTofu -> registry.opentofu.org, Terraform -> registry.terraform.io).
# Everything else resolves `direct` from the registry. Consumed via TF_CLI_CONFIG_FILE.
cat > "$ROOT/tf/.terraformrc.local" <<'EOF'
# Generated by 'mise run infra:providers' — do not edit.
provider_installation {
  filesystem_mirror {
    path    = "__MIRROR__"
    include = [
      "registry.opentofu.org/zack/hetzner", "registry.terraform.io/zack/hetzner",
    ]
  }
  direct {
    exclude = [
      "registry.opentofu.org/zack/hetzner", "registry.terraform.io/zack/hetzner",
    ]
  }
}
EOF
# shellcheck disable=SC2016
sed -i.bak "s#__MIRROR__#${MIRROR}#" "$ROOT/tf/.terraformrc.local" && rm -f "$ROOT/tf/.terraformrc.local.bak"
echo "wrote filesystem_mirror -> tf/.terraformrc.local"
