# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

load("ext://helm_resource", "helm_repo", "helm_resource")
load("ext://restart_process", "custom_build_with_restart")
load("ext://uibutton", "cmd_button", "text_input")

# ---------------------------------------------------------------------------
# Provider configuration
# ---------------------------------------------------------------------------
# Providers list supports strings and dicts:
#   "capi_core"               -- built-in CAPI core support
#   "bgp-containers"          -- shared BGP router and default-site VIP pool for container nodes
#   "capd"                    -- built-in CAPD support
#   "nico"                    -- CAPNICo plus NICo endpoint (nico-sim by default)
#   "launchlayer"             -- CAPLL plus its fake LaunchLayer API, from capll_source_dir
#   "capd-reboot-controller"  -- CAPD reboot dev controller provider
#   "capi-syscmp"             -- CAPI system component addon provider
#   "dsx-identity-exchange"   -- DSX-compatible JWT exchange test double
#   "dsx-imds-attestation"    -- local DSX IMDS node-attestation fixture
#   {"my-provider": "/path/to/folder"} -- external, Tiltfile at <folder>/Tiltfile
# Default: ["capi_core", "bgp-containers", "capd", "capd-reboot-controller"]

# Provider interface
# ------------------
# Each provider must expose a `register` function in <provider_dir>/Tiltfile:
#
#   def register(ctx):
#       ...
#       return struct(controller_resource_deps, controller_env_overrides,
#                     preflight_script=...)  # optional
#
# Input — ctx is a struct with:
#   ctx.main_dir      (string)  Root directory of the main Tiltfile (config.main_dir).
#   ctx.cfg           (dict)    Parsed tilt_config.json contents.
#   ctx.tilt_env      (dict)    Parsed .env.tilt contents, falling back to .env.tilt.example.
#   ctx.provider_names (list[string]) Enabled provider names, normalized from strings and dicts.
#   ctx.kind_host_ip  (string)  IP reachable from inside Kind pods (e.g. Kind gateway).
#   ctx.kind_cluster_name (string) Name of the active Kind management cluster.
#   ctx.spire_trust_domain (string) Trust domain configured for the local SPIRE server.
#   ctx.site_controller_vip (string) Address reachable from local tenant nodes.
#   ctx.provider_dir  (string)  Absolute path to the provider's root directory.
#
# Output — returned struct with:
#   controller_resource_deps (list[string])     Tilt resource names the controller should depend on.
#                                               Appended to the nvke-controller resource's resource_deps.
#   controller_env_overrides (dict[string, string]) Overrides for .env.tilt. Only the names this file passes to
#                                               the controller's env list reach it; settings in
#                                               nvke-controller-config go through controller_chart_flags.
#   controller_chart_flags (list[string], optional) Additional Helm flags for the controller.
#   spire_chart_flags  (list[string], optional) Additional Helm flags for SPIRE.
#   spire_resource_deps (list[string], optional) Tilt resources SPIRE should depend on.
#   preflight_script   (string, optional)       Bash fragment appended to the
#                                               check-management-cluster preflight script.
#                                               Use to assert provider-required tooling or
#                                               CRDs are present in the cluster.
#
# cwe_resource_deps, cwe_env_overrides and cwe_chart_flags are the deprecated
# names of the three controller_ fields. They are still read for one release.
#
# Inside register(), the provider creates its own Tilt resources (local_resource,
# helm_resource, etc.) and returns the struct to wire itself into the controller.

# Built-in provider name -> directory (relative to config.main_dir, or absolute).
_builtin_provider_dirs = {
    "capi_core": os.path.join(config.main_dir, "hack/capi-core-provider"),
    "bgp-containers": os.path.join(config.main_dir, "hack/bgp-containers"),
    "capd": os.path.join(config.main_dir, "hack/capd-provider"),
    "nico": os.path.join(config.main_dir, "hack/nico-provider"),
    "launchlayer": os.path.join(config.main_dir, "hack/launchlayer-provider"),
    "capd-reboot-controller": os.path.join(config.main_dir, "hack/capd-reboot-controller"),
    "capi-syscmp": os.path.join(config.main_dir, "hack/capi-syscmp-provider"),
    "dsx-identity-exchange": os.path.join(config.main_dir, "hack/dsx-identity-exchange-mock"),
    "dsx-imds-attestation": os.path.join(config.main_dir, "hack/dsx-imds-attestation"),
    "management-engine": os.path.join(config.main_dir, "../management-engine"),
}

_tilt_config = read_json("tilt_config.json", default={})
cfg = _tilt_config
# CI can preload immutable images into Kind and bypass the local Docker builds.
# Local development keeps the existing build behavior when these are unset.
CONTROLLER_IMAGE = cfg.get("nvke_controller_image", "")
# cwe_image is the deprecated name of nvke_controller_image, read for one release.
if not CONTROLLER_IMAGE and cfg.get("cwe_image", ""):
    warn("tilt_config.json: cwe_image is deprecated; rename it to nvke_controller_image.")
    CONTROLLER_IMAGE = cfg["cwe_image"]
SITE_CONTROLLER_VIP_OVERRIDE = cfg.get("site_controller_vip", "")

_provider_entries = cfg.get("providers", [
    "capi_core",
    "bgp-containers",
    "capd",
    "capd-reboot-controller",
])
def _provider_entry_name(entry):
    if type(entry) == "string":
        return entry
    return entry.keys()[0]

_provider_names = [_provider_entry_name(_entry) for _entry in _provider_entries]
DSX_IDENTITY_EXCHANGE_ENABLED = "dsx-identity-exchange" in _provider_names

if "nico" in _provider_names and "capi_core" not in _provider_names:
    fail("Provider 'nico' requires 'capi_core' in the provider list.")

if "capd" in _provider_names and "capi_core" not in _provider_names:
    fail("Provider 'capd' requires 'capi_core' in the provider list.")

if "capi-syscmp" in _provider_names and "capi_core" not in _provider_names:
    fail("Provider 'capi-syscmp' requires 'capi_core' in the provider list.")

if "nico-vm" in _provider_names and "capi_core" not in _provider_names:
    fail("Provider 'nico-vm' requires 'capi_core' in the provider list.")

if "launchlayer" in _provider_names and "capi_core" not in _provider_names:
    fail("Provider 'launchlayer' requires 'capi_core' in the provider list.")

# nico-vm points nico-credentials at the local nico-vms backend and its
# credentials resource depends on the 'nico-vms' Tilt resource by name.
#
# 'nico-vm' and 'nico-vms' are one character apart, so both fail() messages
# below name what each provider IS rather than relying on the key alone.
if "nico-vm" in _provider_names and "nico-vms" not in _provider_names:
    fail("Provider 'nico-vm' (the CAPNICo controller, installed from the NGC Helm chart) " +
         "requires 'nico-vms' (the local VM backend that serves the Forge API on port 18080) " +
         "in the provider list: it points nico-credentials at that backend and depends on " +
         "its Tilt resource by name.")

# 'nico' and 'nico-vms' are mutually exclusive Forge backends for the controller: both
# bind host port 18080 (nico-mock's port-forward vs nico-vms's listener). Enable at
# most one. (capd is orthogonal and may accompany either.)
if "nico" in _provider_names and "nico-vms" in _provider_names:
    fail("Providers 'nico' (nico-mock, container-backed nodes) and 'nico-vms' (real " +
         "KVM/libvirt VMs) are mutually exclusive controller backends: both bind host port 18080. " +
         "Enable only one (capd may accompany either).")

# 'nico' and 'nico-vm' are mutually exclusive ways to get a CAPNICo
# controller: both install one into the capnico-system namespace and own the
# 'nico-credentials' secret it reads. Enable at most one.
if "nico" in _provider_names and "nico-vm" in _provider_names:
    fail("Providers 'nico' (nico-mock, container-backed) and 'nico-vm' (the CAPNICo chart " +
         "from NGC) are mutually exclusive: both install a CAPNICo controller into " +
         "capnico-system and own the 'nico-credentials' secret. Enable only one.")

# The controller accepts only the API provider blocks in supportedInfraProviders. The
# 'nico' provider (nico-sim) serves the container and the nico-vms backends;
# the e2e suite submits Infra blocks to the first and Nico blocks to the second.
_supported_infra_providers = []
if "nico" in _provider_names or "nico-vms" in _provider_names:
    _supported_infra_providers.append("nico")
if "capd" in _provider_names or "nico" in _provider_names or "nico-vm" in _provider_names:
    _supported_infra_providers.append("infra")
if "launchlayer" in _provider_names:
    _supported_infra_providers.append("launchLayer")
if not _supported_infra_providers:
    _supported_infra_providers.append("nico")

