// peach daemon — manage the persistent peach bridge daemon
//
// wraps `peach serve` so it starts automatically on login and restarts if
// it crashes. the agent points at the executable that ran `daemon install`,
// and `peach upgrade` replaces that file in place and then restarts a running
// daemon itself, so the plist/unit file never needs rewriting.
//
// `daemonInstall` is shared by `peach setup` and the explicit
// `peach daemon install` machine-bootstrap path.
//
//   macOS:  ~/Library/LaunchAgents/dev.sootsim.daemon.plist (launchd)
//   linux:  ~/.config/systemd/user/sootsim-daemon.service (systemd --user)
//   win:    not yet supported — use `peach serve` in a persistent shell.
//
// the macOS launchd Label is `dev.sootsim.daemon` (matching the .app
// CFBundleIdentifier).

import { spawnSync } from 'child_process'
import {
  existsSync,
  mkdirSync,
  readdirSync,
  readFileSync,
  readlinkSync,
  realpathSync,
  rmSync,
  statSync,
  writeFileSync,
} from 'fs'
import { homedir } from 'os'
import { dirname, resolve } from 'path'
import { DEFAULT_SOOTSIM_BRIDGE_PORT } from '../../src/bridge-constants'
import { unregisterNativeDesktopLinks } from '../../src/desktop-host-delivery'
import {
  daemonAppDir,
  isDaemonLockfileFresh,
  readDaemonLockfile,
  shouldSkipPersistentDaemon,
  rnxHomeDir,
  type DaemonLockfile,
} from '../../src/home-paths'
import { rnxPublicBrand } from '../../src/public-brand'
import { printCommandHelp } from '../help'
import { escapeXml } from '../maestro-report'
import { peachExit } from '../run-rnx'
import { rnxSelfInvocation, type RnxSelfInvocation } from '../self-invocation'
import { DAEMON_ENVIRONMENT, ensureDaemonApp } from './daemon-mac-app'

// minimum seconds between launchd / systemd respawns. without this, a daemon
// that crashes on startup respawns in a tight loop — launchd's default is 10s,
// systemd's previous setting was 3s. bumping to 60s caps the damage of any
// misconfig that still slips past the bridge-host's port-fallback search.
const RESPAWN_THROTTLE_SECONDS = 60

const SERVICE_LABEL_MAC = 'dev.sootsim.daemon'
const LEGACY_SERVICE_LABEL_MAC = 'dev.sootsim.server'
const SERVICE_NAME_LINUX = 'sootsim-daemon'
const LOG_DIR = resolve(homedir(), 'Library/Logs/sootsim')
const LOG_DIR_LINUX = resolve(homedir(), '.local/state/sootsim')
const LSOF = process.platform === 'darwin' ? '/usr/sbin/lsof' : 'lsof'

interface DaemonOptions {
  port?: number
}

export async function runDaemon(args: string[], opts: DaemonOptions = {}) {
  const [sub, ...rest] = args
  const port = opts.port ?? DEFAULT_SOOTSIM_BRIDGE_PORT

  if (!sub || sub === '--help' || sub === '-h') {
    printHelp()
    return
  }

  switch (sub) {
    case 'install':
      return daemonInstall({ port, force: rest.includes('--force') })
    case 'uninstall':
      return daemonUninstall(rest)
    case 'status':
      return daemonStatus()
    case 'restart':
      return daemonRestart()
    case 'start':
      return daemonStart()
    case 'stop':
      return daemonStop()
    case 'logs':
      return daemonLogs(rest)
    default:
      console.error(`  unknown daemon subcommand: ${sub}`)
      printHelp()
      peachExit(1)
  }
}

function printHelp() {
  printCommandHelp('daemon')
}

// --- resolve sootsim binary ----------------------------------------------

// launchd and systemd run agents with a stripped PATH (basically just
// /usr/bin:/bin:/usr/sbin:/sbin), so anything that depends on PATH resolution
// never starts. rnxSelfInvocation() answers with absolute paths for both CLI
// shapes; resolve symlinks on the entry script so the service spawns the real
// file rather than a bin shim that would itself need PATH.
function resolveDaemonInvocation(): RnxSelfInvocation {
  const invocation = rnxSelfInvocation()
  return {
    executable: invocation.executable,
    prefixArgs: invocation.prefixArgs.map(realPathOrSelf),
  }
}

function realPathOrSelf(p: string): string {
  try {
    return realpathSync(p)
  } catch {
    return p
  }
}

// --- plist / unit generation ---------------------------------------------

