import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { assertKnownArgs, optionalArg, parseArgs, reportCliError, requiredArg } from "./cli.ts";
import { verifyManifest } from "./manifest.ts";

async function main(): Promise<void> {
  const args = parseArgs(process.argv.slice(2));
  assertKnownArgs(args, ["manifest", "public-key", "artifact-root", "require-signature"]);
  const path = resolve(requiredArg(args, "manifest"));
  const raw = JSON.parse(await readFile(path, "utf8")) as unknown;
  const publicKeyPath = optionalArg(args, "public-key");
  const artifactRoot = optionalArg(args, "artifact-root");
  const manifest = await verifyManifest(raw, {
    ...(publicKeyPath === undefined ? {} : { publicKeyPath }),
    ...(artifactRoot === undefined ? {} : { artifactRoot }),
    requireSignature: args.get("require-signature") === true,
  });
  process.stdout.write(
    `OK: ${manifest.payload.releaseId}, payload et ${manifest.payload.artifacts.length} description(s) d'artefact valides${manifest.signature ? ", signature présente" : ""}.\n`,
  );
}

main().catch(reportCliError);