CONTROLLER_NAMESPACE = "nke-controller"
TEMPORAL_NAMESPACE = "temporal"
POSTGRES_NAMESPACE = "postgres"
SPIRE_NAMESPACE = "spire-server"
CONTROLLER_LOCAL_DEBUG_MARKER = ".tilt-cwe-debug-local"
# NKE_CONTROLLER_HTTP_PORT, NKE_CONTROLLER_TEMPORAL_UI_PORT, CWE_HTTP_PORT and CWE_TEMPORAL_UI_PORT are deprecated aliases for the NVKE_CONTROLLER_ names; #1399 removes them.
CONTROLLER_HTTP_PORT = os.getenv("NVKE_CONTROLLER_HTTP_PORT", "") or os.getenv("NKE_CONTROLLER_HTTP_PORT", "") or os.getenv("CWE_HTTP_PORT", "") or "8080"
CONTROLLER_TEMPORAL_UI_PORT = os.getenv("NVKE_CONTROLLER_TEMPORAL_UI_PORT", "") or os.getenv("NKE_CONTROLLER_TEMPORAL_UI_PORT", "") or os.getenv("CWE_TEMPORAL_UI_PORT", "") or "8081"

# Tilt UI links open in the browser of whoever views the Tilt UI. When Tilt runs
# on a remote host accessed via forwarded ports (e.g. Mutagen forwards a target
# at +1000), set TILT_LINK_PORT_OFFSET so links point at the correct forwarded
# port. Default 0 = local (links match the host's bind ports). This offsets only
# the displayed link URLs, not the actual service bind / port-forward ports.
LINK_PORT_OFFSET = int(os.getenv("TILT_LINK_PORT_OFFSET", "0"))

def ui_link(port, path, name):
    return link("http://localhost:%d%s" % (int(port) + LINK_PORT_OFFSET, path), name)

# Pin chart versions to avoid surprise breakage from upstream releases.
CHART_VERSION_POSTGRESQL = "18.5.15"
CHART_VERSION_TEMPORAL = "0.74.0"
CHART_VERSION_SPIRE_CRDS = "0.5.0"
CHART_VERSION_CERT_MANAGER = "v1.20.2"

def get_kind_cluster_name():
    kind_cluster_name = os.getenv("KIND_CLUSTER_NAME", "")
    if kind_cluster_name != "":
        return kind_cluster_name

    current_context = k8s_context()
    if current_context.startswith("kind-"):
        return current_context[5:]

    return "kind-cluster-name-not-set"

KIND_CLUSTER_NAME_VALUE = get_kind_cluster_name()
# cwe-capi is the old default cluster. Its SPIRE server still issues
# cwe-capi.nke.local identities, so the derived trust domain below would not
# match them. An explicit KIND_CLUSTER_NAME=cwe-capi is a deliberate choice.
if os.getenv("KIND_CLUSTER_NAME", "") == "" and KIND_CLUSTER_NAME_VALUE == "cwe-capi":
    fail("Kind cluster 'cwe-capi' is the old dev cluster. The dev cluster is now 'controller-capi', with trust domain " +
         "controller-capi.nvke.local. Delete the old cluster with 'kind delete cluster --name cwe-capi', then run " +
         "'make capd-up' and 'tilt up' again.")
EXPECTED_K8S_CONTEXT = "kind-%s" % KIND_CLUSTER_NAME_VALUE
SPIRE_TRUST_DOMAIN = "%s.nvke.local" % KIND_CLUSTER_NAME_VALUE
NKE_OIDC_ISSUER_URL = "https://nke.site-controller.internal"
SPIRE_CONTROLLER_ADMIN_PATH = "/nvke-service/nke-controller"
if DSX_IDENTITY_EXCHANGE_ENABLED:
    SPIRE_CONTROLLER_ADMIN_PATH = "/tenant/nke/service/nke-controller/bm/cwe"

# sha256 of /app/tpm_attestor_server inside ghcr.io/spiffe/spire-tpm-plugin-tpm-attestor-server:v1.9.0,
# selected by host arch (kind pulls the Linux variant matching the host CPU). Override via env var
# when bumping the image; recompute with:
#   docker run --rm --entrypoint sha256sum ghcr.io/spiffe/spire-tpm-plugin-tpm-attestor-server:v1.9.0 /app/tpm_attestor_server
def normalize_arch(arch):
    if arch == "x86_64":
        return "amd64"
    if arch == "aarch64":
        return "arm64"
    return arch

def local_arch():
    docker_arch = str(local("docker version --format '{{.Server.Arch}}' 2>/dev/null || true", quiet=True, echo_off=True)).strip()
    if docker_arch != "":
        return normalize_arch(docker_arch)

    return normalize_arch(str(local("uname -m", quiet=True, echo_off=True)).strip())

def _spire_tpm_attestor_server_checksum():
    override = os.getenv("SPIRE_TPM_ATTESTOR_SERVER_CHECKSUM")
    if override:
        return override

    arch = local_arch()
    checksums = {
        "amd64": "46d0caad8c25a027dd11c93e18b58a8bc6fbd9f1fe2e36fa2a0dd440986de4dc",
        "arm64": "b69d0153c8241383f24da138bc85429a620d9f962a2f10abb314aa0e39046d16",
    }
    if arch not in checksums:
        fail("unsupported host arch %r for SPIRE TPM attestor server; set SPIRE_TPM_ATTESTOR_SERVER_CHECKSUM explicitly" % arch)
    return checksums[arch]

SPIRE_TPM_ATTESTOR_SERVER_CHECKSUM = _spire_tpm_attestor_server_checksum()

if k8s_context() != EXPECTED_K8S_CONTEXT:
    fail("Tilt must run against kube context '%s', but the current context is '%s'" % (EXPECTED_K8S_CONTEXT, k8s_context()))

allow_k8s_contexts(EXPECTED_K8S_CONTEXT)

# Increase the timeout for k8s upsert operations to 15 minutes for large helm charts.
update_settings(k8s_upsert_timeout_secs=900)

def include_user_tilt_files():
    if not os.path.exists("tilt.d"):
        return

    for f in listdir("tilt.d"):
        if not (f.endswith(".tilt") or f.endswith(".star")):
            continue
        include(f)

def parse_env_file(path):
    values = {}
    if not os.path.exists(path):
        return values
    for line in str(read_file(path)).split("\n"):
        line = line.strip()
        if line == "" or line.startswith("#"):
            continue
        parts = line.split("=", 1)
        if len(parts) != 2:
            continue
        values[parts[0].strip()] = parts[1].strip()
    return values

_tilt_env = parse_env_file(os.path.join(config.main_dir, ".env.tilt"))
if not _tilt_env:
    _tilt_env = parse_env_file(os.path.join(config.main_dir, ".env.tilt.example"))

# ---------------------------------------------------------------------------
# cert-manager — needed by the OIDC discovery provider to issue its TLS cert
# from the long-lived NVKE OIDC upstream CA (see deploy/k8s/oidc-upstream-ca-certificate.yaml).
#
# cert-manager is frequently already present out-of-band — most commonly
# clusterctl installs its own copy when it initialises CAPI. We probe the
# cluster at parse time and
# branch:
#   * absent                       -> install via helm (fresh)
#   * present, helm-managed         -> keep the helm_resource so Tilt owns
#                                      upgrades / value changes
#   * present, not helm-managed     -> skip helm entirely; stand up a readiness
#     (e.g. clusterctl)                gate under the same resource name so
#                                      downstream deps stay wired
#
# Either way the resource is named "cert-manager" so dependents (spire-server,
# oidc-ca-bootstrap) need no special-casing. If the cluster is unreachable at
# parse time the probe reports "absent" and we fall back to the helm path —
# the helm_resource depends on check-management-cluster, so nothing actually
# runs until the cluster is up.
# ---------------------------------------------------------------------------
CERT_MANAGER_NAMESPACE = "cert-manager"

def detect_cert_manager():
    # Presence is checked via the CRD (namespace- and installer-agnostic).
    # Ownership is checked via `helm status`, which is authoritative for
    # "Tilt's helm can manage this release".
    state = str(local(
        """
        if ! kubectl get crd certificates.cert-manager.io >/dev/null 2>&1; then
          echo absent
        elif helm status cert-manager -n %s >/dev/null 2>&1; then
          echo helm
        else
          echo external
        fi
        """ % CERT_MANAGER_NAMESPACE,
        quiet=True,
        echo_off=True,
    )).strip()
    # Guard against unexpected output (e.g. unreachable cluster noise): default
    # to the fresh-install path, matching prior behaviour.
    if state not in ("absent", "helm", "external"):
        return "absent"
    return state

# ---------------------------------------------------------------------------
# Provider loading
# ---------------------------------------------------------------------------

# Host IP reachable from inside Kind pods. On macOS, host.docker.internal works.
# On Linux with native Docker, use the Kind network gateway IP.
# Match an IPv4 address rather than filtering out colons. A newer Docker CLI
# renders an absent Gateway as the string "invalid IP" (Go's zero netip.Addr),
# so {{if .Gateway}} is true and the old filter kept "invalid IP". The kind
# network lists its IPv6 subnet, which has no gateway, first.
_kind_host_ip = str(local(
    "docker network inspect kind -f '{{range .IPAM.Config}}{{println .Gateway}}{{end}}' 2>/dev/null | grep -Eo '^[0-9]+(\\.[0-9]+){3}$' | head -1 || true",
    quiet=True,
)).strip() or "host.docker.internal"