function renderPlist(invocation: RnxSelfInvocation, port: number): string {
  mkdirSync(LOG_DIR, { recursive: true })
  const stdout = resolve(LOG_DIR, 'bridge.out.log')
  const stderr = resolve(LOG_DIR, 'bridge.err.log')
  // launchd points at the .app launcher (which exec's the real invocation
  // in place) rather than at bun/node directly, so Login Items reads the
  // bundle's CFBundleDisplayName instead of bun's signer identity.
  const { launcherPath } = ensureDaemonApp(invocation, port, { stdout, stderr })
  const programArgs = `    <string>${escapeXml(launcherPath)}</string>`
  return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>${SERVICE_LABEL_MAC}</string>
  <key>ProgramArguments</key>
  <array>
${programArgs}
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>ThrottleInterval</key><integer>${RESPAWN_THROTTLE_SECONDS}</integer>
  <key>ProcessType</key><string>Interactive</string>
  <key>StandardOutPath</key><string>${stdout}</string>
  <key>StandardErrorPath</key><string>${stderr}</string>
</dict>
</plist>
`
}

function renderSystemdUnit(invocation: RnxSelfInvocation, port: number): string {
  mkdirSync(LOG_DIR_LINUX, { recursive: true })
  const exec = [invocation.executable, ...invocation.prefixArgs].map(shellQuote).join(' ')
  const environment = DAEMON_ENVIRONMENT.filter((key) => process.env[key])
    .map((key) => `Environment=${shellQuote(`${key}=${process.env[key]}`)}\n`)
    .join('')
  return `[Unit]
Description=peach bridge daemon
After=default.target

[Service]
Type=simple
${environment}ExecStart=${exec} serve --quiet --port ${port}
Restart=always
RestartSec=${RESPAWN_THROTTLE_SECONDS}

[Install]
WantedBy=default.target
`
}

function shellQuote(value: string): string {
  return /[^\w@%+=:,./-]/.test(value) ? `'${value.replace(/'/g, `'\\''`)}'` : value
}

// --- platform paths ------------------------------------------------------

function macPlistPath(): string {
  return resolve(homedir(), 'Library/LaunchAgents', `${SERVICE_LABEL_MAC}.plist`)
}

function macLegacyPlistPath(userHome = homedir()): string {
  return resolve(userHome, 'Library/LaunchAgents', `${LEGACY_SERVICE_LABEL_MAC}.plist`)
}

function linuxUnitPath(): string {
  return resolve(homedir(), '.config/systemd/user', `${SERVICE_NAME_LINUX}.service`)
}

// --- subcommands ---------------------------------------------------------

export interface DaemonServiceStatus {
  supported: boolean
  installed: boolean
  path?: string
}

export function getDaemonServiceStatus(): DaemonServiceStatus {
  if (shouldSkipPersistentDaemon()) return { supported: false, installed: false }
  if (process.platform === 'darwin') {
    const path = macPlistPath()
    return { supported: true, installed: existsSync(path), path }
  }
  if (process.platform === 'linux') {
    const path = linuxUnitPath()
    return { supported: linuxUserManagerReachable(), installed: existsSync(path), path }
  }
  return { supported: false, installed: false }
}

// systemctl --user reaches the user's systemd manager through this socket; a
// container, WSL without systemd or a login with no user session has none.
function linuxUserManagerReachable(): boolean {
  const runtime = process.env.XDG_RUNTIME_DIR
  return runtime ? existsSync(resolve(runtime, 'systemd/private')) : false
}

