/** * Which version of the agent each server runs, and which version this Homelab Manager would give a new install. An agent is a copy of * a script that was served at install time, so after the app is updated the agents out on the servers can be behind. Each script carries * its version as a number (`AGENT_VERSION=2` / `$script:AgentVersion = 2`), says it in every report, and the "latest" is read from the very * scripts this app serves — so the two can never disagree about what "current" means. * * 1 — before the number was reported (so an agent that says nothing is version 1) * 2 — reports pending updates, and its own version */ import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; export type AgentOs = "linux" | "windows"; export interface LatestAgentVersions { linux: number | null; windows: number | null; } // server/src/services → the repository's agent folder (the same place the app serves /agent from; in the image it sits beside server/dist). const here = dirname(fileURLToPath(import.meta.url)); export const AGENT_DIR = join(here, "..", "..", "..", "agent"); const FILES: Record = { linux: join("linux", "report-tasks.sh"), windows: join("windows", "report-tasks.ps1") }; const PATTERNS: Record = { linux: /^AGENT_VERSION=(\d+)\s*$/m, windows: /^\$script:AgentVersion\s*=\s*(\d+)\s*$/m, }; /** The version a script says it is, or null if it doesn't say. */ export function parseAgentVersion(text: string, os: AgentOs): number | null { const m = PATTERNS[os].exec(text.replace(/\r\n/g, "\n")); return m ? Number(m[1]) : null; } let cached: LatestAgentVersions | null = null; /** What the scripts served from here say. Read once (they don't change while the app runs); null for one that can't be read. */ export function latestAgentVersions(dir: string = AGENT_DIR): LatestAgentVersions { if (cached && dir === AGENT_DIR) return cached; const read = (os: AgentOs): number | null => { try { return parseAgentVersion(readFileSync(join(dir, FILES[os]), "utf8"), os); } catch { return null; } }; const result = { linux: read("linux"), windows: read("windows") }; if (dir === AGENT_DIR) cached = result; return result; } /** * Whether a server's agent is behind. Only a server that reports through an agent can be: one that never has (a Proxmox guest tracked * through its host, say) has none to update. An agent that reports no version is version 1. */ export function isAgentOutdated(row: { osType: string; lastSeenAt: string | null; agentVersion: number | null }, latest: LatestAgentVersions): boolean { if (!row.lastSeenAt) return false; const newest = row.osType === "windows" ? latest.windows : row.osType === "linux" ? latest.linux : null; if (newest === null) return false; return (row.agentVersion ?? 1) < newest; }