"use strict";

/**
 * openclaw service install
 *
 * Creates systemd unit files for openclaw.service and openclaw-gateway.service,
 * then daemon-reloads, enables, and starts them.
 */

const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");

const CONFIG_FILE = "/etc/openclaw/config.json";

function getCliBinPath() {
  // Find the globally installed openclaw bin directory
  try {
    const npmRoot = execSync("npm root -g", { encoding: "utf8" }).trim();
    return path.join(npmRoot, "@openclaw", "cli");
  } catch {
    // Fallback to the package's own location
    return path.resolve(__dirname, "..");
  }
}

function install(args) {
  console.log("Installing OpenClaw systemd services...");

  const pkgDir = getCliBinPath();
  const serverScript = path.join(pkgDir, "lib", "server.js");
  const gatewayScript = path.join(pkgDir, "lib", "gateway.js");

  // Determine node path
  let nodePath;
  try {
    nodePath = execSync("which node", { encoding: "utf8" }).trim();
  } catch {
    nodePath = "/usr/bin/node";
  }

  // --- openclaw.service ---
  const serverUnit = `[Unit]
Description=OpenClaw Server
After=network.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=${nodePath} ${serverScript}
Restart=on-failure
RestartSec=5
EnvironmentFile=-/etc/openclaw/env
WorkingDirectory=/var/lib/openclaw
StandardOutput=journal
StandardError=journal
SyslogIdentifier=openclaw

[Install]
WantedBy=multi-user.target
`;

  // --- openclaw-gateway.service ---
  const gatewayUnit = `[Unit]
Description=OpenClaw API Gateway
After=openclaw.service
Requires=openclaw.service

[Service]
Type=simple
ExecStart=${nodePath} ${gatewayScript} --serve
Restart=on-failure
RestartSec=5
EnvironmentFile=-/etc/openclaw/env
WorkingDirectory=/var/lib/openclaw
StandardOutput=journal
StandardError=journal
SyslogIdentifier=openclaw-gateway

[Install]
WantedBy=multi-user.target
`;

  // Write unit files
  fs.writeFileSync("/etc/systemd/system/openclaw.service", serverUnit);
  console.log("  Written /etc/systemd/system/openclaw.service");

  fs.writeFileSync("/etc/systemd/system/openclaw-gateway.service", gatewayUnit);
  console.log("  Written /etc/systemd/system/openclaw-gateway.service");

  // Reload systemd
  console.log("  Reloading systemd daemon...");
  execSync("systemctl daemon-reload");

  // Enable services
  console.log("  Enabling services...");
  execSync("systemctl enable openclaw.service openclaw-gateway.service");

  // Start services
  console.log("  Starting openclaw.service...");
  execSync("systemctl start openclaw.service");

  console.log("  Starting openclaw-gateway.service...");
  execSync("systemctl start openclaw-gateway.service");

  // Brief pause for startup
  execSync("sleep 2");

  // Check status
  try {
    const serverStatus = execSync("systemctl is-active openclaw.service", {
      encoding: "utf8",
    }).trim();
    console.log(`  openclaw.service: ${serverStatus}`);
  } catch {
    console.error("  openclaw.service: failed to start");
  }

  try {
    const gwStatus = execSync("systemctl is-active openclaw-gateway.service", {
      encoding: "utf8",
    }).trim();
    console.log(`  openclaw-gateway.service: ${gwStatus}`);
  } catch {
    console.error("  openclaw-gateway.service: failed to start");
  }

  console.log("Systemd service installation complete.");
}

function run(args) {
  const sub = args[0];

  switch (sub) {
    case "install":
      return install(args.slice(1));
    default:
      console.error(`Unknown service subcommand: ${sub}`);
      console.error("Usage: openclaw service install");
      process.exit(1);
  }
}

module.exports = { run };