export async function daemonInstall({ port, force }: { port: number; force: boolean }) {
  if (shouldSkipPersistentDaemon()) {
    throw new Error('background daemon setup is unavailable in this environment')
  }
  if (process.platform === 'linux' && !linuxUserManagerReachable()) {
    throw new Error(
      'background daemon setup is unavailable in this environment: no systemd user manager answers this session',
    )
  }

  const invocation = resolveDaemonInvocation()
  console.log(`  binary: ${[invocation.executable, ...invocation.prefixArgs].join(' ')}`)
  console.log(`  port:   ${port}`)

  if (process.platform === 'darwin') {
    // a launchd-spawned executable on an external volume stalls in dyld: the
    // process spawns, never binds and never exits. only the executable is
    // observed to stall, so scripts and peach home are not checked.
    if (realPathOrSelf(invocation.executable).startsWith('/Volumes/')) {
      throw new Error(
        `${invocation.executable} is on an external volume, which the background service cannot load. install ${rnxPublicBrand.commandName} on the startup disk, then run \`${rnxPublicBrand.commandName} daemon install\` again`,
      )
    }
    const legacy = teardownLegacyMacDaemonArtifacts()
    if (!legacy.missing) {
      console.log(`  removed legacy ${LEGACY_SERVICE_LABEL_MAC} service`)
    }
    const path = macPlistPath()
    if (existsSync(path) && !force) {
      console.log(`  already installed at ${path}`)
      const pid = await startMacDaemon(path)
      console.log(`  registered (state: running, pid ${pid})`)
      console.log(`  pass --force to overwrite the service configuration`)
      return
    }
    await stopMacDaemonBridge(invocation)
    mkdirSync(dirname(path), { recursive: true })
    writeFileSync(path, renderPlist(invocation, port))
    console.log(`  wrote ${path}`)
    const pid = await startMacDaemon(path)
    console.log(
      `  registered (state: running, pid ${pid}, log: ${resolve(LOG_DIR, 'bridge.err.log')})`,
    )
    return
  }

  if (process.platform === 'linux') {
    const path = linuxUnitPath()
    if (existsSync(path) && !force) {
      console.log(`  already installed at ${path}`)
      console.log(`  pass --force to overwrite the service configuration`)
    } else {
      mkdirSync(dirname(path), { recursive: true })
      writeFileSync(path, renderSystemdUnit(invocation, port))
      console.log(`  wrote ${path}`)
    }

    const reload = spawnSync('systemctl', ['--user', 'daemon-reload'], {
      stdio: 'pipe',
      encoding: 'utf8',
    })
    if (reload.status !== 0) {
      const msg = (reload.stderr || reload.stdout || '').trim()
      throw new Error(`systemctl daemon-reload failed${msg ? `: ${msg}` : ''}`)
    }
    const enable = spawnSync(
      'systemctl',
      ['--user', 'enable', '--now', SERVICE_NAME_LINUX],
      { stdio: 'pipe', encoding: 'utf8' },
    )
    if (enable.status !== 0) {
      const msg = (enable.stderr || enable.stdout || '').trim()
      throw new Error(
        `systemctl enable --now failed${msg ? `: ${msg}` : ''}` +
          ` — try \`peach daemon uninstall\` then retry.`,
      )
    }
    const isActive = spawnSync('systemctl', ['--user', 'is-active', SERVICE_NAME_LINUX], {
      encoding: 'utf8',
    })
    const state = (isActive.stdout || '').trim() || 'unknown'
    console.log(
      `  registered (state: ${state}, journalctl --user -u ${SERVICE_NAME_LINUX} to tail logs)`,
    )

    // user-scope systemd units are killed when the user's last session ends.
    // on most distros the daemon then disappears at logout — the unit is
    // "active" until you log off, then silently dead, and `peach` looks
    // broken when you ssh back in. `loginctl enable-linger` keeps the user
    // bus alive across sessions, which is what every other long-running
    // user agent (gpg-agent, ssh-agent --systemd) also relies on.
    //
    // orb's default user is already lingered (orb seeds it); multipass and
    // lima fresh users are not. probing `loginctl show-user --property=Linger`
    // tells us whether to nudge the user — running enable-linger ourselves
    // requires root (`loginctl enable-linger` invokes a polkit action that
    // typically needs sudo from a non-root user), so we just print the
    // one-liner instead of trying to escalate ourselves.
    try {
      const username = process.env.USER || process.env.LOGNAME || ''
      if (username) {
        const linger = spawnSync(
          'loginctl',
          ['show-user', username, '--property=Linger', '--value'],
          { encoding: 'utf8' },
        )
        const lingerEnabled = (linger.stdout || '').trim().toLowerCase() === 'yes'
        if (!lingerEnabled && linger.status === 0) {
          console.log(
            `  note: linger is not enabled for "${username}". the daemon will exit at logout.\n` +
              `  enable persistence with: sudo loginctl enable-linger ${username}`,
          )
        }
      }
    } catch {
      // loginctl missing or non-systemd init — silent; the daemon still works
      // for the current session even without lingering.
    }
    return
  }

  console.error(`  background daemon is not supported on ${process.platform}`)
  console.error(`  run 'peach serve' in a persistent shell instead`)
  peachExit(1)
}

function macServiceTarget(): string {
  return `gui/${process.getuid!()}/${SERVICE_LABEL_MAC}`
}

function readMacDaemonState(
  target = macServiceTarget(),
): { state: string; pid: number | null } | null {
  const result = spawnSync('launchctl', ['print', target], {
    encoding: 'utf8',
  })
  if (result.status !== 0) return null
  const pid = Number(result.stdout.match(/pid\s*=\s*(\d+)/)?.[1])
  return {
    state: result.stdout.match(/state\s*=\s*(\w+)/)?.[1] ?? 'unknown',
    pid: pid > 0 ? pid : null,
  }
}

function runLaunchctl(args: string[]): void {
  const result = spawnSync('launchctl', args, { encoding: 'utf8' })
  if (result.status !== 0) {
    const detail = (result.stderr || result.stdout).trim() || result.error?.message
    throw new Error(
      `launchctl ${args[0]} failed (exit ${result.status}, signal ${result.signal ?? 'none'})${detail ? `: ${detail}` : ''}`,
    )
  }
}

function macBridgeHasListener(pid: number, port: number): boolean {
  const result = spawnSync(
    LSOF,
    ['-nP', '-a', '-p', String(pid), `-iTCP:${port}`, '-sTCP:LISTEN', '-t'],
    { encoding: 'utf8' },
  )
  if (result.status === 1 && !result.stderr.trim()) return false
  if (result.status !== 0) {
    throw new Error(
      `cannot inspect bridge pid ${pid}: ${result.error?.message ?? result.stderr.trim()}`,
    )
  }
  return result.stdout.trim() === String(pid)
}

// a process runs this invocation's `serve` when its executable is the same
// file and its arguments start with the entry script and `serve`. argv[0] is
// spelled however the spawner named the file (a symlinked /tmp, a bin shim,
// a relative path) while process.execPath is resolved, so the executable is
// compared by device and inode, never by path text. inodes on the system
// volume exceed 2^53, so both compare as bigints. `peach upgrade` renames a
// new file over the executable, so a bridge the previous version started maps
// the old inode; it still runs this invocation when the path it was launched
// from now names this executable.
function sameFile(path: string, device: bigint, inode: bigint): boolean {
  try {
    const stats = statSync(path, { bigint: true })
    return stats.dev === device && stats.ino === inode
  } catch {
    return false
  }
}

