import { Elysia } from 'elysia'
import { staticPlugin } from "@elysiajs/static"
import { stat, readdir, readFile } from "node:fs/promises"
import { createHash } from "node:crypto";

type IndexEntry = { src: string, dest: string, hash: string };

async function scanDir(scanIn: string, base: string, outputBase: string): Promise<IndexEntry[]> {
    let files = await readdir(scanIn + "/" + base);
    let results: IndexEntry[] = [];

    for (let file of files) {
        if (await stat(scanIn + "/" + base + "/" + file).then(r => r.isDirectory())) {
            results = [...results, ...(await scanDir(scanIn, base + "/" + file, outputBase + file + "/"))]
        } else {
            results.push({
                src: base + "/" + file,
                dest: outputBase + file,
                hash: createHash('sha256').update(await readFile(scanIn + "/" + base + "/" + file)).digest('hex')
            });
        }
    }

    return results;
}

new Elysia()
    .get("/index.json", async () => scanDir("..", "src", "/"))
    .get("/sha256.lua", async () => Bun.file("../sha256.lua"))
    .use(staticPlugin({
        assets: "../src",
        prefix: "/src"
    }))
    .get("/install.lua", async () => Bun.file("../install.lua"))
    .listen(parseInt(process.env.PORT || "3000"))