# Tenants reach the management cluster's SPIRE + OIDC endpoints at this address
# (the "fake site-controller VIP" in tilt). Linux and macOS need different
# answers because Docker on macOS runs in a VM:
#   * Linux native Docker: bind NodePorts on the kind bridge gateway via
#     kubectl port-forward; tenants dial that IP.
#   * macOS (Docker Desktop or Colima): CAPD tenant nodes are sibling
#     containers on the same `kind` Docker network as the management node
#     (named "<cluster>-control-plane" by Kind), so they can reach it
#     directly by its own container IP — no VM-side proxying or host-side
#     port-forward required. This sidesteps host.docker.internal entirely:
#     under Docker Desktop it works but is unnecessary, and under Colima it
#     resolves to a fixed VM-side gateway address whose port forwarder does
#     not reliably forward the SPIRE OIDC NodePort back through it.
#     host.docker.internal is kept only as a fallback for setups where the
#     management node isn't a "<cluster>-control-plane" container on the
#     `kind` network (e.g. non-CAPD backends).
#   * CI: site_controller_vip may point directly at the Kind control-plane IP;
#     CAPD machines share that Docker network and can use its NodePorts.
_on_mac = str(local("uname -s", quiet=True, echo_off=True)).strip() == "Darwin"
if SITE_CONTROLLER_VIP_OVERRIDE:
    _kind_site_controller_vip = SITE_CONTROLLER_VIP_OVERRIDE
elif _on_mac:
    _management_node_ip = str(local(
        "docker inspect --format '{{(index .NetworkSettings.Networks \"kind\").IPAddress}}' %s-control-plane 2>/dev/null || true" % KIND_CLUSTER_NAME_VALUE,
        quiet=True,
        echo_off=True,
    )).strip()
    _kind_site_controller_vip = _management_node_ip or "host.docker.internal"
else:
    _kind_site_controller_vip = _kind_host_ip

# Collect integration points from all providers.
_all_controller_resource_deps = []
# Default controller env overrides applied before any provider overrides. Providers
# can still .update() these if they need a different value.
#
# SPIRE_SERVER_ADDRESS: tenants reach the SPIRE server through the platform-
# correct site-controller VIP, which the controller bakes into the spire-agent config it
# generates for each tenant. The default in .env.tilt.example is
# host.docker.internal, which only resolves on Docker Desktop; this override
# makes the Linux native Docker path work too.
_all_controller_env_overrides = {
    "SPIRE_SERVER_ADDRESS": _kind_site_controller_vip,
}
_all_preflight_fragments = []
_all_controller_chart_flags = []
_all_spire_chart_flags = []
_all_spire_resource_deps = []

def _provider_controller_field(provider_name, result, name, default=None):
    if hasattr(result, "controller_" + name):
        return getattr(result, "controller_" + name)
    if hasattr(result, "cwe_" + name):
        warn("Provider '%s' returns cwe_%s, which is deprecated; rename it to controller_%s." % (provider_name, name, name))
        return getattr(result, "cwe_" + name)
    if default == None:
        fail("Provider '%s' register() must return controller_%s." % (provider_name, name))
    return default

for _entry in _provider_entries:
    if type(_entry) == "string":
        _provider_name = _entry
        _provider_dir = _builtin_provider_dirs.get(_provider_name, "")
        if not _provider_dir:
            fail("Unknown built-in provider '%s'. Use a dict entry for external providers." % _provider_name)
    elif type(_entry) == "dict":
        _provider_name = _entry.keys()[0]
        _provider_dir = _entry[_provider_name]
        # ctx.provider_dir is contracted to be absolute: provider build scripts
        # cd into it and then resolve sibling paths, which breaks if the value
        # stays relative. Relative entries are resolved from config.main_dir.
        if not _provider_dir.startswith("/"):
            _provider_dir = os.path.abspath(os.path.join(config.main_dir, _provider_dir))
    else:
        fail("Invalid provider entry: %s" % _entry)

    _tiltfile_path = os.path.join(_provider_dir, "Tiltfile")
    if not os.path.exists(_tiltfile_path):
        fail("Provider '%s' Tiltfile not found at %s." % (_provider_name, _tiltfile_path))
    _symbols = load_dynamic(_tiltfile_path)
    _result = _symbols["register"](struct(
        main_dir     = config.main_dir,
        cfg          = cfg,
        tilt_env     = _tilt_env,
        provider_names = _provider_names,
        kind_host_ip = _kind_host_ip,
        kind_cluster_name = KIND_CLUSTER_NAME_VALUE,
        spire_trust_domain = SPIRE_TRUST_DOMAIN,
        site_controller_vip = _kind_site_controller_vip,
        provider_dir = _provider_dir,
    ))
    _all_controller_resource_deps += _provider_controller_field(_provider_name, _result, "resource_deps")
    _all_controller_env_overrides.update(_provider_controller_field(_provider_name, _result, "env_overrides"))
    _all_controller_chart_flags += _provider_controller_field(_provider_name, _result, "chart_flags", [])
    _all_spire_chart_flags += getattr(_result, "spire_chart_flags", [])
    _all_spire_resource_deps += getattr(_result, "spire_resource_deps", [])
    if getattr(_result, "preflight_script", ""):
        _all_preflight_fragments.append(_result.preflight_script)

# ---------------------------------------------------------------------------
# Local environment / required credentials
# ---------------------------------------------------------------------------
#
# Parsed before provider loading so external providers can consume .env.tilt
# through ctx.tilt_env.
_tilt_env.update(_all_controller_env_overrides)

# Credentials with no defaults anywhere in the repo. The developer supplies each
# one via .env.tilt or the shell environment; `tilt up` fails fast rather than
# standing the stack up on placeholder credentials.
_required_cred_names = [
    "DGXC_TENANT_USER",
    "DGXC_TENANT_PASSWORD",
    "CNPG_SUPERUSER_PASSWORD",
    "CNPG_CLOUD_PASSWORD",
    "CNPG_TEMPORAL_PASSWORD",
]
_required_creds = {}
for _name in _required_cred_names:
    _required_creds[_name] = os.getenv(_name, _tilt_env.get(_name, "")).strip()
_missing_creds = [_name for _name in _required_cred_names if _required_creds[_name] == ""]
if _missing_creds:
    fail("Missing required credential(s): %s. Set them in .env.tilt or export them before `tilt up` — there are no defaults (see .env.tilt.example)." % ", ".join(_missing_creds))

# CNPG_SUPERUSER_PASSWORD is the single source of truth for the local postgres
# superuser: it provisions the bitnami postgres chart, authenticates temporal
# against it, and is what the controller substitutes into DB_CONNECTION_STRING at startup
# (config.EffectiveDBConnectionString).
_postgres_superuser_password = _required_creds["CNPG_SUPERUSER_PASSWORD"]

# ---------------------------------------------------------------------------
# Preflight checks
# ---------------------------------------------------------------------------
#
# Note: The label and button number prefix e.g. "1-my-button" are hacks to control the order of the resources and buttons in the Tilt UI.
#

_preflight_script = """
      set -euo pipefail
      kubectl cluster-info >/dev/null 2>&1 || {
        echo "No reachable management cluster. Run 'make colima-up' and 'make capd-up' (or 'make capi-core-up') first." >&2
        exit 1
      }
"""
for _fragment in _all_preflight_fragments:
    _preflight_script += _fragment
_preflight_script += """
      current_context="$(kubectl config current-context)"
      kind_cluster_name="${KIND_CLUSTER_NAME:-}"
      if [ -z "${kind_cluster_name}" ]; then
        case "${current_context}" in
          kind-*)
            ;;
          *)
            echo "KIND_CLUSTER_NAME is not set and current context '${current_context}' is not a kind context." >&2
            exit 1
            ;;
        esac
      fi
      command -v helm >/dev/null || {
        echo "helm is required in PATH" >&2
        exit 1
      }
      if helm status cwe -n cloud-workflow-engine >/dev/null 2>&1; then
        echo "This cluster runs the controller as Helm release cwe in namespace cloud-workflow-engine. Tilt now installs it as nke-controller in nke-controller and cannot take over the old install. Recreate the cluster: make kind-down, then make capd-up." >&2
        exit 1
      fi
"""
if not CONTROLLER_IMAGE:
    _preflight_script += """
      command -v docker >/dev/null || {
        echo "docker is required in PATH" >&2
        exit 1
      }
      command -v go >/dev/null || {
        echo "go is required in PATH (used for GOARCH detection)" >&2
        exit 1
      }
"""
_preflight_script += """
      command -v kind >/dev/null || {
        echo "kind is required in PATH" >&2
        exit 1
      }
      echo "Management cluster and local tooling are ready"
"""

