import { readFileSync } from "node:fs";
import https from "node:https";

const path = process.argv[2];
const host = process.env.KUBERNETES_SERVICE_HOST;
const port = Number(process.env.KUBERNETES_SERVICE_PORT || "443");
const token = readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8").trim();
const ca = readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt");

const req = https.request({ host, port, path, method: "GET", ca, headers: { authorization: `Bearer ${token}` } }, (res) => {
  let body = "";
  res.setEncoding("utf8");
  res.on("data", (chunk) => { body += chunk; });
  res.on("end", () => {
    if ((res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300) {
      process.stdout.write(body);
      process.exit(0);
    }
    process.stderr.write(body || `kube api status ${res.statusCode}`);
    process.exit(1);
  });
});
req.on("error", (error) => {
  process.stderr.write(error?.message || String(error));
  process.exit(1);
});
req.end();