function serveArgs(invocation: RnxSelfInvocation): string[] {
  return [...invocation.prefixArgs, 'serve']
}

function macProcessRunsServe(pid: number, invocation: RnxSelfInvocation): boolean {
  const launch = macProcessArgs(pid)
  if (
    launch === null ||
    !serveArgs(invocation).every((arg, index) => launch.args[index + 1] === arg)
  )
    return false
  if (launch.executable.startsWith('/') && sameExecutable(invocation, launch.executable))
    return true
  // lsof names each mapped text file by device and inode; the executable is one.
  const files = spawnSync(LSOF, ['-nP', '-a', '-p', String(pid), '-d', 'txt', '-FDi'], {
    encoding: 'utf8',
  })
  let device = -1n
  let runsExecutable = false
  for (const line of files.stdout.split('\n')) {
    if (line.startsWith('D')) device = BigInt(line.slice(1))
    else if (
      line.startsWith('i') &&
      sameFile(invocation.executable, device, BigInt(line.slice(1)))
    )
      runsExecutable = true
  }
  return runsExecutable
}

function sameExecutable(invocation: RnxSelfInvocation, path: string): boolean {
  try {
    const stats = statSync(path, { bigint: true })
    return sameFile(invocation.executable, stats.dev, stats.ino)
  } catch {
    return false
  }
}

// the kernel's exact argv vector (KERN_PROCARGS2: argc, executable path, then
// argc NUL-terminated arguments), read through the system JXA Foundation
// bridge. `ps` flattens argv with spaces and cannot recover argument
// boundaries.
function macProcessArgs(pid: number): { executable: string; args: string[] } | null {
  const int32 = (value: number) => {
    const bytes = Buffer.alloc(4)
    bytes.writeUInt32LE(value)
    return bytes
  }
  const capacity = 1 << 20 // ARG_MAX
  const mib = Buffer.concat([int32(1), int32(49), int32(pid)]).toString('base64')
  const size = Buffer.alloc(8)
  size.writeBigUInt64LE(BigInt(capacity))
  const script = `
ObjC.import('Foundation');
ObjC.bindFunction('sysctl', ['int', ['void *', 'unsigned int', 'void *', 'void *', 'void *', 'unsigned long']]);
const mib = $.NSData.alloc.initWithBase64EncodedStringOptions(${JSON.stringify(mib)}, 0).mutableCopy;
const size = $.NSData.alloc.initWithBase64EncodedStringOptions(${JSON.stringify(size.toString('base64'))}, 0).mutableCopy;
const out = $.NSMutableData.dataWithLength(${capacity});
if ($.sysctl(mib.mutableBytes, 3, out.mutableBytes, size.mutableBytes, null, 0) !== 0)
  throw new Error('sysctl KERN_PROCARGS2 failed');
ObjC.unwrap(size.base64EncodedStringWithOptions(0)) + ' ' + ObjC.unwrap(out.base64EncodedStringWithOptions(0));
`
  // runner-toolchain-platform: darwin
  const result = spawnSync('/usr/bin/osascript', ['-l', 'JavaScript', '-e', script], {
    encoding: 'utf8',
    maxBuffer: 4 * capacity,
  })
  if (result.status !== 0) return null
  const [length, data] = result.stdout.trim().split(' ')
  const buffer = Buffer.from(data, 'base64').subarray(
    0,
    Number(Buffer.from(length, 'base64').readBigUInt64LE()),
  )
  const argc = buffer.readInt32LE(0)
  const executable = buffer.toString('utf8', 4, buffer.indexOf(0, 4))
  let at = buffer.indexOf(0, 4) // end of the executable path
  while (buffer[at] === 0) at++ // padding before argv[0]
  const args: string[] = []
  for (; args.length < argc; at = buffer.indexOf(0, at) + 1)
    args.push(buffer.toString('utf8', at, buffer.indexOf(0, at)))
  return { executable, args }
}

export async function stopMacDaemonBridge(
  invocation: RnxSelfInvocation,
  target: string | null = macServiceTarget(),
): Promise<void> {
  const service = target === null ? null : readMacDaemonState(target)
  const lock = readDaemonLockfile()
  if (isDaemonLockfileFresh(lock) && lock.pid !== service?.pid) {
    // a lockfile alone cannot authorize a signal after pid reuse.
    if (
      !macBridgeHasListener(lock.pid, lock.bridgePort) ||
      !macProcessRunsServe(lock.pid, invocation)
    ) {
      throw new Error(
        `cannot hand off bridge on port ${lock.bridgePort}: pid ${lock.pid} is not this Peach invocation`,
      )
    }
    process.kill(lock.pid, 'SIGTERM')
  }
  if (service && target !== null) runLaunchctl(['bootout', target])
  if (!lock) return
  const deadline = Date.now() + 4000
  while (Date.now() < deadline) {
    if (!macBridgeHasListener(lock.pid, lock.bridgePort)) return
    await new Promise((resolve) => setTimeout(resolve, 100))
  }
  throw new Error(`bridge pid ${lock.pid} did not release port ${lock.bridgePort}`)
}

