// h dev seed-cdi
// deno run -A ./.scripts/seed-cdi.ts

import * as path from "jsr:@std/path";

import { listComposeFiles, paths } from "../routines/paths.js";

async function main() {
  const sourceFiles = await listComposeFiles().then((files) =>
    files.filter((name) => name.includes(".nvidia.") && !name.endsWith(".build.yml"))
  );

  for (const file of sourceFiles) {
    const outName = file.replace(".nvidia.", ".cdi.");
    const serviceName = resolveServiceName(file);
    const content =
      `
# This file is generated by seed-cdi.ts script,
# any updates will be overwritten.
services:
  ${serviceName}:
    deploy:
      resources:
        reservations:
          devices:
            - driver: cdi
              capabilities: [gpu]
              device_ids:
              - nvidia.com/gpu=all
    `.trim() + "\n";

    const outPath = path.join(paths.services, outName);
    console.log(`Writing ${outPath}...`);
    await Deno.writeTextFile(outPath, content);
  }

  console.log("Done!");
}

function resolveServiceName(filename: string) {
  const ignored = new Set(["compose", "x", "nvidia", "yml"]);
  const parts = filename.split(".").filter((part) => !ignored.has(part));

  if (parts.length !== 1) {
    throw new Error(
      `Unsupported seed Nvidia file: ${filename}, update the seed-cdi script`
    );
  }

  return parts[0];
}

main().catch(console.error);
