import { execSync } from "child_process";

const kubeconfig = "/Users/jroberts/projects/K8S-QuickDeploy/k8s.yaml";

function getKey(name: string): string {
  const b64 = execSync(
    `KUBECONFIG=${kubeconfig} kubectl get secret optima-keys-secret -n optima -o jsonpath="{.data.${name}}"`,
  )
    .toString()
    .trim();
  return Buffer.from(b64, "base64").toString("utf-8");
}

const privKeys = [
  "ACCESS_TOKEN_PRIVATE_KEY",
  "REFRESH_TOKEN_PRIVATE_KEY",
  "PERMISSIONS_PRIVATE_KEY",
  "SECURE_VALUES_PRIVATE_KEY",
];

const converted: Record<string, string> = {};

// Use openssl CLI to convert PKCS#1 to PKCS#8 (Bun's crypto has issues with some keys)
for (const k of privKeys) {
  const pem = getKey(k);
  const pkcs8 = execSync("openssl pkey -in /dev/stdin", {
    input: pem,
  }).toString();
  converted[k] = pkcs8;
  console.log(`${k}: converted to PKCS#8 ✅`);
}

const pubPem = getKey("SECURE_VALUES_PUBLIC_KEY");
const spki = execSync("openssl rsa -RSAPublicKey_in -pubout -in /dev/stdin", {
  input: pubPem,
}).toString();
converted["SECURE_VALUES_PUBLIC_KEY"] = spki;
console.log("SECURE_VALUES_PUBLIC_KEY: converted to SPKI ✅");

// Generate kubectl command to recreate the secret with PKCS#8 keys
const args = Object.entries(converted)
  .map(([k, v]) => `--from-literal=${k}='${v}'`)
  .join(" \\\n  ");

console.log("\n--- Delete and recreate secret with PKCS#8 keys ---\n");
console.log(
  `KUBECONFIG=${kubeconfig} kubectl delete secret optima-keys-secret -n optima`,
);
console.log(
  `KUBECONFIG=${kubeconfig} kubectl create secret generic optima-keys-secret -n optima \\\n  ${args}`,
);

// Actually do it
console.log("\nApplying...");
execSync(
  `KUBECONFIG=${kubeconfig} kubectl delete secret optima-keys-secret -n optima`,
);

const literals = Object.entries(converted).map(
  ([k, v]) => `--from-literal=${k}=${v}`,
);
const cmd = `KUBECONFIG=${kubeconfig} kubectl create secret generic optima-keys-secret -n optima ${literals.join(" ")}`;
execSync(cmd);

console.log("Secret recreated with PKCS#8 keys ✅");