export async function startMacDaemon(
  path: string,
  invocation = resolveDaemonInvocation(),
  target = macServiceTarget(),
): Promise<number> {
  const service = readMacDaemonState(target)
  const lock = readDaemonLockfile()
  if (
    service?.state === 'running' &&
    service.pid !== null &&
    isDaemonLockfileFresh(lock) &&
    lock.pid === service.pid &&
    macBridgeHasListener(lock.pid, lock.bridgePort)
  )
    return service.pid
  // reconcile an unloaded service or a bare bridge before launchd can create
  // another process. start is idempotent when the service already owns the bridge.
  await stopMacDaemonBridge(invocation, target)
  runLaunchctl(['bootstrap', target.slice(0, target.lastIndexOf('/')), path])
  // registration and an xpcproxy pid precede the actual bridge bind.
  const deadline = Date.now() + 4000
  while (Date.now() < deadline) {
    const service = readMacDaemonState(target)
    const lock = readDaemonLockfile()
    if (
      service?.state === 'running' &&
      service.pid !== null &&
      isDaemonLockfileFresh(lock) &&
      lock.pid === service.pid &&
      macBridgeHasListener(lock.pid, lock.bridgePort)
    )
      return service.pid
    await new Promise((resolve) => setTimeout(resolve, 100))
  }
  throw new Error(
    `daemon registered but did not own a responding bridge within 4s. check ${resolve(LOG_DIR, 'bridge.err.log')}`,
  )
}

// --- linux bridge ownership --------------------------------------------

// the linux counterparts to the mac listener and executable checks above. both
// read /proc directly instead of shelling out to lsof, ss or ps, so minimal
// containers and fresh users get the same ownership proof with no extra
// binaries installed.

function linuxBridgeHasListener(pid: number, port: number): boolean {
  let fds: string[]
  try {
    fds = readdirSync(`/proc/${pid}/fd`)
  } catch {
    return false
  }
  const sockets = new Set<string>()
  for (const fd of fds) {
    try {
      const inode = readlinkSync(`/proc/${pid}/fd/${fd}`).match(/^socket:\[(\d+)\]$/)?.[1]
      if (inode) sockets.add(inode)
    } catch {
      // the fd closed between listing and read; skip it.
    }
  }
  if (sockets.size === 0) return false
  const hexPort = port.toString(16).toUpperCase().padStart(4, '0')
  for (const table of ['/proc/net/tcp', '/proc/net/tcp6']) {
    let body: string
    try {
      body = readFileSync(table, 'utf8')
    } catch {
      continue
    }
    const lines = body.split('\n')
    for (let i = 1; i < lines.length; i++) {
      const cols = lines[i].trim().split(/\s+/)
      if (cols.length < 10) continue
      if (cols[3] !== '0A') continue
      if (!cols[1].endsWith(`:${hexPort}`)) continue
      if (sockets.has(cols[9])) return true
    }
  }
  return false
}

function linuxProcessRunsServe(pid: number, invocation: RnxSelfInvocation): boolean {
  // /proc/<pid>/exe resolves to the running executable and cmdline is the argv
  // vector verbatim, so both compare exactly without procps installed.
  try {
    const exe = statSync(`/proc/${pid}/exe`, { bigint: true })
    const launchedFrom = readlinkSync(`/proc/${pid}/exe`).replace(/ \(deleted\)$/, '')
    if (
      !sameFile(invocation.executable, exe.dev, exe.ino) &&
      !sameExecutable(invocation, launchedFrom)
    )
      return false
    const args = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').slice(1)
    return serveArgs(invocation).every((arg, index) => args[index] === arg)
  } catch {
    return false
  }
}

export async function stopLinuxDaemonBridge(
  invocation: RnxSelfInvocation,
  registered: boolean,
): Promise<void> {
  if (registered) {
    const res = spawnSync('systemctl', ['--user', 'stop', SERVICE_NAME_LINUX], {
      stdio: 'pipe',
      encoding: 'utf8',
    })
    if (res.status !== 0) {
      console.error(`  stop failed: ${res.stderr?.trim()}`)
      peachExit(1)
    }
    return
  }
  const lock = readDaemonLockfile()
  if (!isDaemonLockfileFresh(lock)) return
  // a lockfile alone cannot authorize a signal after pid reuse.
  if (
    !linuxBridgeHasListener(lock.pid, lock.bridgePort) ||
    !linuxProcessRunsServe(lock.pid, invocation)
  ) {
    throw new Error(
      `cannot hand off bridge on port ${lock.bridgePort}: pid ${lock.pid} is not this Peach invocation`,
    )
  }
  process.kill(lock.pid, 'SIGTERM')
  const deadline = Date.now() + 4000
  while (Date.now() < deadline) {
    if (!linuxBridgeHasListener(lock.pid, lock.bridgePort)) return
    await new Promise((resolve) => setTimeout(resolve, 100))
  }
  throw new Error(`bridge pid ${lock.pid} did not release port ${lock.bridgePort}`)
}

