#!/usr/bin/env node
// Patch the bundled Pi footer so operator sessions show the runtime hostname.
// This is intentionally a post-install patch because the live image ships Pi as
// an offline npm-global tarball rather than as source built in this repo.

const fs = require("node:fs");

const file = process.argv[2];
if (!file) {
  console.error("usage: patch-pi-footer-hostname.js FOOTER_JS");
  process.exit(64);
}

let src = fs.readFileSync(file, "utf8");

if (!src.includes('import { hostname } from "node:os";')) {
  if (src.includes('import { isAbsolute, relative, resolve, sep } from "node:path";\n')) {
    src = src.replace(
      'import { isAbsolute, relative, resolve, sep } from "node:path";\n',
      'import { isAbsolute, relative, resolve, sep } from "node:path";\nimport { hostname } from "node:os";\n',
    );
  } else {
    src = src.replace(/^(import .*?;\n)/, 'import { hostname } from "node:os";\n$1');
  }
}

const oldPwdBlock = `        const pwdLine = truncateToWidth(theme.fg("dim", pwd), width, theme.fg("dim", "..."));
        const lines = [pwdLine, dimStatsLeft + dimRemainder];`;

const newPwdBlock = `        // Show runtime hostname on the right of the cwd line. Use the kernel
        // hostname instead of parsing FreeBSD rc.conf so Pi stays portable and
        // reflects changes made after boot.
        const host = hostname();
        const minPwdHostPadding = 2;
        let hostForLine = host;
        let hostWidth = visibleWidth(hostForLine);
        if (hostWidth > width) {
            hostForLine = truncateToWidth(hostForLine, width, "...");
            hostWidth = visibleWidth(hostForLine);
        }
        const availableForPwd = width - hostWidth - minPwdHostPadding;
        let pwdLine;
        if (hostForLine && availableForPwd > 0) {
            const pwdForLine = visibleWidth(pwd) > availableForPwd ? truncateToWidth(pwd, availableForPwd, "...") : pwd;
            const pwdWidth = visibleWidth(pwdForLine);
            const padding = " ".repeat(Math.max(minPwdHostPadding, width - pwdWidth - hostWidth));
            pwdLine = theme.fg("dim", pwdForLine) + padding + theme.fg("dim", hostForLine);
        }
        else if (hostForLine) {
            pwdLine = theme.fg("dim", hostForLine);
        }
        else {
            pwdLine = truncateToWidth(theme.fg("dim", pwd), width, theme.fg("dim", "..."));
        }
        const lines = [pwdLine, dimStatsLeft + dimRemainder];`;

if (!src.includes("const minPwdHostPadding = 2;")) {
  if (!src.includes(oldPwdBlock)) {
    throw new Error(`Pi footer cwd block not found in ${file}`);
  }
  src = src.replace(oldPwdBlock, newPwdBlock);
}

if (!src.includes('lines.push("");\n        return lines;')) {
  src = src.replace('        return lines;\n', '        lines.push("");\n        return lines;\n');
}

fs.writeFileSync(file, src);
console.log(`patched ${file}`);
