import { execSync } from 'child_process'; import { isRoot } from './platform.js'; import type { ServiceDef } from './service-defs.js'; export type ServiceStatus = | 'running' | 'stopped' | 'not_found' | 'not_configured'; export interface ServiceCheck { name: string; status: ServiceStatus; } export type SystemdScope = 'system' | 'user'; export function checkSystemdServiceInScope( name: string, scope: SystemdScope, ): ServiceStatus { const prefix = scope === 'system' ? 'systemctl' : 'systemctl --user'; try { execSync(`${prefix} is-active ${name}`, { stdio: 'ignore' }); return 'running'; } catch { try { const output = execSync(`${prefix} list-unit-files`, { encoding: 'utf-8', }); if (output.includes(name)) { return 'stopped'; } } catch { // systemctl not available } } return 'not_found'; } export function checkSystemdService(name: string): ServiceStatus { return checkSystemdServiceInScope(name, isRoot() ? 'system' : 'user'); } export function checkService( serviceManager: 'systemd' | 'none', serviceName: string, ): ServiceStatus { if (serviceManager === 'systemd') { return checkSystemdService(serviceName); } return 'not_found'; } export function getServiceChecks( serviceDefs: ServiceDef[], serviceManager: 'systemd' | 'none', ): ServiceCheck[] { return serviceDefs.map((def) => ({ name: def.name, status: checkService(serviceManager, def.name), })); }