// removed-path log (idempotent helpers track what they actually touched so the
// caller can report a unified "not installed" / "removed N entries" line).
type TeardownReport = { removed: string[]; missing: boolean }

export function teardownLegacyMacDaemonArtifacts(
  options: {
    userHome?: string
    launchTarget?: string
    bootout?: (target: string) => void
  } = {},
): TeardownReport {
  const userHome = options.userHome ?? homedir()
  const plist = macLegacyPlistPath(userHome)
  const logDir = resolve(userHome, 'Library/Logs/sootsim')
  const removed: string[] = []
  if (existsSync(plist)) {
    const target = `${
      options.launchTarget ?? `gui/${process.getuid?.() ?? 0}`
    }/${LEGACY_SERVICE_LABEL_MAC}`
    const bootout =
      options.bootout ??
      ((serviceTarget: string) => {
        spawnSync('launchctl', ['bootout', serviceTarget], { stdio: 'ignore' })
      })
    bootout(target)
    rmSync(plist, { force: true })
    removed.push(plist)
  }
  for (const name of ['server.err.log', 'server.out.log']) {
    const log = resolve(logDir, name)
    if (!existsSync(log)) continue
    rmSync(log, { force: true })
    removed.push(log)
  }
  return { removed, missing: removed.length === 0 }
}

/** stop + disable + remove the persistent launchd / systemd registration
 *  and its support files (mac .app bundle, log dir). does NOT touch user
 *  data under ~/.peach. idempotent: each entry is checked before remove. */
export function teardownDaemonService(): TeardownReport {
  const removed: string[] = []
  if (process.platform === 'darwin') {
    const legacy = teardownLegacyMacDaemonArtifacts()
    removed.push(...legacy.removed)
    const plist = macPlistPath()
    if (existsSync(plist)) {
      spawnSync(
        'launchctl',
        ['bootout', `gui/${process.getuid!()}/${SERVICE_LABEL_MAC}`],
        { stdio: 'ignore' },
      )
      rmSync(plist, { force: true })
      removed.push(plist)
    }
    // daemon-app holds only the generated .app launcher, so the whole
    // directory goes with the service.
    const appDir = daemonAppDir()
    if (existsSync(appDir)) {
      rmSync(appDir, { recursive: true, force: true })
      removed.push(appDir)
    }
    if (existsSync(LOG_DIR)) {
      rmSync(LOG_DIR, { recursive: true, force: true })
      removed.push(LOG_DIR)
    }
    return { removed, missing: removed.length === 0 }
  }
  if (process.platform === 'linux') {
    const unit = linuxUnitPath()
    if (existsSync(unit)) {
      // `disable --now` stops + disables in one call. ignore exit status: a
      // unit whose ExecStart no longer exists can return non-zero while
      // still successfully disabling the unit.
      spawnSync('systemctl', ['--user', 'disable', '--now', SERVICE_NAME_LINUX], {
        stdio: 'ignore',
      })
      rmSync(unit, { force: true })
      spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' })
      // reset-failed clears the "failed" state that lingers in systemd when
      // the unit exited with a missing ExecStart, otherwise `systemctl --user
      // status sootsim-daemon` keeps showing failed even after the unit file
      // is gone.
      spawnSync('systemctl', ['--user', 'reset-failed', SERVICE_NAME_LINUX], {
        stdio: 'ignore',
      })
      removed.push(unit)
    }
    if (existsSync(LOG_DIR_LINUX)) {
      rmSync(LOG_DIR_LINUX, { recursive: true, force: true })
      removed.push(LOG_DIR_LINUX)
    }
    return { removed, missing: removed.length === 0 }
  }
  // win + others: no persistent daemon mechanism yet; nothing to tear down.
  return { removed, missing: true }
}

/** remove EVERYTHING under ~/.peach: installed runtimes, electron support,
 *  device profiles and their app storage, live dev-bridge state, lockfile,
 *  and config. only `peach daemon uninstall --purge` calls this, because a
 *  user who asked to remove a background service did not ask to lose the
 *  simulators they have been working in. idempotent. honors $PEACH_HOME. */
export function teardownRnxHome(): TeardownReport {
  const removed: string[] = []
  const home = rnxHomeDir()
  unregisterNativeDesktopLinks()
  if (existsSync(home)) {
    rmSync(home, { recursive: true, force: true })
    removed.push(home)
  }
  return { removed, missing: removed.length === 0 }
}

// `uninstall` removes the background service and nothing else. device
// profiles, their app storage, and live dev-bridge state belong to simulators
// the user may still be working in, so deleting them is something you ask for
// by name with `--purge`.
async function daemonUninstall(rest: string[]) {
  const unknown = rest.filter((arg) => arg !== '--purge')
  if (unknown.length > 0) {
    console.error(`  unknown daemon uninstall option: ${unknown[0]}`)
    printHelp()
    peachExit(1)
    return
  }
  const purge = rest.includes('--purge')

  const service = teardownDaemonService()
  for (const path of service.removed) console.log(`  removed ${path}`)

  if (!purge) {
    if (service.missing) console.log('  not installed')
    const home = rnxHomeDir()
    if (existsSync(home)) {
      console.log(`  kept ${home} (runtimes, device profiles, open simulators)`)
      console.log(
        `  remove that too with \`${rnxPublicBrand.commandName} daemon uninstall --purge\``,
      )
    }
    return
  }

  const home = teardownRnxHome()
  for (const path of home.removed) console.log(`  removed ${path}`)
  if (service.missing && home.missing) console.log('  not installed')
}

