/**
 * Linux systemd unit writer — PLAN_RELAY_AGENT T17. Runs as the LOGGED-IN USER (never root,
 * EXPLORE §4d), restart-on-failure; no secrets in the unit (key/cert stay in the keystore).
 */
const UNIT_NAME = 'web-terminal-agent.service'

export function systemdUnitName(): string {
  return UNIT_NAME
}

export function systemdUnitPath(homedir: string): string {
  return `${homedir}/.config/systemd/user/${UNIT_NAME}`
}

/** Build the unit. ExecStart = `<bin> run`; Restart=on-failure; User=<user> (never root). */
export function buildSystemdUnit(binPath: string, user: string): string {
  return [
    '[Unit]',
    'Description=web-terminal host agent (rendezvous relay)',
    'After=network-online.target',
    '',
    '[Service]',
    'Type=simple',
    `ExecStart=${binPath} run`,
    'Restart=on-failure',
    'RestartSec=1',
    `User=${user}`,
    '',
    '[Install]',
    'WantedBy=default.target',
    '',
  ].join('\n')
}

export function systemdEnableCommand(): { cmd: string; args: readonly string[] } {
  return { cmd: 'systemctl', args: ['--user', 'enable', '--now', UNIT_NAME] }
}
export function systemdDisableCommand(): { cmd: string; args: readonly string[] } {
  return { cmd: 'systemctl', args: ['--user', 'disable', '--now', UNIT_NAME] }
}
