/**
 * FSBuilder 2.1
 * Copyright (c) 2022-2025 NanderTGA
 * Licensed under AGPL v3
 * Download the latest version from `https://nandertga.ddns.net/w96-packages/fsbuilder.ts`
 * NOTE: this version has been tweaked to work for my repository specifically, but feel free to modify it for your own.
 * If you do, I do expect you to put it up somewhere on your repo. Not doing that is probably a license violation.
 * Usage: `$ npx tsx fsbuilder.ts <dirname(use "." to build rofs.json for the current dir)>`
 */

import fs from "fs";
import path from "path";

export enum fileType {
    file = 0,
    directory = 1
}

export type RofsJson = Record<string, {
    length: number,
    type: fileType,
}>;

let rofs: RofsJson;

export function processDir(dir: string): void {
    console.debug(`Processing ${dir}`);
    rofs[`/w96-packages/${dir}`] = {
        length: 0,
        type  : fileType.directory
    };

    const dirListing = fs.readdirSync(dir);
    dirListing.forEach(cFile => {
        const fileWithDir = path.posix.join(dir, cFile);
        if (fs.statSync(fileWithDir).isDirectory()) processDir(fileWithDir);
        else processFile(fileWithDir);
    });
}

export function processFile(file: string): void {
    console.debug(`Processing ${file}`);
    const fileLength = fs.statSync(file).size;
    rofs[`/w96-packages/${file}`] = {
        length: fileLength,
        type  : fileType.file
    };
}

export async function build(rootDir: string): Promise<RofsJson> {
    return new Promise( resolve => {
        rofs = {
            "/": { length: 0, type: fileType.directory },
            "/w96-packages": { length: 0, type: fileType.directory },
        };
    
        processDir(path.normalize(rootDir));
        if (rootDir == ".") delete rofs["/."];
        if (rootDir == ".") delete rofs["/w96-packages/."];
        rofs["/.meta"] = rofs["/w96-packages/.meta"]
        resolve(rofs);
    });
}

export default async function BuildAndWrite(rootDir: string): Promise<void> {
    const rofs = await build(rootDir);
    fs.writeFileSync(path.resolve(rootDir, "rofs.json"), JSON.stringify(rofs))
}

if (require.main === module) BuildAndWrite(process.argv[2]).then(() => console.log("Done"));
