/**
 * Linux systemd uninstaller.
 * Run as root: node installer/linux/uninstall-service.js
 */
const fs = require("fs");
const { execSync } = require("child_process");

const serviceName = "siraya-printer";
const installDir = process.env.SIRAYA_INSTALL_DIR || "/opt/siraya/printer";
const dataDir = process.env.SIRAYA_DATA_DIR || "/var/lib/siraya/printer";
const keepData = process.env.SIRAYA_KEEP_DATA === "1";

if (process.platform !== "linux") {
  process.exit(0);
}

if (process.getuid && process.getuid() !== 0) {
  console.error("Run as root");
  process.exit(1);
}

try {
  execSync(`systemctl stop ${serviceName}.service`, { stdio: "ignore" });
  execSync(`systemctl disable ${serviceName}.service`, { stdio: "ignore" });
} catch {
  /* ignore */
}

const unitPath = `/etc/systemd/system/${serviceName}.service`;
if (fs.existsSync(unitPath)) {
  fs.unlinkSync(unitPath);
}
execSync("systemctl daemon-reload", { stdio: "ignore" });

if (!keepData && fs.existsSync(dataDir)) {
  fs.rmSync(dataDir, { recursive: true, force: true });
}
if (fs.existsSync(installDir)) {
  fs.rmSync(installDir, { recursive: true, force: true });
}

console.log("Removed", serviceName);
process.exit(0);
