# The dev loop. `make tilt` from the project root, or `cd ctrl && tilt up`.
# Works unedited; replace the two EXAMPLES and add yours in the marked sections.
# rig supplies this file but does not own it, and nothing here names this directory.
# Notes: docs/notes/Tiltfile.md

# ── who we are, and on which ports ─────────────────────────────────────────
# Asked of ctrl/ports.sh (via lib/config.sh), never recomputed here in Starlark.
_facts   = str(local('bash ports.sh active', quiet=True)).split()
CLUSTER  = _facts[0]
CTX      = _facts[1]
HTTP     = _facts[2]
HTTPS    = _facts[3]
TILT     = _facts[4]
REGISTRY = _facts[5]

# Where the manifests live (MANIFESTS_DIR, see k8s/README.md).
# The value is REPO-ROOT relative and this file runs in ctrl/, so prefix '../'.
MANIFESTS = '../' + _facts[6]

# ── refuse to deploy into the wrong cluster ────────────────────────────────
# Tilt fixes the context before parsing this file, so it can only be refused here.
# `make tilt` passes --context; this catches a bare `tilt up`.
allow_k8s_contexts(CTX)
if k8s_context() != CTX:
    fail("Wrong kubectl context: '%s'. This is %s — run: make tilt, or tilt up --context %s"
         % (k8s_context(), CLUSTER, CTX))

# The namespace has to exist before anything lands in it, and kustomize does not
# guarantee ordering across resources. Creating it here is idempotent.
local('kubectl --context %s create namespace %s --dry-run=client -o yaml | kubectl --context %s apply -f -'
      % (CTX, CLUSTER, CTX), quiet=True)

# ── images go to this environment's own registry ───────────────────────────
# Fail closed: name the registry rather than let Tilt infer it, or a miss pushes
# an unqualified image to docker.io.
default_registry('localhost:' + REGISTRY)

k8s_yaml(kustomize(MANIFESTS))

# ── Images ─────────────────────────────────────────────────────────────────
# (nothing yet — rig's examples run upstream images. Add docker_build calls here.)


# ── Resources ──────────────────────────────────────────────────────────────
# (nothing yet — add k8s_resource calls here to name and order what you deploy.)


# Everything with no dev loop of its own, gathered so it does not clutter the UI.
k8s_resource(
    objects=[CLUSTER + ':namespace'],
    new_name='infra',
)

# ═══════════════════════════════════════════════════════════════════════════
# Catalogue — paste what you need, delete the rest.
# Commented out so this file runs as-is.
# ═══════════════════════════════════════════════════════════════════════════
#
# ── build an image ─────────────────────────────────────────────────────────
# context= is the REPO ROOT ('..'); dockerfile= is relative to THIS file (ctrl/).
# So every COPY is repo-root relative, even for files beside the Dockerfile.
#
# docker_build(
#     CLUSTER + '-api',                  # must match `image:` in the manifest —
#     context='..',                      #   that string is the only thing
#     dockerfile='Dockerfile.api',       #   connecting the two
#     ignore=['.git', 'def', '.venv', 'node_modules', '__pycache__'],
#     live_update=[sync('../api', '/app/api')],
# )
#
# ── name and order a resource ──────────────────────────────────────────────
# k8s_resource('api', resource_deps=['postgres'], labels=['app'])
# k8s_resource('gateway', resource_deps=['api', 'ui'], labels=['app'])
#
# ── reload the gateway when its config changes ─────────────────────────────
# A hash-less configMapGenerator ConfigMap never changes name, so edits do NOT
# roll the pod on their own.
#
# local_resource(
#     'gateway-reload',
#     cmd='kubectl --context %s -n %s rollout restart deployment/gateway' % (CTX, CLUSTER),
#     deps=['k8s/base/Caddyfile'],
#     resource_deps=['gateway'],
#     auto_init=False,
# )
#
# ── an overlay whose secretGenerator reads outside its own directory ───────
# kustomize refuses to read above the kustomization root unless told to. Only
# add this if you actually have such a generator; it loosens a safety check.
#
# k8s_yaml(kustomize(MANIFESTS, flags=['--load-restrictor=LoadRestrictionsNone']))
#
# ── reach a service directly, bypassing the gateway ────────────────────────
# Prefer the gateway; host ports are shared machine-wide. If you need one, take it
# from this environment's own port block.
#
# k8s_resource('postgres', port_forwards=[str(int(HTTP) + 5) + ':5432'])
