#!/usr/bin/env node

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';

function fail(message) {
  console.error(`ERROR: ${message}`);
  process.exit(1);
}

const [, , inputPkg, outputDir] = process.argv;
if (!inputPkg || !outputDir) {
  fail('usage: repack-networkmgr-for-mdo.mjs <input-pkg> <output-dir>');
}

if (!fs.existsSync(inputPkg)) {
  fail(`input package not found: ${inputPkg}`);
}

fs.mkdirSync(outputDir, { recursive: true });

const tempRoot = fs.mkdtempSync(path.join(outputDir, 'work-'));
const extractRoot = path.join(tempRoot, 'root');
const packageOut = path.join(tempRoot, 'out');
fs.mkdirSync(extractRoot, { recursive: true });
fs.mkdirSync(packageOut, { recursive: true });

try {
  let result = spawnSync('tar', ['-xf', inputPkg, '-C', extractRoot], {
    stdio: 'inherit',
  });
  if (result.status !== 0) {
    fail(`failed to extract ${inputPkg}`);
  }

  const manifestPath = path.join(extractRoot, '+MANIFEST');
  const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));

  if (manifest.deps?.sudo) {
    delete manifest.deps.sudo;
  }

  if (manifest.files?.['/usr/local/etc/sudoers.d/networkmgr']) {
    delete manifest.files['/usr/local/etc/sudoers.d/networkmgr'];
  }

  const sudoersPath = path.join(extractRoot, 'usr/local/etc/sudoers.d/networkmgr');
  fs.rmSync(sudoersPath, { force: true });

  const desktopRel = 'usr/local/etc/xdg/autostart/networkmgr.desktop';
  const desktopKey = `/${desktopRel}`;
  const desktopPath = path.join(extractRoot, desktopRel);
  if (!fs.existsSync(desktopPath)) {
    fail(`missing desktop file in package: ${desktopKey}`);
  }

  let desktop = fs.readFileSync(desktopPath, 'utf8');
  if (desktop.includes('Exec=sudo networkmgr')) {
    desktop = desktop.replace('Exec=sudo networkmgr', 'Exec=mdo -u root networkmgr');
    fs.writeFileSync(desktopPath, desktop);
  } else if (!desktop.includes('Exec=mdo -u root networkmgr')) {
    fail(`unexpected desktop launcher in ${desktopKey}`);
  }

  if (!manifest.files?.[desktopKey]) {
    fail(`desktop file missing from manifest: ${desktopKey}`);
  }
  manifest.files[desktopKey].sum =
    '1$' + crypto.createHash('sha256').update(fs.readFileSync(desktopPath)).digest('hex');

  let flatsize = 0;
  for (const key of Object.keys(manifest.files || {})) {
    const filePath = path.join(extractRoot, key.replace(/^\//, ''));
    flatsize += fs.statSync(filePath).size;
  }
  manifest.flatsize = flatsize;

  fs.writeFileSync(manifestPath, JSON.stringify(manifest));

  result = spawnSync('/usr/local/sbin/pkg-static', [
    'create',
    '-M',
    manifestPath,
    '-r',
    extractRoot,
    '-o',
    packageOut,
  ], {
    stdio: 'inherit',
  });
  if (result.status !== 0) {
    fail('pkg create failed while rebuilding networkmgr');
  }

  const outputPkg = fs
    .readdirSync(packageOut)
    .filter((name) => name.startsWith('networkmgr-') && name.endsWith('.pkg'))
    .sort()[0];
  if (!outputPkg) {
    fail('rebuilt networkmgr package not found');
  }

  const finalPath = path.join(outputDir, outputPkg);
  fs.copyFileSync(path.join(packageOut, outputPkg), finalPath);
  console.log(finalPath);
} finally {
  fs.rmSync(tempRoot, { recursive: true, force: true });
}