// the service manager's own word is not proof the bridge works: a daemon that
// crashes on start reads as `active` all through systemd's restart backoff,
// which is how a fully broken daemon reported healthy on the 2026-08-19 drive.
// the lockfile carries a pid and a heartbeat, so it answers the question the
// caller actually asked.
function printBridgeLiveness(expectedPid?: number | null) {
  const lock = readDaemonLockfile()
  if (isDaemonLockfileFresh(lock)) {
    if (expectedPid !== undefined && lock.pid !== expectedPid) {
      console.log(
        `  bridge:    port ${lock.bridgePort} is served by pid ${lock.pid}, outside the registered daemon`,
      )
      return
    }
    console.log(`  bridge:    responding on port ${lock.bridgePort} (pid ${lock.pid})`)
    return
  }
  console.log(
    lock
      ? '  bridge:    NOT responding — stale lockfile; check `peach daemon logs`'
      : '  bridge:    NOT responding — no lockfile; check `peach daemon logs`',
  )
}

async function daemonStatus() {
  if (process.platform === 'darwin') {
    const path = macPlistPath()
    if (!existsSync(path)) {
      console.log(`  installed: no`)
      return
    }
    console.log(`  installed: yes  (${path})`)
    const binary = readPlistBinary(path)
    if (binary) console.log(`  binary:    ${binary}`)
    const service = readMacDaemonState()
    console.log(
      service
        ? `  state:     ${service.state}${service.pid ? ` (pid ${service.pid})` : ''}`
        : '  state:     not running',
    )
    printBridgeLiveness(service?.pid ?? null)
    return
  }
  if (process.platform === 'linux') {
    const path = linuxUnitPath()
    if (!existsSync(path)) {
      console.log(`  installed: no`)
      return
    }
    console.log(`  installed: yes  (${path})`)
    const res = spawnSync('systemctl', ['--user', 'is-active', SERVICE_NAME_LINUX], {
      encoding: 'utf8',
    })
    console.log(`  state:     ${res.stdout.trim() || 'unknown'}`)
    printBridgeLiveness()
    return
  }
  console.error(`  unsupported platform: ${process.platform}`)
  peachExit(1)
}

// hands off an idle bridge that an older cli left running, so the next start
// serves the current cli's routes. a service-managed bridge restarts through
// its service; a bare bridge gets SIGTERM only when its pid still owns the
// lockfile's listening port, since a lockfile alone cannot authorize a signal.
// its sims and files are untouched: the caller proves the bridge idle first.
export async function retireIdleBridge(lock: DaemonLockfile): Promise<void> {
  if (process.platform === 'darwin') {
    const service = existsSync(macPlistPath())
      ? readMacDaemonState(macServiceTarget())
      : null
    if (service?.pid === lock.pid) return daemonRestart()
    if (!macBridgeHasListener(lock.pid, lock.bridgePort)) return
    process.kill(lock.pid, 'SIGTERM')
    return waitForBridgeRelease(macBridgeHasListener, lock)
  }
  if (process.platform === 'linux') {
    const mainPid = spawnSync(
      'systemctl',
      ['--user', 'show', SERVICE_NAME_LINUX, '-p', 'MainPID', '--value'],
      { encoding: 'utf8' },
    ).stdout.trim()
    if (mainPid === String(lock.pid)) return daemonRestart()
    if (!linuxBridgeHasListener(lock.pid, lock.bridgePort)) return
    process.kill(lock.pid, 'SIGTERM')
    return waitForBridgeRelease(linuxBridgeHasListener, lock)
  }
}

async function waitForBridgeRelease(
  hasListener: (pid: number, port: number) => boolean,
  lock: DaemonLockfile,
): Promise<void> {
  const deadline = Date.now() + 4000
  while (Date.now() < deadline) {
    if (!hasListener(lock.pid, lock.bridgePort)) return
    await new Promise((resolve) => setTimeout(resolve, 100))
  }
  throw new Error(`bridge pid ${lock.pid} did not release port ${lock.bridgePort}`)
}

async function daemonRestart() {
  if (process.platform === 'darwin') {
    const path = macPlistPath()
    if (!existsSync(path)) {
      console.error('  daemon not registered. run `peach daemon install`')
      peachExit(1)
    }
    await stopMacDaemonBridge(resolveDaemonInvocation())
    await startMacDaemon(path)
    console.log('  restarted')
    return
  }
  if (process.platform === 'linux') {
    const path = linuxUnitPath()
    if (!existsSync(path)) {
      console.error('  daemon not registered. run `peach daemon install`')
      peachExit(1)
    }
    const res = spawnSync('systemctl', ['--user', 'restart', SERVICE_NAME_LINUX], {
      stdio: 'pipe',
      encoding: 'utf8',
    })
    if (res.status !== 0) {
      console.error(`  restart failed: ${res.stderr?.trim()}`)
      peachExit(1)
    }
    console.log('  restarted')
    return
  }
  console.error(`  unsupported platform: ${process.platform}`)
  peachExit(1)
}