local_resource(
    "check-management-cluster",
    labels=["0-preflight"],
    cmd=["bash", "-c", _preflight_script],
    deps=[],
)

# ---------------------------------------------------------------------------
# Infrastructure: PostgreSQL, Temporal, SPIRE
# ---------------------------------------------------------------------------

# Pull the postgres chart directly from the Bitnami OCI registry instead of
# adding the classic HTTP repo. `helm repo add bitnami` downloads the full
# index.yaml (tens of MB), which times out on slow networks; OCI fetches only
# this one chart version.
helm_resource(
    "postgres",
    "oci://registry-1.docker.io/bitnamicharts/postgresql",
    labels=["1-infra"],
    release_name="postgres",
    namespace=POSTGRES_NAMESPACE,
    deps=["deploy/helm-values/postgres.yaml"],
    flags=[
      "--create-namespace",
      "--values", "deploy/helm-values/postgres.yaml",
      "--set-string", "auth.password=%s" % _postgres_superuser_password,
      "--version", CHART_VERSION_POSTGRESQL,
      "--wait",
      "--timeout", "10m",
    ],
    resource_deps=["check-management-cluster"],
    port_forwards=[5432],
)

# Pull the chart with retries and install from the archive: the repo index
# points at a GitHub release asset, and helm_repo cannot retry a 500 on it.
TEMPORAL_CHART_DIR = ".local/charts"
TEMPORAL_CHART_ARCHIVE = "%s/temporal-%s.tgz" % (TEMPORAL_CHART_DIR, CHART_VERSION_TEMPORAL)

local_resource(
    "temporal-chart",
    cmd=["bash", "-c", """
      set -euo pipefail
      mkdir -p "%s"
      for attempt in 1 2 3 4 5; do
        if helm pull temporal --repo https://go.temporal.io/helm-charts --version "%s" --destination "%s"; then
          exit 0
        fi
        echo "helm pull temporal %s failed (attempt ${attempt}/5), retrying in $((attempt * 10))s" >&2
        sleep $((attempt * 10))
      done
      exit 1
    """ % (TEMPORAL_CHART_DIR, CHART_VERSION_TEMPORAL, TEMPORAL_CHART_DIR, CHART_VERSION_TEMPORAL)],
    labels=["1-infra"],
    allow_parallel=True,
)

helm_resource(
    "temporal",
    TEMPORAL_CHART_ARCHIVE,
    labels=["1-infra"],
    release_name="temporal",
    namespace=TEMPORAL_NAMESPACE,
    deps=["deploy/helm-values/temporal.yaml"],
    flags=[
      "--create-namespace",
      "--values", "deploy/helm-values/temporal.yaml",
      "--set-string", "server.config.persistence.default.sql.password=%s" % _postgres_superuser_password,
      "--set-string", "server.config.persistence.visibility.sql.password=%s" % _postgres_superuser_password,
      "--version", CHART_VERSION_TEMPORAL,
      "--wait",
      "--timeout", "15m",
    ],
    resource_deps=["check-management-cluster", "temporal-chart", "postgres"],
    links=[
      ui_link(CONTROLLER_TEMPORAL_UI_PORT, "", "Temporal UI"),
    ],
)

local_resource(
    "port-forward-temporal-ui",
    labels=["1-infra"],
    serve_cmd="while true; do kubectl -n " + TEMPORAL_NAMESPACE + " port-forward svc/temporal-web " + CONTROLLER_TEMPORAL_UI_PORT + ":8080 || true; sleep 2; done",
    resource_deps=["temporal"],
    readiness_probe=probe(exec=exec_action(["nc", "-z", "localhost", CONTROLLER_TEMPORAL_UI_PORT]), period_secs=5, failure_threshold=2),
    allow_parallel=True,
)

local_resource(
    "port-forward-temporal-frontend",
    labels=["1-infra"],
    serve_cmd="while true; do kubectl -n " + TEMPORAL_NAMESPACE + " port-forward svc/temporal-frontend 7233:7233 || true; sleep 2; done",
    resource_deps=["temporal"],
    readiness_probe=probe(exec=exec_action(["nc", "-z", "localhost", "7233"]), period_secs=5, failure_threshold=2),
    allow_parallel=True,
)

helm_repo(
    "spiffe-hardened",
    "https://spiffe.github.io/helm-charts-hardened/",
    labels=["1-infra"],
    resource_name="spiffe-hardened-repo",
)

# Local clone of the upstream spiffe-hardened/spire chart, pinned to a commit.
# It exposes `global.spire.jwtIssuer` to the OIDC discovery provider — without
# it the provider derives `iss` from the request's Host header and we end up
# advertising `https://<ip>:30443` instead of the logical site-controller URL.
#
# The jwtIssuer support landed upstream in
# https://github.com/spiffe/helm-charts-hardened/pull/829, but no release has
# been cut yet. Rather than track the moving `main` branch (which could break
# us on any upstream push), we pin an exact commit on main. Bump
# SPIRE_CHART_REPO_COMMIT deliberately after re-testing; switch back to the
# published Helm repo (`chart="spiffe-hardened/spire"`, pinned version) once a
# release with the fix ships.
#
# Why a local clone and not a git URL via the helm-git plugin: the chart has
# sibling `file://../spire-lib` dependencies that require the whole
# helm-charts-hardened repo on disk during `helm dep build`. helm-git's
# sparse checkout strips that.
SPIRE_CHART_REPO_URL = "https://github.com/spiffe/helm-charts-hardened.git"
# Pinned commit on main (spire chart 0.29.0). Bump only after re-testing.
SPIRE_CHART_REPO_COMMIT = "585203462b6bc7aa06d67b3a153bfff7ff287173"
_spire_chart_dir = os.path.join(config.main_dir, ".local/helm-charts/spire-hardened-upstream")

local_resource(
    "spire-chart-upstream",
    labels=["1-infra"],
    cmd=["bash", "-c", """
      set -euo pipefail
      target=%s
      url=%s
      commit=%s
      # Fetch the pinned commit by SHA at depth 1 (GitHub allows want-by-SHA),
      # then detach onto it. Works for both a fresh dir and an existing clone,
      # and never depends on a branch tip that can move under us.
      if [ ! -d "${target}/.git" ]; then
        rm -rf "${target}"
        mkdir -p "${target}"
        git -C "${target}" init -q
        git -C "${target}" remote add origin "${url}"
      else
        git -C "${target}" remote set-url origin "${url}"
      fi
      git -C "${target}" fetch --depth=1 origin "${commit}"
      git -C "${target}" checkout -q --detach "${commit}"
      # Materialise the chart's file://../spire-lib sibling and other deps
      # into charts/spire/charts/ — required for `helm install` to find them.
      helm dependency build "${target}/charts/spire" >/dev/null
    """ % (_spire_chart_dir, SPIRE_CHART_REPO_URL, SPIRE_CHART_REPO_COMMIT)],
    resource_deps=["check-management-cluster"],
)

helm_resource(
    "spire-crds",
    labels=["1-infra"],
    chart="spiffe-hardened/spire-crds",
    release_name="spire-crds",
    namespace=SPIRE_NAMESPACE,
    flags=[
      "--create-namespace",
      "--version", CHART_VERSION_SPIRE_CRDS,
      "--wait",
      "--timeout", "10m",
    ],
    pod_readiness="ignore",
    resource_deps=["check-management-cluster", "spiffe-hardened-repo"],
)



_cert_manager_state = detect_cert_manager()

if _cert_manager_state == "external":
    print("cert-manager: detected out-of-band install (not helm-managed) — skipping helm install")
    local_resource(
        "cert-manager",
        labels=["1-infra"],
        cmd=["bash", "-c", """
          set -euo pipefail
          echo "cert-manager is installed out-of-band (not via helm); skipping helm install."
          kubectl -n %s rollout status deploy/cert-manager --timeout=180s
          kubectl -n %s rollout status deploy/cert-manager-webhook --timeout=180s
          kubectl -n %s rollout status deploy/cert-manager-cainjector --timeout=180s
        """ % (CERT_MANAGER_NAMESPACE, CERT_MANAGER_NAMESPACE, CERT_MANAGER_NAMESPACE)],
        resource_deps=["check-management-cluster"],
    )
else:
    helm_repo(
        "jetstack",
        "https://charts.jetstack.io",
        labels=["1-infra"],
        resource_name="jetstack-repo",
    )

    helm_resource(
        "cert-manager",
        "jetstack/cert-manager",
        labels=["1-infra"],
        release_name="cert-manager",
        namespace=CERT_MANAGER_NAMESPACE,
        deps=["deploy/helm-values/cert-manager.yaml"],
        flags=[
          "--create-namespace",
          "--values", "deploy/helm-values/cert-manager.yaml",
          "--version", CHART_VERSION_CERT_MANAGER,
          "--wait",
          "--timeout", "10m",
        ],
        resource_deps=["check-management-cluster", "jetstack-repo"],
    )

