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