async function daemonStart() {
  if (process.platform === 'darwin') {
    const path = macPlistPath()
    if (!existsSync(path)) {
      console.error('  daemon not registered. run `peach daemon install`')
      peachExit(1)
    }
    await startMacDaemon(path)
    console.log('  started')
    return
  }
  if (process.platform === 'linux') {
    const path = linuxUnitPath()
    if (!existsSync(path)) {
      console.error('  daemon not registered. run `peach daemon install`')
      peachExit(1)
    }
    const res = spawnSync('systemctl', ['--user', 'start', SERVICE_NAME_LINUX], {
      stdio: 'pipe',
      encoding: 'utf8',
    })
    if (res.status !== 0) {
      console.error(`  start failed: ${res.stderr?.trim()}`)
      peachExit(1)
    }
    console.log('  started')
    return
  }
  console.error(`  unsupported platform: ${process.platform}`)
  peachExit(1)
}

async function daemonStop() {
  if (process.platform === 'darwin') {
    const path = macPlistPath()
    const registered = existsSync(path)
    if (!registered && !isDaemonLockfileFresh(readDaemonLockfile())) {
      console.error('  daemon not registered — nothing to stop')
      peachExit(1)
    }
    await stopMacDaemonBridge(
      resolveDaemonInvocation(),
      registered ? macServiceTarget() : null,
    )
    console.log('  stopped')
    return
  }
  if (process.platform === 'linux') {
    const path = linuxUnitPath()
    const registered = existsSync(path)
    if (!registered && !isDaemonLockfileFresh(readDaemonLockfile())) {
      console.error('  daemon not registered — nothing to stop')
      peachExit(1)
    }
    await stopLinuxDaemonBridge(resolveDaemonInvocation(), registered)
    console.log('  stopped')
    return
  }
  console.error(`  unsupported platform: ${process.platform}`)
  peachExit(1)
}

// tail the daemon's logs. macOS reads the launchd-redirected files directly
// (works for any user); linux reads the systemd journal. journalctl --user
// fails for a freshly-created user not yet in the systemd-journal/adm group
// ("No journal files were opened due to insufficient permissions"), so on that
// error we retry the system-scoped query and, failing that, point the user at
// the sudo form rather than printing a cryptic permission error.
async function daemonLogs(rest: string[]) {
  const linesArg = rest.find((a) => /^-n\d+$|^--lines=\d+$|^\d+$/.test(a))
  const lines = linesArg ? Number(linesArg.replace(/\D/g, '')) : 200
  const follow = rest.includes('-f') || rest.includes('--follow')

  if (process.platform === 'darwin') {
    const out = resolve(LOG_DIR, 'bridge.out.log')
    const err = resolve(LOG_DIR, 'bridge.err.log')
    const present = [out, err].filter((p) => existsSync(p))
    if (present.length === 0) {
      console.error(`  no daemon logs yet at ${LOG_DIR}. run \`peach daemon install\``)
      peachExit(1)
    }
    const args = follow
      ? ['-n', String(lines), '-F', ...present]
      : ['-n', String(lines), ...present]
    spawnSync('tail', args, { stdio: 'inherit' })
    return
  }

  if (process.platform === 'linux') {
    const unit = `${SERVICE_NAME_LINUX}.service`
    const base = ['--user', '-u', unit, '-n', String(lines), '--no-pager']
    const res = spawnSync('journalctl', follow ? [...base, '-f'] : base, {
      encoding: 'utf8',
      stdio: follow ? 'inherit' : 'pipe',
    })
    if (follow) return
    const combined = `${res.stdout || ''}${res.stderr || ''}`
    const blocked = /insufficient permissions|No journal files were opened/i.test(
      combined,
    )
    if (res.status === 0 && !blocked) {
      process.stdout.write(res.stdout || '')
      return
    }
    // fresh-user fallback: the system journal holds the user-unit logs even when
    // the user can't read --user scope. try it, then fall back to guidance.
    const sys = spawnSync(
      'journalctl',
      [`_SYSTEMD_USER_UNIT=${unit}`, '-n', String(lines), '--no-pager'],
      { encoding: 'utf8' },
    )
    if (sys.status === 0 && (sys.stdout || '').trim()) {
      process.stdout.write(sys.stdout)
      return
    }
    console.error(
      `  could not read --user journal for ${unit} (this user isn't in the systemd-journal group yet).\n` +
        `  run:  sudo journalctl _SYSTEMD_USER_UNIT=${unit} -n ${lines} --no-pager`,
    )
    peachExit(1)
  }

  console.error(`  unsupported platform: ${process.platform}`)
  peachExit(1)
}

function readPlistBinary(path: string): string | null {
  try {
    const body = readFileSync(path, 'utf8')
    const match = body.match(/<array>\s*<string>([^<]+)<\/string>/)
    return match?.[1] || null
  } catch {
    return null
  }
}