# SANs for the OIDC leaf serving cert. _kind_site_controller_vip is usually a
# container IP (Linux's kind bridge gateway, or macOS's auto-detected
# management node IP), which goes into ipAddresses; the host.docker.internal
# fallback is a hostname and must be a dnsName instead. The provider matches
# against the Host header / SNI, so every reachable identity must be present.
def _looks_like_ipv4(value):
    _parts = value.split(".")
    if len(_parts) != 4:
        return False
    for _part in _parts:
        if not _part.isdigit() or int(_part) > 255:
            return False
    return True

_oidc_ip_sans = ["127.0.0.1", _kind_host_ip]
_oidc_dns_sans = []
# _kind_site_controller_vip may be an override, an auto-detected container
# IP, or the host.docker.internal hostname fallback; classify generically by
# shape rather than re-deriving which source it came from.
if _looks_like_ipv4(_kind_site_controller_vip):
    if _kind_site_controller_vip not in _oidc_ip_sans:
        _oidc_ip_sans.append(_kind_site_controller_vip)
else:
    _oidc_dns_sans.append(_kind_site_controller_vip)

_spire_set_string_flags = []
for _i, _ip in enumerate(_oidc_ip_sans):
    _spire_set_string_flags += [
        "--set-string",
        "spiffe-oidc-discovery-provider.tls.certManager.certificate.ipAddresses[%d]=%s" % (_i, _ip),
    ]
# Append the dynamic DNS SANs after the static dnsNames in spire.yaml
# (indices 0..1: nke.site-controller.internal, localhost).
_STATIC_DNS_NAME_COUNT = 2
for _i, _name in enumerate(_oidc_dns_sans):
    _spire_set_string_flags += [
        "--set-string",
        "spiffe-oidc-discovery-provider.tls.certManager.certificate.dnsNames[%d]=%s" % (_STATIC_DNS_NAME_COUNT + _i, _name),
    ]

# Dynamic entries for the provider's accepted-domains list. kube-apiserver
# fetches the discovery URL by IP or hostname, and the provider rejects any
# request whose Host header isn't on this list. Static entries
# (nke.site-controller.internal, localhost, 127.0.0.1) live in spire.yaml.
_oidc_dynamic_domains = [_kind_host_ip, _kind_site_controller_vip]

# Append dynamic domains to the static list defined in spire.yaml. The static
# list has indices 0..2; start the override list at index 3.
_STATIC_ADDITIONAL_DOMAIN_COUNT = 3
for _i, _domain in enumerate(_oidc_dynamic_domains):
    _spire_set_string_flags += [
        "--set-string",
        "spiffe-oidc-discovery-provider.config.additionalDomains[%d]=%s" % (
            _STATIC_ADDITIONAL_DOMAIN_COUNT + _i, _domain),
    ]

helm_resource(
    "spire-server",
    labels=["1-infra"],
    chart=os.path.join(_spire_chart_dir, "charts/spire"),
    release_name="spire",
    namespace=SPIRE_NAMESPACE,
    deps=["deploy/helm-values/spire.yaml"],
    flags=[
      "--create-namespace",
      "--values", "deploy/helm-values/spire.yaml",
      "--set-string", "global.spire.clusterName=%s" % KIND_CLUSTER_NAME_VALUE,
      "--set-string", "global.spire.trustDomain=%s" % SPIRE_TRUST_DOMAIN,
      "--set-string", "global.spire.jwtIssuer=%s" % NKE_OIDC_ISSUER_URL,
      "--set-string", "spire-server.adminIDs[0]=spiffe://%s%s" % (SPIRE_TRUST_DOMAIN, SPIRE_CONTROLLER_ADMIN_PATH),
      "--set-string", "spire-server.nodeAttestor.tpmDirect.checksum=%s" % SPIRE_TPM_ATTESTOR_SERVER_CHECKSUM,
      "--set-string", "spiffe-oidc-discovery-provider.config.jwksUri=https://%s:30443/keys" % _kind_site_controller_vip,
    ] + _spire_set_string_flags + _all_spire_chart_flags + [
      "--wait",
      "--timeout", "15m",
    ],
    # spire-chart-upstream: chart source must exist before helm install.
    resource_deps=["spire-chart-upstream", "spire-crds", "cert-manager", "oidc-upstream-ca-issuer", "oidc-upstream-ca-ready"] + _all_spire_resource_deps,
)

k8s_yaml([
    "deploy/k8s/oidc-upstream-ca.yaml",
    # Separate because the deploy paths apply it only on a first install; Tilt
    # has no such gate, so a long-lived dev cluster re-issues the CA when this
    # Certificate's spec changes. Delete the oidc-provider-upstream-ca Secret
    # if anything in the dev loop has embedded the old CA.
    "deploy/k8s/oidc-upstream-ca-certificate.yaml",
    "deploy/k8s/spire-server-nodeport.yaml",
    "deploy/k8s/spire-oidc-provider-nodeport.yaml",
    "deploy/k8s/spire-tpm-pubhashes-configmap.yaml",
    "deploy/k8s/nvke-auth-dev.yaml",
    "deploy/k8s/nvke-spire-client.yaml",
])

_nke_service_spiffe_id_yaml = str(read_file("deploy/k8s/spire-nvke-services-spiffe-id.yaml"))
if DSX_IDENTITY_EXCHANGE_ENABLED:
    _nke_service_spiffe_id_yaml = _nke_service_spiffe_id_yaml.replace(
        "spiffe://{{.TrustDomain}}/nvke-service/{{.PodSpec.ServiceAccountName}}",
        "spiffe://{{.TrustDomain}}/tenant/nke/service/{{.PodSpec.ServiceAccountName}}/bm/cwe",
    )
k8s_yaml(blob(_nke_service_spiffe_id_yaml))

k8s_resource(
    new_name="oidc-ca-bootstrap",
    labels=["1-infra"],
    objects=[
        "oidc-ca-bootstrap:issuer",
        "oidc-provider-upstream-ca:certificate",
    ],
    resource_deps=["cert-manager"],
    pod_readiness="ignore",
)

k8s_resource(
    new_name="oidc-upstream-ca-issuer",
    labels=["1-infra"],
    objects=["nvke-oidc-upstream-ca:issuer"],
    resource_deps=["oidc-ca-bootstrap"],
    pod_readiness="ignore",
)

k8s_resource(
    new_name="spire-oidc-provider-nodeport",
    labels=["1-infra"],
    objects=["spire-oidc-provider-np:service:spire-server"],
    resource_deps=["spire-server"],
    pod_readiness="ignore",
)

# Gate that flips to ready once cert-manager has issued the leaf serving
# cert for the OIDC discovery provider. Anything that consumes the OIDC
# cert (including the ConfigMap renderer below) depends on this
# resource so it never runs while the Secret is missing.
local_resource(
    "oidc-upstream-ca-ready",
    labels=["1-infra"],
    cmd=["bash", "-c",
         "kubectl -n " + SPIRE_NAMESPACE + " wait --for=condition=Ready " +
         "certificate/oidc-provider-upstream-ca --timeout=180s"],
    resource_deps=["oidc-ca-bootstrap"],
)


k8s_yaml("deploy/k8s/nvke-system-namespace.yaml")

k8s_resource(
    new_name="nvke-system-namespace",
    labels=["1-infra"],
    objects=["nvke-system:namespace"],
    resource_deps=["check-management-cluster"],
    pod_readiness="ignore",
)

# NVKE API authentication scaffolding: the client namespaces and service accounts
# the demo mints tokens for, and the token-minter RBAC. The configuration that
# admits them is chart values, in hack/tilt-controller-api-auth-values.yaml.
k8s_resource(
    new_name="nvke-auth-dev",
    labels=["1-infra"],
    objects=[
        "nke-controller:namespace",
        "nke-clients:namespace",
        "nke-outsiders:namespace",
        "nke-client:serviceaccount:nke-clients",
        "nke-outsider:serviceaccount:nke-outsiders",
        "nke-e2e:serviceaccount:nke-clients",
        "nke-client-token-minter:role:nke-clients",
        "nke-client-token-minter:rolebinding:nke-clients",
        "nke-outsider-token-minter:role:nke-outsiders",
        "nke-outsider-token-minter:rolebinding:nke-outsiders",
    ],
    resource_deps=["check-management-cluster"],
    pod_readiness="ignore",
)

# The SPIRE-attested client identity for the authentication specs: a namespace, a
# service account, the ClusterSPIFFEID that gets it an SVID, and the probe script
# test/e2e/authn_spire_test.go runs in a one-shot pod. Depends on spire-server
# for the ClusterSPIFFEID CRD and controller manager. Tilt does not create the
# probe pod; the spec does.
k8s_resource(
    new_name="nke-spire-client",
    labels=["1-infra"],
    objects=[
        "nke-spire-clients:namespace",
        "nke-spire-client:serviceaccount:nke-spire-clients",
        "nke-spire-client:clusterspiffeid",
        "nke-spire-probe:configmap:nke-spire-clients",
    ],
    resource_deps=["spire-server"],
    pod_readiness="ignore",
)

