#!/usr/bin/env bash
set -euo pipefail

KUBECONFIG_PATH=${BUILD_REMOTE_K3S_KUBECONFIG:-"$HOME/.kube/config-buildboxes"}
if ! kubectl --kubeconfig "$KUBECONFIG_PATH" version --request-timeout=5s >/dev/null 2>&1; then
  printf 'SKIP k3s cluster unreachable via %s\n' "$KUBECONFIG_PATH"
  exit 0
fi

BUILD_REMOTE_K3S=1 \
BUILD_REMOTE_K3S_KUBECONFIG="$KUBECONFIG_PATH" \
BUILD_REMOTE_K3S_IMAGE="${BUILD_REMOTE_K3S_IMAGE:-busybox:1.36}" \
node --input-type=module -e '
  import { spawnSync } from "node:child_process";
  import { tryK3sBuild } from "./modules/workstation/claude/lib/k3s-remote-build.mjs";
  const kubeconfig = process.env.BUILD_REMOTE_K3S_KUBECONFIG;
  const suffix = `${process.pid}-${Date.now()}`;
  const prepName = `rb-workspace-prep-${suffix}`;
  const workspace = `/var/lib/buildbox/builds/k3s-integration-${suffix}`;
  const epoch = String(Date.now() * 1000000);
  const common = ["--kubeconfig", kubeconfig, "--namespace", "default"];
  const run = (args, options = {}) => spawnSync("kubectl", [...common, ...args], { encoding: "utf8", ...options });
  const nodes = run(["get", "nodes", "-o", "json"]);
  if (nodes.status !== 0) throw new Error(nodes.stderr);
  const nodeName = JSON.parse(nodes.stdout).items.find((node) =>
    node.status?.conditions?.some((condition) => condition.type === "Ready" && condition.status === "True"))?.metadata?.name;
  if (!nodeName) throw new Error("no Ready node for workspace integration test");
  const prep = {
    apiVersion: "batch/v1", kind: "Job", metadata: { name: prepName },
    spec: { backoffLimit: 0, ttlSecondsAfterFinished: 300, template: { spec: {
      restartPolicy: "Never", nodeSelector: { "kubernetes.io/hostname": nodeName },
      containers: [{ name: "prep", image: process.env.BUILD_REMOTE_K3S_IMAGE, command: ["/bin/sh", "-c"],
        args: ["mkdir -p \"$1/.git\"; printf %s \"$2\" > \"$1/.rb-epoch\"; printf workspace-ok > \"$1/input.txt\"", "prep", workspace, epoch],
        volumeMounts: [{ name: "repo-mirror", mountPath: "/var/lib/buildbox" }] }],
      volumes: [{ name: "repo-mirror", hostPath: { path: "/var/lib/buildbox", type: "Directory" } }],
    } } },
  };
  try {
    const applied = run(["apply", "-f", "-"], { input: JSON.stringify(prep) });
    if (applied.status !== 0) throw new Error(applied.stderr);
    const waited = run(["wait", "--for=condition=complete", `job/${prepName}`, "--timeout=60s"]);
    if (waited.status !== 0) throw new Error(waited.stderr);
    const key = `integration-${suffix}`;
    const result = tryK3sBuild({ key, argv: ["sh", "-c", "test \"$(cat input.txt)\" = workspace-ok && printf k3s-ok"],
      workingDir: workspace, nodeNames: [nodeName], epoch, log: console.error });
    if (!result?.ran || result.status !== 0) process.exitCode = result?.status || 1;
  } finally {
    run(["delete", "job", prepName, "--ignore-not-found=true", "--wait=false"]);
  }
' | grep -qx k3s-ok
