#!/usr/bin/env node

import child_process from "child_process";
import fs from "fs";
import util from "util";

const my_execFile = util.promisify(child_process.execFile);
let warns_count = 0;
for (const f of await fs.promises.readdir("tests")) {
  // odd linker errors
  if (f.startsWith('Semaphore')) continue;
  // Find self-contained test cases (aka doesn't rely on tasty)
  if (!f.endsWith(".hs")) continue;
  const s = await fs.promises.readFile(`tests/${f}`, "utf-8");
  if (s.indexOf("Test.Tasty") !== -1) continue;

  // Compile the test case
  console.log(`\n${f}`);
  const r = await my_execFile("wasm32-wasi-ghc", [
    `tests/${f}`,
    "-Wno-deprecations",
    "-optl-Wl,--warn-unresolved-symbols",
  ]);

  // Check for wasm-ld warnings that involves the archive generated by
  // cabal build
  const warns = r.stderr
    .split("\n")
    .filter((l) => l.indexOf("dist-newstyle") !== -1);
  warns_count += warns.length;
  console.log(warns);
}

// Use exit code to indicate failure
process.exit(warns_count === 0 ? 0 : 1);
