#!/bin/bash
# ahel-arkenstone-pf — keeps the kubectl port-forwards into the Arkenstone
# k3s cluster alive:
#   127.0.0.1:8020 → arkenstone/svc/arkenstone-api  (engine API, loopback only)
#   127.0.0.1:9200 → arkenstone/svc/opensearch      (datalake — METADATA/
#                     aggregations only, enforced by the arkenstone-bridge;
#                     never exposed beyond loopback)
# Runs as the com.ahel.arkenstone-pf LaunchDaemon (root, KeepAlive). Each
# forward is supervised in its own loop: kubectl port-forward exits on
# connection loss, so we just restart it after a short pause.
set -u

export KUBECONFIG=${KUBECONFIG:-/Users/admin/.kube/config}
KUBECTL=${KUBECTL:-/opt/homebrew/bin/kubectl}

supervise() { # supervise <namespace> <svc> <local-port> <remote-port> <addresses>
  while true; do
    "$KUBECTL" port-forward -n "$1" "svc/$2" "$3:$4" \
      --address "$5" 2>&1 | while IFS= read -r line; do
        printf '%s [%s] %s\n' "$(date '+%F %T')" "$2" "$line"
      done
    sleep 5
  done
}

supervise arkenstone arkenstone-api 8020 8020 127.0.0.1 &
supervise arkenstone opensearch 9200 9200 127.0.0.1 &
wait