k8s_resource(
    new_name="spire-server-nodeport",
    labels=["1-infra"],
    objects=["spire-server-np:service:spire-server"],
    resource_deps=["spire-server"],
    pod_readiness="ignore",
)

cmd_button(
    "1-show-spire-entries",
    argv=["bash", "-c", """
      set -euo pipefail
      kubectl exec -n """ + SPIRE_NAMESPACE + """ spire-server-0 -c spire-server -- bin/spire-server entry show
    """],
    resource="spire-server",
    icon_name="visibility",
    text="Show SPIRE entries",
)

cmd_button(
    "2-agent-list",
    argv=["bash", "-c", """
    set -euo pipefail
    kubectl exec -n """ + SPIRE_NAMESPACE + """ spire-server-0 -c spire-server -- bin/spire-server agent list
    """],
    resource="spire-server",
    icon_name="visibility",
    text="SPIRE agent list",
)

local_resource(
    "port-forward-spire-server",
    labels=["1-infra"],
    serve_cmd="while true; do kubectl -n " + SPIRE_NAMESPACE + " port-forward svc/spire-server-np 30440:443 || true; sleep 2; done",
    resource_deps=["spire-server"],
    readiness_probe=probe(exec=exec_action(["nc", "-z", "localhost", "30440"]), period_secs=5, failure_threshold=2),
    allow_parallel=True,
)

# Bind the SPIRE server and OIDC discovery NodePorts on the kind bridge
# gateway IP. NodePort services bind on each kind node's container IP, not on
# the gateway, so tenants dialing the gateway IP would otherwise hit nothing.
# Linux only: on macOS the kind gateway IP doesn't exist on the host (it
# lives inside the Docker VM) and `kubectl port-forward --address` would
# fail to bind there anyway. It's also unnecessary on macOS: tenants dial
# the management node's own container IP directly (see
# _kind_site_controller_vip above), which already carries the NodePort. A
# configured site_controller_vip (CI) points tenants directly at a Kind node
# too, so the gateway forwards are unnecessary in that mode as well.
if not _on_mac and not SITE_CONTROLLER_VIP_OVERRIDE:
    local_resource(
        "port-forward-spire-server-kind-gw",
        labels=["1-infra"],
        serve_cmd="while true; do kubectl -n %s port-forward --address %s svc/spire-server-np 30440:443 || true; sleep 2; done" % (SPIRE_NAMESPACE, _kind_host_ip),
        resource_deps=["spire-server"],
        readiness_probe=probe(exec=exec_action(["nc", "-z", _kind_host_ip, "30440"]), period_secs=5, failure_threshold=2),
        allow_parallel=True,
    )

    local_resource(
        "port-forward-spire-oidc-kind-gw",
        labels=["1-infra"],
        serve_cmd="while true; do kubectl -n %s port-forward --address %s svc/spire-oidc-provider-np 30443:443 || true; sleep 2; done" % (SPIRE_NAMESPACE, _kind_host_ip),
        resource_deps=["spire-server"],
        readiness_probe=probe(exec=exec_action(["nc", "-z", _kind_host_ip, "30443"]), period_secs=5, failure_threshold=2),
        allow_parallel=True,
    )

k8s_resource(
    new_name="spire-nvke-services-spiffe-id",
    labels=["1-infra"],
    objects=["nvke-service:clusterspiffeid"],
    resource_deps=["spire-server"],
    pod_readiness="ignore",
)

k8s_resource(
    new_name="spire-tpm-pubhashes",
    labels=["1-infra"],
    objects=["tpm-pubhashes:configmap:spire-server"],
    resource_deps=["spire-server"],
    pod_readiness="ignore",
)

# ---------------------------------------------------------------------------
# Controller
# ---------------------------------------------------------------------------

_controller_tenant_access_enabled = os.getenv(
    "TENANT_ACCESS_ENABLED", _tilt_env.get("TENANT_ACCESS_ENABLED", "true")) == "true"
_controller_oidc_enabled = os.getenv(
    "NKE_OIDC_AUTH_ENABLED", _tilt_env.get("NKE_OIDC_AUTH_ENABLED", "true")) == "true"

# NVKE API authentication. Enforcing by default now that the suite mints its own
# token: internal/authtoken discovers the audience from apiAuth in
# nvke-controller-config and nvke.NewClient presents it on every call, so the
# ordinary specs exercise the shipping authentication path rather than
# bypassing it.
#
# The configuration is hack/tilt-controller-api-auth-values.yaml, which the
# chart renders into apiAuth in nvke-controller-config. To drive it by hand, use
# hack/nvke-token.sh for the bearer token.
#
#   NKE_AUTH_ENABLED=false tilt up     -> apiAuth.enabled false, authn off
#   NKE_PERMISSIVE_MODE=true tilt up   -> evaluate and count, never reject
#
_controller_auth_enabled = os.getenv(
    "NKE_AUTH_ENABLED", _tilt_env.get("NKE_AUTH_ENABLED", "true")) == "true"
_controller_permissive_mode = os.getenv(
    "NKE_PERMISSIVE_MODE", _tilt_env.get("NKE_PERMISSIVE_MODE", "false")) == "true"

_controller_chart_extra_env_names = [
    "NODE_PROVISIONING_TIMEOUT",
    "NODE_REBOOT_POLLING_INTERVAL",
    "LOG_LEVEL",
    "LOCAL_DEV_FORCE_DOCKER_MACHINE_BOOTSTRAP",
    "SPIRE_SERVER_API_ADDRESS",
    "SSL_CERT_FILE",
]
_controller_chart_extra_env = []
for _name in _controller_chart_extra_env_names:
    if _name in _tilt_env:
        _controller_chart_extra_env.append({"name": _name, "value": _tilt_env[_name]})
# NODE_REBOOT_SOFT_REBOOT_ENABLED is honored from the process environment first (with the
# .env.tilt value as a fallback) so CI can disable soft reboot without touching the
# production default.
_controller_node_reboot_soft_reboot_enabled = os.getenv(
    "NODE_REBOOT_SOFT_REBOOT_ENABLED",
    _tilt_env.get("NODE_REBOOT_SOFT_REBOOT_ENABLED", ""))
if _controller_node_reboot_soft_reboot_enabled != "":
    _controller_chart_extra_env.append({
        "name": "NODE_REBOOT_SOFT_REBOOT_ENABLED",
        "value": _controller_node_reboot_soft_reboot_enabled,
    })
for _name in _required_cred_names:
    _controller_chart_extra_env.append({"name": _name, "value": _required_creds[_name]})
# API authentication comes from the apiAuth values below, not from this env list.

# Local node images include the CNI manifests package, so install CNI after
# kubeadm init without a bundle server. E2E lanes can still select the legacy
# in-init path explicitly through the process environment or .env.tilt.
_controller_install_cni_after_init = os.getenv(
    "INSTALL_CNI_AFTER_INIT",
    _tilt_env.get("INSTALL_CNI_AFTER_INIT", "true"))

# Keep the chart default when this is unset. E2E sets it explicitly so the
# deployment-wide method matches the attestor baked into its CAPD node image.
_controller_spire_attestation_method = os.getenv(
    "NODE_AGENT_SPIRE_ATTESTATION_METHOD",
    _tilt_env.get("NODE_AGENT_SPIRE_ATTESTATION_METHOD", ""))

# The chart defaults controllers.nico.enabled to true. Only the nico and
# nico-vm providers install the NicoMachine CRD, and the controller exits
# when the flag is true without that CRD.
_nico_controllers_enabled = "nico" in _provider_names or "nico-vm" in _provider_names

