Skip to main content

ryra_core/
upgrade.rs

1//! Diff and upgrade flows for already-installed services.
2//!
3//! "Upgrade" means: re-render an installed service's quadlet + configs
4//! against the current registry, replace any files whose content changed,
5//! and restart the unit. The render path is shared with `add_service`
6//! (driven via [`PlanMode::Upgrade`]); the side-effect steps differ.
7//!
8//! Drift detection is grounded in `service.manifest` — the per-install render
9//! manifest written by `ryra add`. Each tracked file is in one of these
10//! states:
11//!
12//! - **Unchanged**: on-disk content matches what the registry would render.
13//! - **Modified**: registry rendered output differs, but on-disk hash still
14//!   matches the manifest, so we know the file is ours and can be safely
15//!   overwritten.
16//! - **Drift**: on-disk hash matches *neither* the manifest nor the planned
17//!   content — i.e. the user hand-edited it. Refused without `--force`.
18//! - **Added**: file is in the planned set but not in the manifest (registry
19//!   added it).
20//! - **Removed**: file is in the manifest but not in the planned set (registry
21//!   stopped shipping it).
22//!
23//! `.env` is excluded throughout: it carries generated secrets that legitimately
24//! drift across restarts, and re-rendering it on upgrade would clobber rotated
25//! credentials. Its absence from the manifest is the source of truth for that.
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::path::PathBuf;
29
30use crate::error::{Error, Result};
31use crate::exposure::Exposure;
32use crate::generate::GeneratedFile;
33use crate::manifest;
34use crate::metadata::load_metadata;
35use crate::registry::resolve::ServiceRef;
36use crate::{
37    AddResult, PlanMode, REGISTRY_BUNDLED, Step, add_service, is_service_installed,
38    resolve_registry_dir, service_home,
39};
40
41/// Per-file diff classification.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum DiffKind {
44    /// On-disk content matches the planned render. Nothing to do.
45    Unchanged,
46    /// Registry now renders different content. On-disk hash still matches
47    /// the manifest, so the file is ryra-owned and safe to overwrite.
48    Modified,
49    /// On-disk hash differs from both the manifest and the planned render —
50    /// the user hand-edited this file. Upgrade refuses without `--force`.
51    /// Includes the case where there is no manifest entry to compare against
52    /// (service installed before the manifest feature; treated conservatively
53    /// as drift until the user confirms with `--force`).
54    Drift,
55    /// File is in the planned render but absent from the manifest — registry
56    /// added it.
57    Added,
58    /// File is in the manifest but no longer rendered by the registry —
59    /// registry stopped shipping it. Upgrade deletes it.
60    Removed,
61}
62
63#[derive(Debug, Clone)]
64pub struct DiffEntry {
65    pub path: PathBuf,
66    pub kind: DiffKind,
67}
68
69/// One env var the registry expects in `.env` that the user's `.env`
70/// doesn't have. By design env tracking is *append-only* — we never flag
71/// a present-but-different value as drift, and we never propose
72/// removing a key. Users may have manually edited values or added their
73/// own keys; clobbering those would be the larger harm.
74///
75/// `kind` and `prompt` come straight from the registry's `EnvVar`
76/// definition, so the CLI can route Prompted / Required additions
77/// through the same interactive prompt that `ryra add` uses, while
78/// silently appending Default ones.
79#[derive(Debug, Clone)]
80pub struct EnvAddition {
81    pub key: String,
82    pub value: String,
83    pub kind: crate::registry::service_def::EnvKind,
84    pub prompt: Option<String>,
85}
86
87/// Result of comparing the registry's render to what's on disk.
88#[derive(Debug, Clone)]
89pub struct DiffResult {
90    pub service: String,
91    pub entries: Vec<DiffEntry>,
92    /// Static env vars the registry expects but the user's `.env` is
93    /// missing. Empty when the `.env` already covers everything tracked.
94    pub env_additions: Vec<EnvAddition>,
95}
96
97impl DiffResult {
98    /// True when nothing about the install would change — neither files
99    /// nor env vars.
100    pub fn is_clean(&self) -> bool {
101        self.entries
102            .iter()
103            .all(|e| matches!(e.kind, DiffKind::Unchanged))
104            && self.env_additions.is_empty()
105    }
106
107    /// Files the user hand-edited. Upgrade must refuse to overwrite these
108    /// without `--force`.
109    pub fn drifted(&self) -> Vec<&DiffEntry> {
110        self.entries
111            .iter()
112            .filter(|e| matches!(e.kind, DiffKind::Drift))
113            .collect()
114    }
115}
116
117/// Reconstruct the planning inputs we stashed at install time and feed them
118/// back through `add_service` in upgrade mode. Returns the planned step
119/// list and the planned-file content map (path → content). The richer
120/// per-env metadata lives on `AddResult.tracked_envs`.
121async fn replan(service_name: &str) -> Result<(AddResult, BTreeMap<PathBuf, String>)> {
122    if !is_service_installed(service_name) {
123        return Err(Error::ServiceNotInstalled(service_name.to_string()));
124    }
125    let metadata = load_metadata(service_name)?
126        .ok_or_else(|| Error::ServiceNotInstalled(service_name.to_string()))?;
127
128    let exposure = match metadata.url.as_deref() {
129        Some(url) => Exposure::from_url(url),
130        None => Exposure::Loopback,
131    };
132
133    let service_ref = if metadata.registry.is_empty() || metadata.registry == REGISTRY_BUNDLED {
134        ServiceRef::Bundled(service_name.to_string())
135    } else {
136        ServiceRef::Custom {
137            registry: metadata.registry.clone(),
138            service: service_name.to_string(),
139        }
140    };
141    let repo_dir = resolve_registry_dir(&service_ref).await?;
142
143    // Recover existing host ports from the install's `.env` so the
144    // re-render lands on the same numbers. Without this every dynamically
145    // allocated port shifts because `port_in_use` reports them taken.
146    let port_overrides = read_existing_ports(service_name)?;
147
148    // Trivial port-in-use closure: the upgrade caller pins every port via
149    // `port_overrides`, so the closure is never consulted. Returning false
150    // unconditionally is safe — no allocation runs.
151    let port_in_use = |_p: u16| false;
152
153    let result = add_service(
154        service_name,
155        &exposure,
156        metadata.auth.clone(),
157        metadata.auth.is_some(),
158        // SMTP is gated inside add_service by `config.smtp.is_some()` and
159        // the service's own `integrations.smtp` flag, so passing `true`
160        // here mirrors what `ryra add` does and is harmless when SMTP is
161        // not configured.
162        true,
163        // Backup enablement is per-install state; preserve whatever the
164        // user picked at the original `ryra add`.
165        metadata.backup_enabled,
166        &BTreeMap::new(),
167        &BTreeSet::new(),
168        &metadata.registry,
169        &repo_dir,
170        None,
171        &port_in_use,
172        // ACME mode is only consumed when adding the reverse proxy itself;
173        // upgrade never needs to seed the TLS snippet.
174        None,
175        PlanMode::Upgrade,
176        &port_overrides,
177    )?;
178
179    let mut planned: BTreeMap<PathBuf, String> = BTreeMap::new();
180    for step in &result.steps {
181        if let Step::WriteFile(file) = step {
182            planned.insert(file.path.clone(), file.content.clone());
183        }
184    }
185    Ok((result, planned))
186}
187
188/// Parse the on-disk `.env` for a service into a key→value map. Lines
189/// without `=`, comments, and blanks are skipped. Returns an empty map if
190/// the file is absent — caller decides whether that's a soft error.
191fn read_existing_env_keys(service_name: &str) -> Result<BTreeMap<String, String>> {
192    let env_path = service_home(service_name)?.join(".env");
193    let mut out: BTreeMap<String, String> = BTreeMap::new();
194    let content = match std::fs::read_to_string(&env_path) {
195        Ok(c) => c,
196        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
197        Err(source) => {
198            return Err(Error::FileRead {
199                path: env_path,
200                source,
201            });
202        }
203    };
204    for line in content.lines() {
205        let line = line.trim();
206        if line.is_empty() || line.starts_with('#') {
207            continue;
208        }
209        if let Some((k, v)) = line.split_once('=') {
210            out.insert(k.trim().to_string(), v.to_string());
211        }
212    }
213    Ok(out)
214}
215
216/// Parse `SERVICE_PORT_<NAME>=<port>` lines out of an installed service's
217/// `.env`. Returns a name → port map (lowercased name, matching the
218/// `[[ports]]` definition in service.toml).
219fn read_existing_ports(service_name: &str) -> Result<BTreeMap<String, u16>> {
220    let env_path = service_home(service_name)?.join(".env");
221    let mut overrides = BTreeMap::new();
222    let content = match std::fs::read_to_string(&env_path) {
223        Ok(c) => c,
224        // No .env yet means a half-installed service; let the planner
225        // re-allocate. (`add_service` will then surface a richer error if
226        // the install is genuinely broken.)
227        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(overrides),
228        Err(source) => {
229            return Err(Error::FileRead {
230                path: env_path,
231                source,
232            });
233        }
234    };
235    for line in content.lines() {
236        let line = line.trim();
237        if line.is_empty() || line.starts_with('#') {
238            continue;
239        }
240        let Some((key, value)) = line.split_once('=') else {
241            continue;
242        };
243        let Some(name) = key.strip_prefix("SERVICE_PORT_") else {
244            continue;
245        };
246        if let Ok(port) = value.trim().parse::<u16>() {
247            overrides.insert(name.to_ascii_lowercase(), port);
248        }
249    }
250    Ok(overrides)
251}
252
253/// Lockfile-tracked files we never want to flag as drift. The `.env` carries
254/// generated secrets that rotate at runtime; `service.manifest` itself is the
255/// manifest, not a tracked file. Both are excluded from the planned set
256/// during diffing so they don't appear as Removed/Added.
257fn should_skip_path(path: &std::path::Path, manifest_file: &std::path::Path) -> bool {
258    if path == manifest_file {
259        return true;
260    }
261    matches!(path.file_name().and_then(|n| n.to_str()), Some(".env"))
262}
263
264/// Compute the diff between the registry's render and what's on disk for an
265/// installed service.
266pub async fn diff_service(service_name: &str) -> Result<DiffResult> {
267    let (result, planned) = replan(service_name).await?;
268    let manifest_file = manifest::manifest_path(service_name)?;
269    let (manifest_entries, _manifest_envs) = manifest::load(service_name)?.unwrap_or_default();
270    let manifest_by_path: BTreeMap<PathBuf, String> = manifest_entries
271        .into_iter()
272        .map(|e| (e.path, e.sha256))
273        .collect();
274
275    // Env additions: registry-expected static keys missing from the user's
276    // `.env`. Append-only — we ignore present-but-different values
277    // (could be a manual override) and never propose removals (could be
278    // a key the user added themselves that the registry happens not to
279    // ship). The registry-side list comes from the freshly-rendered
280    // `tracked_envs` (which carries kind + prompt for the CLI), not the
281    // on-disk manifest — that's the source of truth.
282    let existing_env = read_existing_env_keys(service_name)?;
283    let env_additions: Vec<EnvAddition> = result
284        .tracked_envs
285        .iter()
286        .filter(|p| !existing_env.contains_key(&p.key))
287        .map(|p| EnvAddition {
288            key: p.key.clone(),
289            value: p.value.clone(),
290            kind: p.kind.clone(),
291            prompt: p.prompt.clone(),
292        })
293        .collect();
294
295    let mut entries: Vec<DiffEntry> = Vec::new();
296    let mut seen: BTreeSet<PathBuf> = BTreeSet::new();
297
298    // Walk planned files first — Added / Modified / Drift / Unchanged.
299    for (path, content) in &planned {
300        if should_skip_path(path, &manifest_file) {
301            continue;
302        }
303        seen.insert(path.clone());
304        let planned_hash = manifest::hash_bytes(content.as_bytes());
305        let on_disk_hash = if path.exists() {
306            Some(manifest::hash_file(path)?)
307        } else {
308            None
309        };
310        let manifest_hash = manifest_by_path.get(path);
311
312        let kind = match (on_disk_hash.as_deref(), manifest_hash.map(String::as_str)) {
313            // File doesn't exist on disk.
314            (None, Some(_)) | (None, None) => match manifest_hash {
315                Some(_) => DiffKind::Modified, // we wrote it, user deleted it; restore
316                None => DiffKind::Added,       // registry adds it, fresh write
317            },
318            // On-disk content already matches what the registry would render.
319            (Some(d), _) if d == planned_hash => DiffKind::Unchanged,
320            // No manifest entry → can't tell if the user touched it.
321            // Conservative: treat as drift so --force is required once.
322            (Some(_), None) => DiffKind::Drift,
323            // On-disk matches the manifest but not the planned render →
324            // ryra-owned, safe to overwrite.
325            (Some(d), Some(l)) if d == l => DiffKind::Modified,
326            // On-disk matches neither lock nor plan → user hand-edited.
327            (Some(_), Some(_)) => DiffKind::Drift,
328        };
329        entries.push(DiffEntry {
330            path: path.clone(),
331            kind,
332        });
333    }
334
335    // Walk manifest entries that the planner no longer emits — Removed.
336    for path in manifest_by_path.keys() {
337        if seen.contains(path) {
338            continue;
339        }
340        if should_skip_path(path, &manifest_file) {
341            continue;
342        }
343        entries.push(DiffEntry {
344            path: path.clone(),
345            kind: DiffKind::Removed,
346        });
347    }
348
349    entries.sort_by(|a, b| a.path.cmp(&b.path));
350    Ok(DiffResult {
351        service: service_name.to_string(),
352        entries,
353        env_additions,
354    })
355}
356
357/// Plan an upgrade for an installed service.
358///
359/// Returns the steps to execute and the backup directory where displaced
360/// files will be copied. The backup dir is *also* baked into the steps
361/// (as `Step::CopyFile` entries placed before each `Step::WriteFile`).
362pub async fn upgrade_service(service_name: &str, force: bool) -> Result<UpgradeResult> {
363    let diff = diff_service(service_name).await?;
364
365    if !force {
366        let drifted = diff.drifted();
367        if !drifted.is_empty() {
368            return Err(Error::HandEditedFiles {
369                service: service_name.to_string(),
370                paths: drifted.iter().map(|e| e.path.clone()).collect(),
371            });
372        }
373    }
374
375    let (result, planned) = replan(service_name).await?;
376    let manifest_file = manifest::manifest_path(service_name)?;
377    let env_file = service_home(service_name)?.join(".env");
378
379    // Hard-fail if `.env` is missing. Append-only env handling can't
380    // reconstruct generated secrets (mysql_root_password, jwt_key, etc.)
381    // and would silently produce a half-written file that fails on
382    // restart. Surface the real problem instead.
383    if !env_file.exists() {
384        return Err(Error::Template(format!(
385            "{service_name}: `.env` is missing at {} — upgrade can't reconstruct generated secrets. \
386             Restore the file from a backup or reinstall the service.",
387            env_file.display()
388        )));
389    }
390
391    // Decide the backup directory once per upgrade run. Used whenever any
392    // file would be overwritten *or* the existing service.manifest exists (the
393    // lock is always backed up so `ryra revert` can reconstruct the
394    // pre-upgrade state). Empty when neither holds — keeps
395    // `~/.local/state/ryra/` from accumulating no-op dirs.
396    let backup_dir = backup_directory(service_name)?;
397    let needs_backup: BTreeSet<PathBuf> = diff
398        .entries
399        .iter()
400        .filter(|e| {
401            matches!(
402                e.kind,
403                DiffKind::Modified | DiffKind::Drift | DiffKind::Removed
404            )
405        })
406        .map(|e| e.path.clone())
407        .collect();
408    let manifest_will_be_backed_up = manifest_file.exists();
409    let backup_used = !needs_backup.is_empty() || manifest_will_be_backed_up;
410
411    // Filter the planned step list down to what an upgrade should actually do.
412    // - WriteFile for `.env` is dropped (preserve secrets).
413    // - PullImage stays (idempotent if cached, fetches new tag if registry bumped).
414    // - StartService is replaced with RestartService at the very end.
415    // - CreateDir / Symlink stay (idempotent and may be needed for new files).
416    // - DaemonReload stays.
417    // - CopyFile stays (vendored binaries; rare to upgrade but handled the same).
418    // - TailscaleSetup / TailscaleEnable were already gated out by PlanMode::Upgrade.
419    let mut steps: Vec<Step> = Vec::new();
420    if backup_used {
421        steps.push(Step::CreateDir(backup_dir.clone()));
422    }
423    let unchanged: BTreeSet<PathBuf> = diff
424        .entries
425        .iter()
426        .filter(|e| matches!(e.kind, DiffKind::Unchanged))
427        .map(|e| e.path.clone())
428        .collect();
429
430    let env_filename = std::ffi::OsStr::new(".env");
431    for step in result.steps {
432        match step {
433            // .env stays untouched on upgrade — generated secrets in the
434            // running service must not be regenerated.
435            Step::WriteFile(GeneratedFile { ref path, .. })
436                if path.file_name() == Some(env_filename) =>
437            {
438                continue;
439            }
440            // Identical content already on disk — skip the write entirely
441            // so the file's mtime stays put and `sha256sum -c` stays clean
442            // for unchanged entries.
443            Step::WriteFile(GeneratedFile { ref path, .. }) if unchanged.contains(path) => {
444                // The manifest is special: even if "unchanged" by content, we
445                // re-emit it because path-level adds/removes mean its content
446                // has changed and we need the new hashes recorded.
447                if path == &manifest_file {
448                    steps.push(step);
449                }
450                continue;
451            }
452            Step::WriteFile(ref file) => {
453                // Always back up the existing service.manifest too, even though
454                // it's filtered out of the diff. `ryra revert` reads the
455                // backed-up lock to know which files were Added during the
456                // upgrade (current lock − pre-upgrade lock) so it can delete
457                // them on revert. Without this, revert would leave
458                // upgrade-added files orphaned.
459                let should_backup = (needs_backup.contains(&file.path)
460                    || file.path == manifest_file)
461                    && file.path.exists();
462                if should_backup {
463                    let rel = backup_relpath(&file.path);
464                    let dst = backup_dir.join(rel);
465                    if let Some(parent) = dst.parent() {
466                        steps.push(Step::CreateDir(parent.to_path_buf()));
467                    }
468                    steps.push(Step::CopyFile {
469                        src: file.path.clone(),
470                        dst,
471                    });
472                }
473                steps.push(step);
474            }
475            // The replanned step list always ends with StartService; we
476            // strip it and append a RestartService at the very end so the
477            // unit picks up the new quadlet.
478            Step::StartService { .. } => continue,
479            other => steps.push(other),
480        }
481    }
482
483    // Removed files: back them up then delete.
484    for entry in &diff.entries {
485        if !matches!(entry.kind, DiffKind::Removed) {
486            continue;
487        }
488        if entry.path.exists() {
489            let rel = backup_relpath(&entry.path);
490            let dst = backup_dir.join(rel);
491            if let Some(parent) = dst.parent() {
492                steps.push(Step::CreateDir(parent.to_path_buf()));
493            }
494            steps.push(Step::CopyFile {
495                src: entry.path.clone(),
496                dst,
497            });
498        }
499        steps.push(Step::RemoveFile(entry.path.clone()));
500    }
501
502    // Env additions: append registry-required static env vars that the
503    // user's .env doesn't have. Append-only — we never rewrite the
504    // existing .env (that would clobber rotated secrets and any manual
505    // edits) and we never remove keys (the user might have added their
506    // own that the registry happens not to ship). The .env is
507    // intentionally NOT backed up: it only ever gains lines and the
508    // pre-existing content survives unchanged.
509    if !diff.env_additions.is_empty() {
510        let mut content = match std::fs::read_to_string(&env_file) {
511            Ok(c) => c,
512            // Service installed but .env missing? Treat the add as a
513            // fresh write — odd state, but the right one to recover to.
514            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
515            Err(source) => {
516                return Err(Error::FileRead {
517                    path: env_file.clone(),
518                    source,
519                });
520            }
521        };
522        if !content.is_empty() && !content.ends_with('\n') {
523            content.push('\n');
524        }
525        for add in &diff.env_additions {
526            content.push_str(&format!("{}={}\n", add.key, add.value));
527        }
528        steps.push(Step::WriteFile(GeneratedFile {
529            path: env_file,
530            content,
531        }));
532    }
533
534    // Pick up the new quadlet by restarting. RestartService is enough to
535    // re-read the env file, re-run ExecStartPre/Post, and pull in any new
536    // ExecStartPost script (the seafile case).
537    steps.push(Step::RestartService {
538        unit: service_name.to_string(),
539    });
540
541    Ok(UpgradeResult {
542        service: service_name.to_string(),
543        diff,
544        steps,
545        backup_dir: if backup_used { Some(backup_dir) } else { None },
546        // The replanned env content is irrelevant for upgrade (we don't
547        // write it), but expose the template-render context bag in case
548        // future callers need it. Keep it empty for now to avoid
549        // confusing consumers.
550        planned_files: planned,
551    })
552}
553
554pub struct UpgradeResult {
555    pub service: String,
556    pub diff: DiffResult,
557    pub steps: Vec<Step>,
558    /// `None` when no files would be overwritten or removed.
559    pub backup_dir: Option<PathBuf>,
560    pub planned_files: BTreeMap<PathBuf, String>,
561}
562
563/// One available backup snapshot for a service.
564#[derive(Debug, Clone)]
565pub struct BackupSnapshot {
566    /// Filesystem path: `~/.local/state/ryra/backups/<timestamp>/<service>/`.
567    pub path: PathBuf,
568    /// `YYYY-MM-DDTHH-MM-SSZ` timestamp from the parent dir name.
569    pub timestamp: String,
570}
571
572pub struct RevertResult {
573    pub service: String,
574    pub snapshot: BackupSnapshot,
575    pub steps: Vec<Step>,
576    /// Files to be copied from backup back to their original locations.
577    pub files_to_restore: Vec<PathBuf>,
578    /// Files added by the upgrade that didn't exist before — will be
579    /// removed by revert. Empty when the snapshot pre-dates the manifest
580    /// feature (we can't reconstruct what was added without it).
581    pub files_to_delete: Vec<PathBuf>,
582}
583
584/// List every backup snapshot for a service, newest first. Empty result
585/// means there's nothing to revert from.
586/// How many backup snapshots `ryra upgrade` retains per service before
587/// auto-pruning. Each snapshot is small (~tens of KB — config files +
588/// the manifest) so the cap is more about mental clutter than disk; 5
589/// is enough to revert a few iterations back without filling the
590/// `~/.local/state/ryra/backups/` tree with dead snapshots from years
591/// of upgrades.
592pub const DEFAULT_BACKUP_KEEP: usize = 5;
593
594/// Drop snapshots older than the most recent `keep` for this service.
595/// Returns the paths that were removed (newest-first within the
596/// removed set; the kept set keeps the same order). The shared
597/// timestamp dir is also removed when this was the last service-
598/// scoped subdir under it (multi-service upgrade runs share a
599/// timestamp dir; we don't want to nuke other services' state).
600pub fn prune_backups(service_name: &str, keep: usize) -> Result<Vec<PathBuf>> {
601    let backups_root = state_dir()?.join("backups");
602    prune_backups_in(&backups_root, service_name, keep)
603}
604
605/// Pure inner that operates on an explicit `<state>/backups/` root.
606/// Split out so tests can drive it against a tmp tree without touching
607/// the real XDG state dir.
608fn prune_backups_in(
609    backups_root: &std::path::Path,
610    service_name: &str,
611    keep: usize,
612) -> Result<Vec<PathBuf>> {
613    let snapshots = list_backups_in(backups_root, service_name)?;
614    if snapshots.len() <= keep {
615        return Ok(Vec::new());
616    }
617    let mut removed: Vec<PathBuf> = Vec::new();
618    for snap in snapshots.into_iter().skip(keep) {
619        if let Err(e) = std::fs::remove_dir_all(&snap.path) {
620            eprintln!(
621                "warning: failed to prune backup {}: {e}",
622                snap.path.display()
623            );
624            continue;
625        }
626        removed.push(snap.path.clone());
627        if let Some(parent) = snap.path.parent()
628            && let Ok(mut entries) = std::fs::read_dir(parent)
629            && entries.next().is_none()
630        {
631            let _ = std::fs::remove_dir(parent);
632        }
633    }
634    Ok(removed)
635}
636
637pub fn list_backups(service_name: &str) -> Result<Vec<BackupSnapshot>> {
638    let backups_root = state_dir()?.join("backups");
639    list_backups_in(&backups_root, service_name)
640}
641
642fn list_backups_in(
643    backups_root: &std::path::Path,
644    service_name: &str,
645) -> Result<Vec<BackupSnapshot>> {
646    if !backups_root.is_dir() {
647        return Ok(Vec::new());
648    }
649    let mut snapshots: Vec<BackupSnapshot> = Vec::new();
650    let entries = std::fs::read_dir(backups_root).map_err(|source| Error::FileRead {
651        path: backups_root.to_path_buf(),
652        source,
653    })?;
654    for entry in entries.flatten() {
655        let stamp_dir = entry.path();
656        if !stamp_dir.is_dir() {
657            continue;
658        }
659        let svc_dir = stamp_dir.join(service_name);
660        if !svc_dir.is_dir() {
661            continue;
662        }
663        let Some(stamp) = stamp_dir.file_name().and_then(|n| n.to_str()) else {
664            continue;
665        };
666        snapshots.push(BackupSnapshot {
667            path: svc_dir,
668            timestamp: stamp.to_string(),
669        });
670    }
671    // Newest first: timestamp is `YYYY-MM-DDTHH-MM-SSZ`, lexical-descending == reverse-chronological.
672    snapshots.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
673    Ok(snapshots)
674}
675
676/// Plan a revert for an installed service.
677///
678/// `at` selects a specific backup timestamp; `None` picks the most recent.
679/// The returned plan: restore every file from the backup tree to its
680/// original location, delete files added by the upgrade, daemon-reload,
681/// restart the unit.
682pub fn revert_service(service_name: &str, at: Option<&str>) -> Result<RevertResult> {
683    if !is_service_installed(service_name) {
684        return Err(Error::ServiceNotInstalled(service_name.to_string()));
685    }
686    let snapshot = pick_snapshot(service_name, at)?;
687
688    // Files to restore: walk the backup tree and reconstruct the original
689    // absolute path for each one. The backup mirrors absolute paths under
690    // `<snapshot>/<original-path-without-leading-slash>`, so the inverse is
691    // simply prefixing `/` to each path-relative-to-snapshot.
692    let mut files_to_restore: Vec<PathBuf> = Vec::new();
693    walk_backup_files(&snapshot.path, &mut files_to_restore)?;
694
695    // Files to delete: anything in the *current* lock that isn't in the
696    // *backed-up* lock was added by the upgrade and should disappear on
697    // revert. If either lock is absent, leave the delete set empty —
698    // safest no-op for snapshots that pre-date this feature.
699    let backup_manifest_file =
700        absolute_to_backup_path(&snapshot.path, &manifest::manifest_path(service_name)?);
701    let (backup_manifest_entries, _) = read_manifest_at(&backup_manifest_file)?;
702    let (current_manifest_entries, _) = manifest::load(service_name)?.unwrap_or_default();
703
704    let backup_manifest_set: BTreeSet<PathBuf> = backup_manifest_entries
705        .iter()
706        .map(|e| e.path.clone())
707        .collect();
708    let mut files_to_delete: Vec<PathBuf> = if backup_manifest_entries.is_empty() {
709        // Pre-feature snapshot: no way to know what was added.
710        Vec::new()
711    } else {
712        current_manifest_entries
713            .iter()
714            .map(|e| e.path.clone())
715            .filter(|p| !backup_manifest_set.contains(p))
716            .collect()
717    };
718    files_to_delete.sort();
719
720    // Build the step list.
721    let mut steps: Vec<Step> = Vec::new();
722    // Restore: backup → original. CopyFile creates parents itself, so no
723    // CreateDir needed.
724    for backup_path in &files_to_restore {
725        let original = backup_to_absolute_path(&snapshot.path, backup_path);
726        steps.push(Step::CopyFile {
727            src: backup_path.clone(),
728            dst: original,
729        });
730    }
731    // Delete: each Added file, plus any orphan symlink in the quadlet dir
732    // that pointed at it (only the actual file is in the lock; the
733    // companion symlink in `~/.config/containers/systemd/` is not).
734    let qd = crate::quadlet_dir()?;
735    for path in &files_to_delete {
736        if path.exists() {
737            steps.push(Step::RemoveFile(path.clone()));
738        }
739        if let Some(name) = path.file_name() {
740            let symlink = qd.join(name);
741            if std::fs::symlink_metadata(&symlink).is_ok() {
742                steps.push(Step::RemoveFile(symlink));
743            }
744        }
745    }
746    steps.push(Step::DaemonReload);
747    steps.push(Step::RestartService {
748        unit: service_name.to_string(),
749    });
750
751    let files_to_restore_orig: Vec<PathBuf> = files_to_restore
752        .iter()
753        .map(|p| backup_to_absolute_path(&snapshot.path, p))
754        .collect();
755    Ok(RevertResult {
756        service: service_name.to_string(),
757        snapshot,
758        steps,
759        files_to_restore: files_to_restore_orig,
760        files_to_delete,
761    })
762}
763
764/// Resolve the snapshot to revert to. `at` is a timestamp string (e.g.
765/// `2026-05-05T13-33-50Z`); when absent, the most recent snapshot wins.
766fn pick_snapshot(service_name: &str, at: Option<&str>) -> Result<BackupSnapshot> {
767    let snapshots = list_backups(service_name)?;
768    if snapshots.is_empty() {
769        return Err(Error::NoBackup(service_name.to_string()));
770    }
771    match at {
772        None => Ok(snapshots
773            .into_iter()
774            .next()
775            .expect("non-empty checked above")),
776        Some(stamp) => snapshots
777            .into_iter()
778            .find(|s| s.timestamp == stamp)
779            .ok_or_else(|| Error::BackupNotFound {
780                service: service_name.to_string(),
781                stamp: stamp.to_string(),
782            }),
783    }
784}
785
786/// Recursively collect every regular file under `root` into `out`. Symlinks
787/// are followed; we don't expect any in a backup tree (we always copied
788/// targets, never link entries).
789fn walk_backup_files(root: &std::path::Path, out: &mut Vec<PathBuf>) -> Result<()> {
790    let entries = std::fs::read_dir(root).map_err(|source| Error::FileRead {
791        path: root.to_path_buf(),
792        source,
793    })?;
794    for entry in entries.flatten() {
795        let path = entry.path();
796        let meta = match entry.metadata() {
797            Ok(m) => m,
798            Err(_) => continue,
799        };
800        if meta.is_dir() {
801            walk_backup_files(&path, out)?;
802        } else if meta.is_file() {
803            out.push(path);
804        }
805    }
806    Ok(())
807}
808
809/// Inverse of `backup_relpath`: a backup path `<root>/home/user/foo`
810/// maps back to `/home/user/foo`.
811fn backup_to_absolute_path(root: &std::path::Path, backup: &std::path::Path) -> PathBuf {
812    let rel = backup.strip_prefix(root).unwrap_or(backup);
813    PathBuf::from("/").join(rel)
814}
815
816/// Forward variant: `<root>` + `/home/user/foo` → `<root>/home/user/foo`.
817fn absolute_to_backup_path(root: &std::path::Path, abs: &std::path::Path) -> PathBuf {
818    let rel = abs.to_string_lossy();
819    let stripped = rel.trim_start_matches('/');
820    root.join(stripped)
821}
822
823/// Read a manifest at the given path. Missing-file is treated as an empty
824/// list — pre-feature backups simply have no lock to reference.
825fn read_manifest_at(
826    path: &std::path::Path,
827) -> Result<(Vec<manifest::ManifestEntry>, Vec<manifest::EnvEntry>)> {
828    if !path.exists() {
829        return Ok((Vec::new(), Vec::new()));
830    }
831    let content = std::fs::read_to_string(path).map_err(|source| Error::FileRead {
832        path: path.to_path_buf(),
833        source,
834    })?;
835    manifest::parse(&content)
836}
837
838/// `~/.local/state/ryra/backups/<timestamp>/<service>/`. Timestamp uses an
839/// ISO-8601-ish form that sorts lexically (no colons — Windows-friendly,
840/// not that it matters today, but the cost is zero).
841fn backup_directory(service_name: &str) -> Result<PathBuf> {
842    let state = state_dir()?;
843    let now = std::time::SystemTime::now()
844        .duration_since(std::time::UNIX_EPOCH)
845        .map_err(|e| Error::Template(format!("system clock before UNIX epoch: {e}")))?
846        .as_secs();
847    let stamp = format_timestamp(now);
848    Ok(state.join("backups").join(stamp).join(service_name))
849}
850
851/// XDG state dir under `ryra/`. Created on demand by the CreateDir step.
852fn state_dir() -> Result<PathBuf> {
853    let base = dirs::state_dir()
854        .or_else(|| dirs::home_dir().map(|h| h.join(".local").join("state")))
855        .ok_or(Error::HomeDirNotFound)?;
856    Ok(base.join("ryra"))
857}
858
859/// Format a UNIX epoch into `YYYY-MM-DDTHH-MM-SSZ`. Avoids the chrono
860/// dependency — we just need stable lexical sort.
861fn format_timestamp(secs: u64) -> String {
862    // Days from 1970-01-01.
863    const SECS_PER_DAY: u64 = 86_400;
864    let days = secs / SECS_PER_DAY;
865    let time_of_day = secs % SECS_PER_DAY;
866    let h = time_of_day / 3600;
867    let m = (time_of_day % 3600) / 60;
868    let s = time_of_day % 60;
869    let (y, mo, d) = ymd_from_days(days);
870    format!("{y:04}-{mo:02}-{d:02}T{h:02}-{m:02}-{s:02}Z")
871}
872
873/// Convert "days since 1970-01-01" into `(year, month, day)` using the
874/// civil-from-days algorithm (Howard Hinnant's date library, MIT). Self-
875/// contained so we don't add a chrono/time dep just for backup naming.
876fn ymd_from_days(days: u64) -> (i64, u32, u32) {
877    let z = days as i64 + 719_468;
878    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
879    let doe = (z - era * 146_097) as u64;
880    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
881    let y = yoe as i64 + era * 400;
882    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
883    let mp = (5 * doy + 2) / 153;
884    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
885    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
886    let y = if m <= 2 { y + 1 } else { y };
887    (y, m, d)
888}
889
890/// Map an absolute path into the backup tree. We strip the leading `/` so the
891/// joined path doesn't escape the backup dir; everything else is preserved
892/// verbatim so the user can `diff -r` across the original location.
893fn backup_relpath(path: &std::path::Path) -> PathBuf {
894    PathBuf::from(path.to_string_lossy().trim_start_matches('/'))
895}
896
897#[cfg(test)]
898mod tests {
899    use super::*;
900
901    #[test]
902    fn timestamp_round_numbers() {
903        // 2026-01-01T00-00-00Z — sanity check on the calendar conversion.
904        // 1767225600 = days from epoch * 86400 for 2026-01-01.
905        // (epoch 0 = 1970-01-01; 56 years incl. leap days = 20454 days.)
906        // Easier: just verify a known value end-to-end.
907        let s = format_timestamp(0);
908        assert_eq!(s, "1970-01-01T00-00-00Z");
909        let s = format_timestamp(86_400);
910        assert_eq!(s, "1970-01-02T00-00-00Z");
911        let s = format_timestamp(31_536_000); // not a leap year (1970)
912        assert_eq!(s, "1971-01-01T00-00-00Z");
913    }
914
915    #[test]
916    fn backup_relpath_strips_leading_slash() {
917        let p = backup_relpath(std::path::Path::new("/home/user/foo/bar"));
918        assert_eq!(p, PathBuf::from("home/user/foo/bar"));
919    }
920
921    /// Stand up a tmp backups tree with the given timestamps and a
922    /// service subdir under each, then run `prune_backups_in` against it.
923    /// Returns (kept timestamps newest-first, removed paths). Hermetic:
924    /// no env vars touched, no shared global state.
925    fn setup_and_prune(stamps: &[&str], keep: usize) -> (Vec<String>, Vec<PathBuf>) {
926        let tmp = std::env::temp_dir().join(format!(
927            "ryra-prune-test-{}-{}",
928            std::process::id(),
929            std::time::SystemTime::now()
930                .duration_since(std::time::UNIX_EPOCH)
931                .unwrap()
932                .as_nanos()
933        ));
934        let backups_root = tmp.join("backups");
935        for s in stamps {
936            std::fs::create_dir_all(backups_root.join(s).join("svc")).unwrap();
937        }
938        let removed = prune_backups_in(&backups_root, "svc", keep).unwrap();
939        let mut kept: Vec<String> = std::fs::read_dir(&backups_root)
940            .unwrap()
941            .filter_map(|e| e.ok())
942            .filter_map(|e| e.file_name().into_string().ok())
943            .collect();
944        kept.sort();
945        kept.reverse();
946        let _ = std::fs::remove_dir_all(&tmp);
947        (kept, removed)
948    }
949
950    #[test]
951    fn prune_keeps_newest_n() {
952        // Five timestamps, keep=3 — the two oldest (lex-smallest) should go.
953        let (kept, removed) = setup_and_prune(
954            &[
955                "2026-01-01T00-00-00Z",
956                "2026-02-01T00-00-00Z",
957                "2026-03-01T00-00-00Z",
958                "2026-04-01T00-00-00Z",
959                "2026-05-01T00-00-00Z",
960            ],
961            3,
962        );
963        assert_eq!(kept.len(), 3);
964        assert_eq!(kept[0], "2026-05-01T00-00-00Z");
965        assert_eq!(kept[2], "2026-03-01T00-00-00Z");
966        assert_eq!(removed.len(), 2);
967    }
968
969    #[test]
970    fn prune_no_op_when_under_keep() {
971        let (kept, removed) = setup_and_prune(&["2026-01-01T00-00-00Z", "2026-02-01T00-00-00Z"], 5);
972        assert_eq!(kept.len(), 2);
973        assert!(removed.is_empty());
974    }
975
976    #[test]
977    fn should_skip_path_excludes_env_and_manifest() {
978        let lock = PathBuf::from("/svc/service.manifest");
979        assert!(should_skip_path(&PathBuf::from("/svc/.env"), &lock));
980        assert!(should_skip_path(&lock, &lock));
981        assert!(!should_skip_path(
982            &PathBuf::from("/svc/configs/x.sh"),
983            &lock
984        ));
985    }
986}