load('ext://helm_remote', 'helm_remote')
load('ext://namespace', 'namespace_create')
load("ext://cert_manager", "deploy_cert_manager")
load('./helpers.py', 'kcp_build')

k8s_yaml('kernel-limits-job.yaml')

current_context = k8s_context()

deploy_cert_manager(version='v1.19.2')
k8s_yaml('./issuer.yaml')

namespace_create('envoy-gateway-system')
helm_remote(
  'gateway-helm',
  repo_url='oci://registry-1.docker.io/envoyproxy',
  repo_name='gateway-helm',
  release_name='envoy',
  namespace='envoy-gateway-system',
  version='v1.7.0',
  values=[],
  set=[],
)

# install the gateway and configure tilt to start a port-forward to the
# resulting service that will route the traffic.
# the name of the gateway is random, hence the selector
k8s_yaml('gateway.yaml')
local_resource('ingress', serve_cmd="./port-forward.bash", allow_parallel=True)

# Observability stack (Grafana, Loki, Prometheus, Promtail) is deployed by
# default. External users who don't need it can skip it to save resources and
# startup time by setting KCP_OBSERVABILITY_ENABLED=false (also accepts 0/no/off).
if os.getenv('KCP_OBSERVABILITY_ENABLED', 'true').lower() not in ('false', '0', 'no', 'off'):
    include('./observability/Tiltfile')
else:
    print('Observability stack disabled (KCP_OBSERVABILITY_ENABLED=false)')

# etcd
# builtin kustomize does not support remote urls, see https://github.com/tilt-dev/tilt/issues/2383
k8s_yaml(kustomize('etcd'))

# jobs to build docker images
kcp_build('kcp')
kcp_build('kcp-front-proxy')

# kcp-operator
k8s_yaml(kustomize('./kcp-operator'))

# define kcp-operator kinds so tilt knows where to update images
k8s_kind('RootShard',
    image_object = {
      'json_path': '{.spec.image}',
      'repo_field': 'repository',
      'tag_field': 'tag'
    }
)
k8s_kind('RootShard',
    # tilt currently can't handle multiple images in a CRD if the repo and
    # tag are split: https://github.com/tilt-dev/tilt/issues/6045
    # (this issue mentions this problem but for another reason)
    # luckily, tilt allows defining the same kind twice and just aggregates the image_objects
    image_object = {
      'json_path': '{.spec.proxy.image}',
      'repo_field': 'repository',
      'tag_field': 'tag'
    }
)
k8s_kind('Shard',
    image_object = {
      'json_path': '{.spec.image}',
      'repo_field': 'repository',
      'tag_field': 'tag'
    }
)
k8s_kind('FrontProxy',
    image_object = {
      'json_path': '{.spec.image}',
      'repo_field': 'repository',
      'tag_field': 'tag'
    }
)

k8s_yaml('./shard-root.yaml')
k8s_resource('root:rootshard', labels='kcp')

k8s_yaml('./shard-theseus.yaml')
k8s_resource('theseus:shard', labels='kcp')

k8s_yaml('./front-proxy.yaml')
k8s_resource('frontproxy:frontproxy', labels='kcp')

k8s_kind('Kubeconfig')
k8s_yaml('./kubeconfig-kcp-admin.yaml')
local_resource('kcp-admin extract',
    cmd="./extract-kubeconfig.bash",
    deps=['frontproxy:kubeconfig', 'root:kubeconfig', 'theseus:kubeconfig'],
    labels='kcp',
    allow_parallel=True,
)

# Portal (contrib-dashboard) — a web UI for kcp workspaces/APIExports served in
# no-oidc mode against the front-proxy. Enabled by default; disable with
# KCP_PORTAL_ENABLED=false (also accepts 0/no/off).
#
# Live-reload build: the dashboard sources live in the sibling contrib-dashboard
# checkout (github.com/kcp-dev/contrib-dashboard, default ../../../contrib-dashboard).
# The docker_build ref matches the image in dashboard.yaml, so Tilt swaps in the
# locally built image and rebuilds it on source changes.
if os.getenv('KCP_PORTAL_ENABLED', 'true').lower() not in ('false', '0', 'no', 'off'):
    DASHBOARD_DIR = os.getenv('KCP_PORTAL_DIR', '../../../contrib-dashboard')
    if not os.path.exists(DASHBOARD_DIR + '/Dockerfile'):
        fail('contrib-dashboard not found at %s — set KCP_PORTAL_DIR to your checkout ' % DASHBOARD_DIR +
             'or disable the portal with KCP_PORTAL_ENABLED=false')
    # docker_build ref matches the image in the checkout's deploy/deployment.yaml
    # (kcp-dashboard), so Tilt swaps in the locally built image and rebuilds it on
    # source changes.
    docker_build(
        'kcp-dashboard',
        DASHBOARD_DIR,
        dockerfile=DASHBOARD_DIR + '/Dockerfile',
        ignore=['node_modules', 'web/dist', 'server/dist', '**/*.log'],
    )
    k8s_yaml(DASHBOARD_DIR + '/deploy/deployment.yaml')
    k8s_resource('kcp-dashboard',
        port_forwards=['8080:8080'],
        # Wait for the admin kubeconfig secret to be extracted so the mount exists.
        resource_deps=['kcp-admin extract'],
        labels='dashboard',
    )
    print('kcp portal → http://localhost:8080 (no-oidc, live-reload from %s)' % DASHBOARD_DIR)
else:
    print('Portal (contrib-dashboard) disabled (KCP_PORTAL_ENABLED=false)')