_controller_chart_flags = [
    "--create-namespace",
    "--set", "cni.installAfterInit=%s" % ("true" if _controller_install_cni_after_init == "true" else "false"),
    "--values", "hack/tilt-controller-chart-values.yaml",
    "--set-string", "appDb.postgresPassword=%s" % _postgres_superuser_password,
    "--set", "apiAuth.enabled=%s" % ("true" if _controller_auth_enabled else "false"),
    "--set", "apiAuth.permissive=%s" % ("true" if _controller_permissive_mode else "false"),
] + (["--values", "hack/tilt-controller-api-auth-values.yaml"] if _controller_auth_enabled else []) + [
    "--set", "capi.rbac.create=true",
    # machine-engine-crds installs them, so Helm must not try to own them.
    "--set", "releaseCRDs.install=false",
    "--set", "tenantAccess.enabled=%s" % ("true" if _controller_tenant_access_enabled else "false"),
    "--set", "controllers.nico.enabled=%s" % ("true" if _nico_controllers_enabled else "false"),
    "--set", "nvkeOIDCAuth.enabled=%s" % ("true" if _controller_oidc_enabled else "false"),
    "--set-string", "nvkeOIDCAuth.issuerURL=%s" % NKE_OIDC_ISSUER_URL,
    "--set-string", "nvkeOIDCAuth.discoveryURL=https://%s:30443/.well-known/openid-configuration" % _kind_site_controller_vip,
    "--set-string", "nvkeOIDCAuth.caBundleSecret.namespace=%s" % SPIRE_NAMESPACE,
    "--set-string", "nvkeOIDCAuth.caBundleSecret.name=oidc-provider-upstream-ca",
    "--set-string", "nvkeOIDCAuth.caBundleSecret.key=ca.crt",
    "--set-string", "spiffe.trustDomain=%s" % SPIRE_TRUST_DOMAIN,
    "--set-string", "spiffe.spire.serverAddress=%s" % _tilt_env.get("SPIRE_SERVER_ADDRESS", _kind_site_controller_vip),
    # helm splits --set-string on commas; escape the one inside the value.
    "--set-string", "supportedInfraProviders=%s" % "\\,".join(_supported_infra_providers),
    "--set-json", "env=%s" % encode_json(_controller_chart_extra_env),
    "--wait",
    "--timeout", "10m",
] + _all_controller_chart_flags

if _controller_spire_attestation_method != "":
    _controller_chart_flags += [
        "--set-string", "nodeAgent.spireAttestationMethod=%s" % _controller_spire_attestation_method,
    ]

if CONTROLLER_IMAGE:
    _image_parts = CONTROLLER_IMAGE.split(":")
    if len(_image_parts) > 1:
        _controller_chart_flags += [
            "--set-string", "image.repository=%s" % ":".join(_image_parts[:-1]),
            "--set-string", "image.tag=%s" % _image_parts[-1],
        ]
    else:
        _controller_chart_flags += [
            "--set-string", "image.repository=%s" % CONTROLLER_IMAGE,
            "--set-string", "image.tag=latest",
        ]

_controller_local_debug_active = os.path.exists(CONTROLLER_LOCAL_DEBUG_MARKER)
_controller_tilt_goarch = local_arch()
_controller_resource_deps = ["postgres", "temporal", "spire-nvke-services-spiffe-id", "spire-tpm-pubhashes", "nvke-system-namespace", "nvke-auth-dev", "machine-engine-releases"] + _all_controller_resource_deps
if _controller_oidc_enabled:
    _controller_resource_deps += ["spire-oidc-provider-nodeport", "oidc-upstream-ca-ready"]

_controller_image_deps = []
_controller_image_keys = []
if not CONTROLLER_IMAGE and not _controller_local_debug_active:
    _controller_image_deps = ["docker.local/cwe:tilt"]
    _controller_image_keys = [("image.repository", "image.tag")]
    _controller_resource_deps = ["nvke-controller-compile"] + _controller_resource_deps
elif _controller_local_debug_active:
    print("Skipping in-cluster controller image build while local controller debug mode is active")

_controller_compile_script = """
      set -euo pipefail
      mkdir -p bin
      CGO_ENABLED=0 GOOS=linux GOARCH="%s" make build
""" % _controller_tilt_goarch

# Default to the sanitized fixture that ships in this repository. It is
# Apache-2.0, builds from a Docker Hub base, and is what CI already uses
# (hack/ci/backend-e2e.sh). Defaulting to the nke-site-deploy sibling instead meant
# a plain `tilt up` failed for anyone without that checkout, even though a
# working profiles tree was one directory away.
#
# Point NVKE_CONTROLLER_PROFILES_DIR at nke-site-deploy/cwe-profiles/profiles to exercise
# the fleet profiles.
# NKE_CONTROLLER_PROFILES_DIR, NKE_CONTROLLER_PROFILES_PRELOADED, CWE_PROFILES_DIR and CWE_PROFILES_PRELOADED are deprecated aliases for the NVKE_CONTROLLER_ names; #1399 removes them.
_controller_profiles_dir = (os.getenv("NVKE_CONTROLLER_PROFILES_DIR", "") or os.getenv("NKE_CONTROLLER_PROFILES_DIR", "") or os.getenv("CWE_PROFILES_DIR", "") or _tilt_env.get("NVKE_CONTROLLER_PROFILES_DIR", "") or _tilt_env.get("NKE_CONTROLLER_PROFILES_DIR", "") or _tilt_env.get("CWE_PROFILES_DIR", "")).strip()
if _controller_profiles_dir == "":
    _controller_profiles_dir = os.path.abspath(os.path.join(config.main_dir, "test", "fixtures", "profiles"))
elif not _controller_profiles_dir.startswith("/"):
    _controller_profiles_dir = os.path.abspath(os.path.join(config.main_dir, _controller_profiles_dir))
_controller_profiles_preloaded = (os.getenv("NVKE_CONTROLLER_PROFILES_PRELOADED", "") or os.getenv("NKE_CONTROLLER_PROFILES_PRELOADED", "") or os.getenv("CWE_PROFILES_PRELOADED", "")) == "true"
# Starlark's os.path has exists/join but not isdir.
if not _controller_profiles_preloaded and not _controller_profiles_dir:
    fail("NVKE_CONTROLLER_PROFILES_DIR must point to an external profiles directory")
if not _controller_profiles_preloaded and not os.path.exists(_controller_profiles_dir):
    fail("Controller profiles not found at %s. Set NVKE_CONTROLLER_PROFILES_DIR to a profiles tree; the in-repo fixture is controller/test/fixtures/profiles and the fleet profiles live in nke-site-deploy." % _controller_profiles_dir)

_controller_profiles_context = os.path.dirname(_controller_profiles_dir)
_controller_profiles_dockerfile = os.path.join(_controller_profiles_context, "Dockerfile")
_controller_profiles_runbooks_dir = os.path.join(_controller_profiles_context, "runbooks")

# Match hack/tilt-controller-chart-values.yaml: when profiles.image is on, skip baking
# profiles into the Tilt controller image and skip live_update sync into the read-only mount.
_controller_profiles_image_enabled = True

if _controller_profiles_image_enabled:
    if _controller_profiles_preloaded:
        print("Using preloaded docker.local/cwe-profiles:tilt image")
    else:
        _controller_image_deps = _controller_image_deps + ["docker.local/cwe-profiles:tilt"]
        _controller_image_keys = _controller_image_keys + [("profiles.image.repository", "profiles.image.tag")]
        if not os.path.exists(_controller_profiles_dockerfile):
            fail("Controller profiles Dockerfile not found at %s" % _controller_profiles_dockerfile)
        if not os.path.exists(_controller_profiles_runbooks_dir):
            fail("Controller profile runbooks not found at %s" % _controller_profiles_runbooks_dir)
        custom_build(
            ref="docker.local/cwe-profiles:tilt",
            command=[
                "bash", "-c",
                """
                set -euo pipefail
                if [ "$(uname -s)" = "Darwin" ] && [ -z "${DOCKER_HOST:-}" ]; then
                  export DOCKER_HOST="${COLIMA_DOCKER_HOST:-unix://${HOME}/.colima/default/docker.sock}"
                fi
                retry() { "$@" || { echo "docker build failed, retrying once in 15s" >&2; sleep 15; "$@"; }; }; retry docker build --platform linux/%s --tag "$EXPECTED_REF" -f "%s" "%s"
                """ % (_controller_tilt_goarch, _controller_profiles_dockerfile, _controller_profiles_context),
            ],
            deps=[_controller_profiles_dir, _controller_profiles_runbooks_dir, _controller_profiles_dockerfile],
        )

# docker build runs through a one-shot retry: the mirror can 404 a layer it just resolved.
_controller_build_script = """
      set -euo pipefail

      if [ "$(uname -s)" = "Darwin" ] && [ -z "${DOCKER_HOST:-}" ]; then
        export DOCKER_HOST="${COLIMA_DOCKER_HOST:-unix://${HOME}/.colima/default/docker.sock}"
      fi

      mkdir -p bin
      # nvke-controller-compile owns bin/controller. Compiling here too rewrote a file this
      # build watches, so every build queued the next one.
      [ -x bin/controller ] || CGO_ENABLED=0 GOOS=linux GOARCH="%s" make build
      tmp_dir="$(mktemp -d)"
      trap 'rm -rf "${tmp_dir}"' EXIT
      cp hack/Dockerfile.controller.tilt "${tmp_dir}/Dockerfile"
      mkdir -p "${tmp_dir}/bin"
      cp bin/controller "${tmp_dir}/bin/controller"
      retry() { "$@" || { echo "docker build failed, retrying once in 15s" >&2; sleep 15; "$@"; }; }; retry docker build --platform linux/%s --tag "$EXPECTED_REF" "${tmp_dir}"
""" % (_controller_tilt_goarch, _controller_tilt_goarch)

