#!/bin/sh
set -eu

log() {
  printf '%s\n' "$*" >&2
}

is_true() {
  case "$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')" in
    1|true|yes|on) return 0 ;;
    *) return 1 ;;
  esac
}

wait_for_kube_api_tunnel() {
  local_host="${K3SCTL_KUBE_API_LOCAL_HOST:-127.0.0.1}"
  local_port="${K3SCTL_KUBE_API_LOCAL_PORT:-6443}"
  attempts="${K3SCTL_KUBE_API_SSH_TUNNEL_WAIT_ATTEMPTS:-30}"
  index=1
  while [ "$index" -le "$attempts" ]; do
    status="$(curl -ksS --connect-timeout 2 --max-time 4 -o /dev/null -w '%{http_code}' "https://${local_host}:${local_port}/version" 2>/dev/null || true)"
    case "$status" in
      200|401|403)
        log "k3sctl-adapter: kube api tunnel reachable status=${status}"
        return 0
        ;;
    esac
    sleep 1
    index=$((index + 1))
  done
  log "k3sctl-adapter: kube api tunnel did not become reachable at ${local_host}:${local_port}"
  return 1
}

start_kube_api_ssh_tunnel() {
  if ! is_true "${K3SCTL_KUBE_API_SSH_TUNNEL_ENABLED:-false}"; then
    return 0
  fi

  ssh_host="${K3SCTL_KUBE_API_SSH_HOST:-host.docker.internal}"
  ssh_user="${K3SCTL_KUBE_API_SSH_USER:-ubuntu}"
  ssh_key="${K3SCTL_KUBE_API_SSH_KEY:-/run/host-ssh/id_ed25519}"
  local_host="${K3SCTL_KUBE_API_LOCAL_HOST:-127.0.0.1}"
  local_port="${K3SCTL_KUBE_API_LOCAL_PORT:-6443}"
  remote_host="${K3SCTL_KUBE_API_REMOTE_HOST:-127.0.0.1}"
  remote_port="${K3SCTL_KUBE_API_REMOTE_PORT:-6443}"
  restart_delay="${K3SCTL_KUBE_API_SSH_RESTART_DELAY_SECONDS:-2}"

  if [ ! -r "$ssh_key" ]; then
    log "k3sctl-adapter: SSH tunnel key is not readable: ${ssh_key}"
    exit 1
  fi

  mkdir -p /tmp/k3sctl-ssh
  (
    while :; do
      log "k3sctl-adapter: starting kube api SSH tunnel ${local_host}:${local_port}->${remote_host}:${remote_port} via ${ssh_user}@${ssh_host}"
      ssh \
        -i "$ssh_key" \
        -o BatchMode=yes \
        -o StrictHostKeyChecking=no \
        -o UserKnownHostsFile=/tmp/k3sctl-ssh/known_hosts \
        -o ExitOnForwardFailure=yes \
        -o ServerAliveInterval=15 \
        -o ServerAliveCountMax=3 \
        -N \
        -L "${local_host}:${local_port}:${remote_host}:${remote_port}" \
        "${ssh_user}@${ssh_host}" || true
      log "k3sctl-adapter: kube api SSH tunnel exited; restarting in ${restart_delay}s"
      sleep "$restart_delay"
    done
  ) &

  wait_for_kube_api_tunnel
}

start_kube_api_ssh_tunnel
exec "$@"
