// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃ This file is part of the Perspective library, distributed under the terms ┃
// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

import * as fs from "node:fs";
import * as path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, "..");
const DIST = path.join(__dirname, "dist");
const STAGING = path.join(REPO_ROOT, "dist-gh-pages");
const BRANCH = "gh-pages";

function git(args, opts = {}) {
    return execFileSync("git", args, {
        stdio: "inherit",
        cwd: REPO_ROOT,
        ...opts,
    });
}

function copyRecursive(src, dest) {
    const stat = fs.statSync(src);
    if (stat.isDirectory()) {
        fs.mkdirSync(dest, { recursive: true });
        for (const child of fs.readdirSync(src)) {
            copyRecursive(path.join(src, child), path.join(dest, child));
        }
    } else {
        fs.copyFileSync(src, dest);
    }
}

if (!fs.existsSync(DIST)) {
    console.error(`Missing ${DIST} — run \`npm run build\` first.`);
    process.exit(1);
}

if (!fs.existsSync(STAGING)) {
    git(["worktree", "add", STAGING, BRANCH]);
} else {
    git(["fetch", "origin", BRANCH]);
    git(["checkout", `origin/${BRANCH}`], { cwd: STAGING });
}

// Clear tracked + untracked content in the staging worktree, preserving
// the worktree's `.git` link.
git(["rm", "-rf", "--quiet", "--ignore-unmatch", "."], { cwd: STAGING });
git(["clean", "-fdx"], { cwd: STAGING });

for (const entry of fs.readdirSync(DIST)) {
    copyRecursive(path.join(DIST, entry), path.join(STAGING, entry));
}

git(["add", "-A"], { cwd: STAGING });

console.log(`Staged dist/ onto ${BRANCH} at ${STAGING}`);
console.log(`Review with \`git -C ${STAGING} status\`, then commit and push.`);