if not _controller_profiles_image_enabled:
    _controller_build_script = """
      set -euo pipefail

      if [ "$(uname -s)" = "Darwin" ] && [ -z "${DOCKER_HOST:-}" ]; then
        export DOCKER_HOST="${COLIMA_DOCKER_HOST:-unix://${HOME}/.colima/default/docker.sock}"
      fi

      mkdir -p bin
      # nvke-controller-compile owns bin/controller. Compiling here too rewrote a file this
      # build watches, so every build queued the next one.
      [ -x bin/controller ] || CGO_ENABLED=0 GOOS=linux GOARCH="%s" make build
      tmp_dir="$(mktemp -d)"
      trap 'rm -rf "${tmp_dir}"' EXIT
      cp hack/Dockerfile.controller.tilt "${tmp_dir}/Dockerfile"
      # Bake profiles into the image when profiles.image materialize is off.
      awk '1; /^RUN mkdir -p [/]profiles$/ {print "COPY ./profiles /profiles"}' \
        "${tmp_dir}/Dockerfile" > "${tmp_dir}/Dockerfile.new"
      mv "${tmp_dir}/Dockerfile.new" "${tmp_dir}/Dockerfile"
      mkdir -p "${tmp_dir}/bin"
      cp bin/controller "${tmp_dir}/bin/controller"
      mkdir -p "${tmp_dir}/profiles"
      cp -a "%s/." "${tmp_dir}/profiles/"
      retry() { "$@" || { echo "docker build failed, retrying once in 15s" >&2; sleep 15; "$@"; }; }; retry docker build --platform linux/%s --tag "$EXPECTED_REF" "${tmp_dir}"
""" % (_controller_tilt_goarch, _controller_profiles_dir, _controller_tilt_goarch)

if not CONTROLLER_IMAGE and not _controller_local_debug_active:
    local_resource(
        "nvke-controller-compile",
        cmd=["bash", "-c", _controller_compile_script],
        labels=["3-nvke-controller"],
        deps=[
          "cmd",
          "internal",
          "api",
          "Makefile",
          "Makefile.dev",
          "go.mod",
          "go.sum",
        ],
        ignore=[
          "**/__debug_bin*",
        ],
    )

# The chart's own CRD bundle, applied before the chart, which has its copy turned
# off with releaseCRDs.install=false: a local resource that waits for the chart to
# install them holds every unparallelizable build behind it, including the chart's.
local_resource(
    "machine-engine-crds",
    cmd=["bash", "-c", """
      set -euo pipefail
      kubectl apply --server-side --field-manager=tilt-release-crds \
        -f deploy/charts/controller/files/crds.yaml
      for crd in machineimages clusterreleases nodepoolreleases; do
        kubectl wait --for=condition=Established --timeout=120s "crd/${crd}.internal.nvke.nvidia.com"
      done
    """],
    labels=["3-nvke-controller"],
    deps=["deploy/charts/controller/files/crds.yaml"],
    resource_deps=["check-management-cluster"],
)

# Applies the releases the controller resolves every OS image from.
# NKE_CONTROLLER_RELEASES_DIR is a deprecated alias for NVKE_CONTROLLER_RELEASES_DIR; #1399 removes it.
_nke_release_dir = (os.getenv("NVKE_CONTROLLER_RELEASES_DIR", "") or os.getenv("NKE_CONTROLLER_RELEASES_DIR", "") or _tilt_env.get("NVKE_CONTROLLER_RELEASES_DIR", "") or _tilt_env.get("NKE_CONTROLLER_RELEASES_DIR", "")).strip()
if _nke_release_dir == "":
    _nke_release_dir = os.path.join(_controller_profiles_context, "releases")
elif not _nke_release_dir.startswith("/"):
    _nke_release_dir = os.path.abspath(os.path.join(config.main_dir, _nke_release_dir))

local_resource(
    "machine-engine-releases",
    cmd=["bash", "-c", """
      set -euo pipefail
      dir="%s"
      [ -d "${dir}" ] || { echo "releases not found at ${dir}; set NVKE_CONTROLLER_RELEASES_DIR to a directory of generated MachineImage, ClusterRelease and NodePoolRelease manifests" >&2; exit 1; }
      # MachineImage specs are immutable. After editing a profile, delete the
      # stale image (kubectl delete machineimage <name>) and apply again.
      kubectl apply --server-side --field-manager=tilt-releases -f "${dir}"
    """ % _nke_release_dir],
    labels=["3-nvke-controller"],
    deps=[_nke_release_dir],
    resource_deps=["machine-engine-crds"],
    allow_parallel=True,
)

helm_resource(
    "nvke-controller",
    chart="deploy/charts/controller",
    labels=["3-nvke-controller"],
    release_name="nke-controller",
    namespace=CONTROLLER_NAMESPACE,
    image_deps=_controller_image_deps,
    image_keys=_controller_image_keys,
    deps=[
      ".env.tilt",
      ".env.tilt.example",
      "hack/tilt-controller-chart-values.yaml",
      "hack/tilt-controller-api-auth-values.yaml",
      "deploy/charts/controller",
    ],
    flags=_controller_chart_flags,
    resource_deps=_controller_resource_deps,
    port_forwards=[CONTROLLER_HTTP_PORT + ":8080"],
    links=[
      ui_link(CONTROLLER_HTTP_PORT, "/api/docs", "Swagger Docs"),
      ui_link(CONTROLLER_HTTP_PORT, "/metrics", "Metrics"),
      ui_link(CONTROLLER_TEMPORAL_UI_PORT, "/namespaces/nke-controller/workflows", "Temporal UI"),
    ],
)

if not CONTROLLER_IMAGE and not _controller_local_debug_active:
    # When profiles.image is enabled, /profiles is an emptyDir filled by the
    # materialize initContainer (read-only on the app container). Do not
    # live_update sync into that mount.
    _controller_live_update = [
      fall_back_on(["hack/Dockerfile.controller.tilt", "go.mod", "go.sum", "Makefile", "Makefile.dev"]),
      sync("bin/controller", "/usr/local/bin/controller"),
    ]
    _controller_build_deps = [
      "bin",
      "hack/Dockerfile.controller.tilt",
      "Makefile",
      "Makefile.dev",
      "go.mod",
      "go.sum",
    ]
    if not _controller_profiles_image_enabled:
        _controller_live_update.insert(-1, sync(_controller_profiles_dir, "/profiles"))
        _controller_build_deps.append(_controller_profiles_dir)

    custom_build_with_restart(
        ref="docker.local/cwe:tilt",
        command=["bash", "-c", _controller_build_script],
        deps=_controller_build_deps,
        entrypoint="/usr/local/bin/controller",
        live_update=_controller_live_update,
        trigger=["bin/controller"],
        ignore=[
          "**/__debug_bin*",
        ],
    )

cmd_button(
    "2-create-sample-capd-cluster",
    argv=["bash", "-c", """
      set -euo pipefail
      API_URL="http://localhost:%s/api/clusters" \
      CLUSTER_NAME="${CLUSTER_NAME:-capd}" \
      KUBERNETES_VERSION="${KUBERNETES_VERSION:-1.34.2}" \
      CONTROL_PLANE_DESIRED_COUNT="${CONTROL_PLANE_DESIRED_COUNT:-3}" \
      WORKER_DESIRED_COUNT="${WORKER_DESIRED_COUNT:-1}" \
      ETCD_ENCRYPTED="${ETCD_ENCRYPTED:-false}" \
      ./hack/create-capd-cluster.sh
    """ % CONTROLLER_HTTP_PORT],
    resource="nvke-controller",
    icon_name="add_box",
    text="Create sample CAPD cluster",
    inputs=[
        text_input("CLUSTER_NAME", default="capd"),
        text_input("KUBERNETES_VERSION", default="1.34.2"),
        text_input("CONTROL_PLANE_DESIRED_COUNT", default="3"),
        text_input("WORKER_DESIRED_COUNT", default="1"),
        text_input("ETCD_ENCRYPTED", default="false"),
    ],
)

cmd_button(
    "3-restart-nvke-controller",
    argv=["bash", "-c", """
      set -euo pipefail
      kubectl -n """ + CONTROLLER_NAMESPACE + """ rollout restart deployment/nke-controller
      kubectl -n """ + CONTROLLER_NAMESPACE + """ rollout status deployment/nke-controller --timeout=180s
    """],
    resource="nvke-controller",
    icon_name="restart_alt",
    text="Restart controller",
)

cmd_button(
    "4-fetch-capd-kubeconfig",
    argv=["bash", "-c", """
      set -euo pipefail
      CLUSTER_NAME="${CLUSTER_NAME:-capd}"
      export DOCKER_HOST="${DOCKER_HOST:-unix://${HOME}/.colima/default/docker.sock}"
      ./hack/fetch-capd-kubeconfig.sh "${CLUSTER_NAME}"
    """],
    resource="nvke-controller",
    icon_name="download",
    text="Fetch CAPD workload kubeconfig",
    inputs=[
        text_input("CLUSTER_NAME", default="capd"),
    ],
)

include_user_tilt_files()
