# The dev loop, rig's half. `make tilt` from rig's folder, or from an overlay's forwarder.
# rig owns this file: who we are, the context guard, the registry, the overlay's manifests.
# The workload's half is the overlay's own Tiltfile, included at the end; edit that one.
# 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]
# Absolute paths, or '-' when there is none.
MANIFESTS = '' if _facts[6] == '-' else _facts[6]
OVERLAY   = '' if _facts[7] == '-' else _facts[7]

# ── 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))

# ── 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)

# ── the overlay's manifests ────────────────────────────────────────────────
# Every namespace they use must exist before anything lands in it, and kustomize
# does not order resources, so create them here (idempotent). The Namespaces they
# declare are grouped as 'infra', whatever they are named.
if MANIFESTS:
    _yaml = kustomize(MANIFESTS)
    k8s_yaml(_yaml)
    _declared = []
    _namespaces = {}
    for _o in decode_yaml_stream(_yaml):
        if not _o:
            continue
        _md = _o.get('metadata') or {}
        if _o.get('kind') == 'Namespace':
            _declared.append(_md.get('name'))
            _namespaces[_md.get('name')] = True
        elif _md.get('namespace'):
            _namespaces[_md.get('namespace')] = True
    for _ns in sorted(_namespaces.keys()):
        local('kubectl --context %s create namespace %s --dry-run=client -o yaml | kubectl --context %s apply -f -'
              % (CTX, _ns, CTX), quiet=True)
    if _declared:
        k8s_resource(objects=[_n + ':namespace' for _n in _declared], new_name='infra')

# ── the workload's half: the overlay's Tiltfile ────────────────────────────
# Included, so its relative paths resolve from the overlay's own folder. It reads
# these facts with os.getenv and never needs a path back into rig.
os.putenv('RIG_CLUSTER', CLUSTER)
os.putenv('RIG_CONTEXT', CTX)
os.putenv('RIG_HTTP_PORT', HTTP)
os.putenv('RIG_HTTPS_PORT', HTTPS)
os.putenv('RIG_TILT_PORT', TILT)
os.putenv('RIG_REGISTRY', 'localhost:' + REGISTRY)
os.putenv('RIG_OVERLAY_DIR', OVERLAY)
if OVERLAY and os.path.exists(OVERLAY + '/Tiltfile'):
    include(OVERLAY + '/Tiltfile')
