ryra-core 0.7.3

Core library for ryra: config, registry, and service generation logic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
//! `ryra configure <service>` — re-plan an installed service with a
//! caller-supplied set of [`Overrides`] applied on top of its current
//! recorded state.
//!
//! The render path is shared with [`crate::add_service`] (driven via
//! [`crate::PlanMode::Upgrade`] so the install-time rejects don't fire and
//! the install-only side effects stay quiet). What's new here is the
//! *state recovery*, *change classification*, and *cross-service
//! lifecycle handling*:
//!
//! 1. Load `metadata.toml` + the existing `.env` and compute the current
//!    configuration (`enable_auth`, `enable_smtp`, `enable_backup`,
//!    `enabled_groups`, exposure, per-secret values).
//! 2. Apply [`Overrides`] to produce the *target* configuration.
//! 3. Re-call `add_service` in upgrade mode with the target values, passing
//!    the existing secrets through `pre_built_ctx` so `secret.*` and
//!    `auth.*` are preserved verbatim (a freshly-rotated JWT key would
//!    invalidate every active session). When auth is *being enabled*,
//!    fresh `auth.client_id` / `auth.client_secret` are minted here and
//!    seeded into `pre_built_ctx` so the same values flow into both the
//!    rendered `.env` and the `register_oidc_client` step.
//! 4. Diff the plan vs. on-disk state (reusing the upgrade diff machinery)
//!    and classify the high-level changes via [`ConfigureChange`] so the
//!    CLI can render them with the right colour and gate destructive
//!    transitions behind explicit confirmation.
//! 5. Emit lifecycle side-steps the install path normally handles only at
//!    `PlanMode::Add` time:
//!    - Authelia OIDC client `register` / `unregister` when `--auth` is
//!      flipped or the URL changes on an auth-enabled service (the
//!      `redirect_uri` is pinned to the URL at registration time).
//!    - `TailscaleEnable` / `TailscaleDisable` when the exposure crosses
//!      the loopback / URL / tailscale boundary.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use crate::config::ConfigPaths;
use crate::error::{Error, Result};
use crate::exposure::Exposure;
use crate::generate::GeneratedFile;
use crate::metadata::load_metadata;
use crate::registry::resolve::ServiceRef;
use crate::registry::service_def::{AuthKind, EnvFormat};
use crate::system::secret;
use crate::upgrade::{DiffEntry, DiffKind, DiffResult, EnvAddition};
use crate::{
    AddResult, PlanMode, REGISTRY_DEFAULT, Step, WellKnownService, add_service, authelia, caddy,
    config, is_service_installed, list_installed, manifest, quadlet_dir, registry,
    resolve_registry_dir, service_home,
};

/// What the caller wants to change. Every field is "leave alone" by default;
/// `Some(_)` means "set to this value." Two-sided enums (e.g.
/// [`ExposureChange`]) make "remove" representable without overloading
/// `Some("")` with a sentinel meaning.
#[derive(Debug, Clone, Default)]
pub struct Overrides {
    /// Change the service's exposure: a public URL, a Tailscale Service,
    /// or loopback-only. `None` leaves the current exposure alone.
    pub exposure: Option<ExposureChange>,
    /// Flip per-service SMTP wiring. The global SMTP config is unchanged
    /// either way.
    pub smtp: Option<bool>,
    /// Flip the backup inclusion flag for this install.
    pub backup: Option<bool>,
    /// Flip OIDC auth wiring. `Some(true)` registers an OIDC client with
    /// the installed auth provider and adds OIDC env vars; `Some(false)`
    /// unregisters and strips them.
    pub auth: Option<bool>,
    /// Env-group names to turn ON (members land in `.env`).
    pub enable_groups: BTreeSet<String>,
    /// Env-group names to turn OFF (members drop out of `.env`).
    pub disable_groups: BTreeSet<String>,
    /// Raw per-env overrides applied during render. Useful for changing
    /// the value of a `prompted` env var (e.g. an admin email) without
    /// touching anything else.
    pub env_overrides: BTreeMap<String, String>,
}

/// Exposure transition. `Loopback` means "no public route" (the install's
/// equivalent of dropping `--url` and `--tailscale`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExposureChange {
    /// Caddy-routed public URL. Internal vs. Public is auto-classified
    /// from the hostname by [`Exposure::from_url`].
    Url(String),
    /// Tailscale Service exposure. The caller must pre-derive the URL
    /// from the system's tailnet identity (`<svc>-<host>.<tailnet>`).
    Tailscale(String),
    /// Loopback-only (no Caddy route, no Tailscale Service).
    Loopback,
}

/// A single high-level change the configure run will apply. The CLI uses
/// this for the summary banner; `is_destructive` decides whether the
/// change requires the user to type the service name to confirm.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigureChange {
    /// URL changed (or added, or removed). Covers all exposure
    /// transitions: tailscale-on shows as `Url { to: Some(ts_url) }`.
    Url {
        from: Option<String>,
        to: Option<String>,
    },
    /// Per-service SMTP wiring toggled.
    Smtp { from: bool, to: bool },
    /// Backup inclusion flag flipped.
    Backup { from: bool, to: bool },
    /// OIDC auth wiring toggled.
    Auth { from: bool, to: bool },
    /// An env-group bundle was switched on (members appended to `.env`).
    GroupEnabled(String),
    /// An env-group bundle was switched off (members removed from `.env`).
    GroupDisabled(String),
    /// A single env var's value was overridden by the user.
    EnvOverride {
        key: String,
        from: Option<String>,
        to: String,
    },
}

impl ConfigureChange {
    /// True when applying the change would invalidate state the user might
    /// depend on. The CLI gates these behind explicit confirmation.
    ///
    /// - Removing or changing the URL detaches the existing Caddy route
    ///   (and breaks any OAuth callback configured at the old hostname).
    /// - Disabling auth removes the OIDC client and SSO env vars; users
    ///   who logged in via SSO can no longer reach the service that way.
    /// - Disabling SMTP cuts off outbound mail for the service.
    /// - Disabling backup means future `ryra backup run` calls skip this
    ///   install — historical snapshots are kept on the restic repo.
    /// - Disabling a group drops env vars the service had access to;
    ///   features depending on them stop working until re-enabled.
    pub fn is_destructive(&self) -> bool {
        match self {
            ConfigureChange::Url { from, to } => from.is_some() && from != to,
            ConfigureChange::Smtp {
                from: true,
                to: false,
            } => true,
            ConfigureChange::Backup {
                from: true,
                to: false,
            } => true,
            ConfigureChange::Auth {
                from: true,
                to: false,
            } => true,
            ConfigureChange::GroupDisabled(_) => true,
            ConfigureChange::Smtp { .. } => false,
            ConfigureChange::Backup { .. } => false,
            ConfigureChange::Auth { .. } => false,
            ConfigureChange::GroupEnabled(_) => false,
            ConfigureChange::EnvOverride { .. } => false,
        }
    }
}

/// Output of [`configure_service`].
pub struct ConfigureResult {
    pub service: String,
    /// High-level transitions, in a stable order — the CLI walks this for
    /// the human-readable summary and the destructive-change gate.
    pub changes: Vec<ConfigureChange>,
    /// File-level diff from the upgrade machinery. Empty `entries` means
    /// no files differ from the current install (only metadata-level
    /// changes like `--backup` might still be in `changes`).
    pub diff: DiffResult,
    /// Steps to execute. Empty when neither files nor metadata would
    /// change (no-op configure).
    pub steps: Vec<Step>,
    /// True if at least one change in `changes` is destructive.
    pub has_destructive: bool,
}

impl ConfigureResult {
    /// True when nothing would change at all — neither files, env, nor
    /// metadata. The CLI uses this to short-circuit "already configured
    /// that way" without printing a confusing empty summary.
    /// `steps` is the source of truth: [`build_configure_steps`]
    /// returns `Vec::new()` whenever no step would run.
    pub fn is_noop(&self) -> bool {
        self.steps.is_empty()
    }
}

/// Re-plan an installed service against `overrides`. Pure: emits steps but
/// performs no I/O beyond reading the current install's state from disk.
pub async fn configure_service(
    service_name: &str,
    overrides: &Overrides,
) -> Result<ConfigureResult> {
    if !is_service_installed(service_name) {
        return Err(Error::ServiceNotInstalled(service_name.to_string()));
    }

    let metadata = load_metadata(service_name)?
        .ok_or_else(|| Error::ServiceNotInstalled(service_name.to_string()))?;

    let current_url: Option<String> = metadata.url.clone();
    let current_smtp: bool = metadata.smtp_enabled;
    let current_backup: bool = metadata.backup_enabled;
    let current_auth: bool = metadata.auth.is_some();
    let current_groups: BTreeSet<String> = metadata.enabled_groups.iter().cloned().collect();

    // Compute target values.
    let target_url: Option<String> = match &overrides.exposure {
        None => current_url.clone(),
        Some(ExposureChange::Loopback) => None,
        Some(ExposureChange::Url(u)) => Some(u.clone()),
        Some(ExposureChange::Tailscale(u)) => Some(u.clone()),
    };
    let target_smtp: bool = overrides.smtp.unwrap_or(current_smtp);
    let target_backup: bool = overrides.backup.unwrap_or(current_backup);
    let target_auth: bool = overrides.auth.unwrap_or(current_auth);

    let service_ref = if metadata.registry.is_empty() || metadata.registry == REGISTRY_DEFAULT {
        ServiceRef::Default(service_name.to_string())
    } else {
        ServiceRef::Custom {
            registry: metadata.registry.clone(),
            service: service_name.to_string(),
        }
    };
    let repo_dir = resolve_registry_dir(&service_ref).await?;
    let reg_service = registry::find_service(&repo_dir, service_name)?;

    // Validate env_group flags before we touch any state, mirroring
    // `add_service`'s unknown-group check.
    let known_groups: BTreeSet<&str> = reg_service
        .def
        .env_groups
        .iter()
        .map(|g| g.name.as_str())
        .collect();
    for g in overrides
        .enable_groups
        .iter()
        .chain(overrides.disable_groups.iter())
    {
        if !known_groups.contains(g.as_str()) {
            let known: Vec<String> = known_groups.iter().map(|s| (*s).to_string()).collect();
            let hint = if known.is_empty() {
                " (service defines no env_groups)".to_string()
            } else {
                format!(" (known: {})", known.join(", "))
            };
            return Err(Error::UnknownEnvGroup {
                service: service_name.to_string(),
                group: g.clone(),
                hint,
            });
        }
    }
    for g in &overrides.enable_groups {
        if overrides.disable_groups.contains(g) {
            return Err(Error::ConfigureUnsupported {
                service: service_name.to_string(),
                field: format!("env_group '{g}'"),
                workaround:
                    "group can't appear in both --enable and --disable in one configure run"
                        .to_string(),
            });
        }
    }
    if target_backup && !reg_service.def.integrations.backup {
        return Err(Error::BackupNotSupported(service_name.to_string()));
    }
    // Enabling auth requires the service to support OIDC natively.
    // (`add_service` checks this too, but failing here gives a cleaner
    // error than a half-built plan.)
    if !current_auth
        && target_auth
        && reg_service.def.integrations.auth.is_empty()
        && !crate::capability::def_provides(&reg_service.def, crate::Capability::OidcProvider)
    {
        return Err(Error::NoOidcSupport(service_name.to_string()));
    }
    // OIDC client registration needs a base URL to write into the
    // `redirect_uris`. Covers both turn-on (need URL up front) and
    // URL-change-while-on (the re-register would have no target).
    let url_changed_pre = current_url != target_url;
    let needs_register_pre = target_auth && (!current_auth || url_changed_pre);
    if needs_register_pre && target_url.is_none() {
        return Err(Error::ConfigureUnsupported {
            service: service_name.to_string(),
            field: "auth without url".to_string(),
            workaround: "auth needs a public URL for the OIDC redirect_uri; pass `--url <URL>` \
                 alongside `--auth`, or use `--no-auth` to disable auth"
                .to_string(),
        });
    }

    let mut target_groups = current_groups.clone();
    for g in &overrides.enable_groups {
        target_groups.insert(g.clone());
    }
    for g in &overrides.disable_groups {
        target_groups.remove(g);
    }

    // Recover existing secrets from the live `.env` so re-render doesn't
    // mint fresh ones. When auth is being *enabled* for the first time,
    // mint client_id / client_secret here (so we can pass the same pair
    // to the OIDC registration step below).
    let mut pre_built_ctx = recover_template_ctx(service_name, &reg_service.def)?;
    let mut minted_oidc: Option<(String, String)> = None;
    if !current_auth && target_auth {
        let client_id = secret::generate(&EnvFormat::Uuid, None);
        let client_secret = secret::generate(&EnvFormat::String, Some(64));
        pre_built_ctx.insert("auth.client_id".into(), client_id.clone());
        pre_built_ctx.insert("auth.client_secret".into(), client_secret.clone());
        minted_oidc = Some((client_id, client_secret));
    }

    // Pin existing host ports across re-renders — same rule as upgrade.
    let port_overrides = read_existing_ports(service_name)?;
    let port_in_use = |_p: u16| false;

    let target_exposure: Exposure = match &target_url {
        None => Exposure::Loopback,
        Some(u) => Exposure::from_url(u),
    };
    let prior_kind = current_url
        .as_deref()
        .map(Exposure::from_url)
        .unwrap_or(Exposure::Loopback);

    let result = add_service(crate::AddServiceParams {
        service_name,
        exposure: &target_exposure,
        auth: if target_auth {
            crate::AuthChoice::Native(AuthKind::Oidc)
        } else {
            crate::AuthChoice::None
        },
        enable_smtp: target_smtp,
        enable_backup: target_backup,
        env_overrides: &overrides.env_overrides,
        enabled_groups: &target_groups,
        registry_name: &metadata.registry,
        repo_dir: &repo_dir,
        pre_built_ctx: Some(pre_built_ctx),
        port_in_use: &port_in_use,
        // ACME is only consumed when seeding caddy on first install.
        acme_mode: None,
        mode: PlanMode::Upgrade,
        port_overrides: &port_overrides,
    })?;

    let diff = build_diff(service_name, &result)?;

    // High-level changes — order reflects how a user mentally categorises
    // the transitions (routing first, then per-service features, then
    // env scope, then individual vars).
    let mut changes: Vec<ConfigureChange> = Vec::new();
    if current_url != target_url {
        changes.push(ConfigureChange::Url {
            from: current_url.clone(),
            to: target_url.clone(),
        });
    }
    if current_auth != target_auth {
        changes.push(ConfigureChange::Auth {
            from: current_auth,
            to: target_auth,
        });
    }
    if current_smtp != target_smtp {
        changes.push(ConfigureChange::Smtp {
            from: current_smtp,
            to: target_smtp,
        });
    }
    if current_backup != target_backup {
        changes.push(ConfigureChange::Backup {
            from: current_backup,
            to: target_backup,
        });
    }
    for g in target_groups.difference(&current_groups) {
        changes.push(ConfigureChange::GroupEnabled(g.clone()));
    }
    for g in current_groups.difference(&target_groups) {
        changes.push(ConfigureChange::GroupDisabled(g.clone()));
    }
    let existing_env = read_existing_env_keys(service_name)?;
    for (key, val) in &overrides.env_overrides {
        let prior = existing_env.get(key).cloned();
        if prior.as_deref() != Some(val.as_str()) {
            changes.push(ConfigureChange::EnvOverride {
                key: key.clone(),
                from: prior,
                to: val.clone(),
            });
        }
    }
    let has_destructive = changes.iter().any(|c| c.is_destructive());

    // Cross-service lifecycle: classify what side-effects this configure
    // needs beyond writing the service's own files.
    //
    // OIDC: re-register whenever (a) auth is being turned on, or (b)
    // auth was already on but the URL changed (Authelia pins the
    // redirect_uri at registration time, so the old entry would now
    // point at the wrong hostname).
    let url_changed = current_url != target_url;
    let needs_unregister = current_auth && (!target_auth || url_changed);
    let needs_register = target_auth && (!current_auth || url_changed);
    // Tailscale: enable when entering, disable when leaving. The two
    // sides are independent — going `tailscale → url` runs both.
    let prior_is_ts = matches!(prior_kind, Exposure::Tailscale { .. });
    let target_is_ts = matches!(target_exposure, Exposure::Tailscale { .. });
    let needs_tailscale_disable = prior_is_ts && !target_is_ts;
    let needs_tailscale_enable = target_is_ts && !prior_is_ts;

    // Configure is a *user-requested-change applicator*, not a
    // drift-corrector. If the user asked for nothing (no
    // `ConfigureChange` entries) and no cross-service lifecycle step is
    // needed, we return zero steps — even if a `.env` re-render would
    // produce slightly different bytes (e.g. an `{{auth.*}}` template
    // resolving differently because caddy's port shifted since
    // install). Drift correction is what `ryra upgrade` is for; making
    // configure also chase drift produces confusing "nothing changed
    // but I'm restarting your service" runs.
    let no_user_request = changes.is_empty()
        && !needs_unregister
        && !needs_register
        && !needs_tailscale_disable
        && !needs_tailscale_enable;
    let steps = if no_user_request {
        Vec::new()
    } else {
        build_configure_steps(
            service_name,
            &result,
            &reg_service.def,
            &diff,
            current_url.as_deref(),
            target_url.as_deref(),
            needs_unregister,
            needs_register,
            needs_tailscale_disable,
            needs_tailscale_enable,
            minted_oidc.as_ref(),
        )?
    };

    Ok(ConfigureResult {
        service: service_name.to_string(),
        changes,
        diff,
        steps,
        has_destructive,
    })
}

/// Build the upgrade-style file diff from the freshly-planned `WriteFile`
/// steps. Mirrors `upgrade::diff_service` but operates on the already-
/// computed `AddResult` so we don't re-run the planner.
fn build_diff(service_name: &str, result: &AddResult) -> Result<DiffResult> {
    let manifest_file = manifest::manifest_path(service_name)?;
    let (manifest_entries, _) = manifest::load(service_name)?.unwrap_or_default();
    let manifest_by_path: BTreeMap<PathBuf, String> = manifest_entries
        .into_iter()
        .map(|e| (e.path, e.sha256))
        .collect();

    let planned: BTreeMap<PathBuf, String> = result
        .steps
        .iter()
        .filter_map(|s| match s {
            Step::WriteFile(f) => Some((f.path.clone(), f.content.clone())),
            _ => None,
        })
        .collect();

    let existing_env = read_existing_env_keys(service_name)?;
    let env_additions: Vec<EnvAddition> = result
        .tracked_envs
        .iter()
        .filter(|p| !existing_env.contains_key(&p.key))
        .map(|p| EnvAddition {
            key: p.key.clone(),
            value: p.value.clone(),
            kind: p.kind.clone(),
            prompt: p.prompt.clone(),
        })
        .collect();

    let mut entries: Vec<DiffEntry> = Vec::new();
    let mut seen: BTreeSet<PathBuf> = BTreeSet::new();
    let env_filename = std::ffi::OsStr::new(".env");

    for (path, content) in &planned {
        seen.insert(path.clone());
        let planned_hash = manifest::hash_bytes(content.as_bytes());
        let on_disk_hash = if path.exists() {
            Some(manifest::hash_file(path)?)
        } else {
            None
        };
        let manifest_hash = manifest_by_path.get(path);
        let is_env = path.file_name() == Some(env_filename);
        let is_manifest = path == &manifest_file;
        let kind = match (on_disk_hash.as_deref(), manifest_hash.map(String::as_str)) {
            (None, _) => match manifest_hash {
                Some(_) => DiffKind::Modified,
                None => DiffKind::Added,
            },
            (Some(d), _) if d == planned_hash => DiffKind::Unchanged,
            // `.env` and the manifest itself have no manifest entry by
            // design (`.env` because of rotating secrets, the manifest
            // because of self-reference). For both, "no manifest entry"
            // does NOT mean drift — treat them as ryra-owned and safe
            // to overwrite. Without this carve-out they'd always read
            // as Drift on the first configure of a legacy install.
            (Some(_), None) if is_env || is_manifest => DiffKind::Modified,
            (Some(_), None) => DiffKind::Drift,
            (Some(d), Some(l)) if d == l => DiffKind::Modified,
            (Some(_), Some(_)) => DiffKind::Drift,
        };
        entries.push(DiffEntry {
            path: path.clone(),
            kind,
        });
    }
    for path in manifest_by_path.keys() {
        if seen.contains(path) {
            continue;
        }
        entries.push(DiffEntry {
            path: path.clone(),
            kind: DiffKind::Removed,
        });
    }
    entries.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(DiffResult {
        service: service_name.to_string(),
        entries,
        env_additions,
    })
}

/// Assemble the final step list:
///
/// ```text
///   writes → copies → removals
///   → caddy route teardown (url leaving)
///   → OIDC unregister (auth off / url changed with auth)
///   → Tailscale disable (leaving tailscale)
///   → daemon-reload (if any quadlet changed)
///   → caddy reload (if Caddyfile changed)
///   → Tailscale setup + enable (entering tailscale)
///   → OIDC register (auth on / url changed with auth)
///   → restart
/// ```
///
/// `Reload/restart` steps are gated on at least one file actually changing
/// **or** a cross-service lifecycle step needing to run. Without the gate,
/// configure would always restart the unit (phantom downtime) and prompt
/// the user to confirm even when there was literally nothing to apply.
#[allow(clippy::too_many_arguments)]
fn build_configure_steps(
    service_name: &str,
    result: &AddResult,
    service_def: &registry::service_def::ServiceDef,
    diff: &DiffResult,
    current_url: Option<&str>,
    target_url: Option<&str>,
    needs_unregister: bool,
    needs_register: bool,
    needs_tailscale_disable: bool,
    needs_tailscale_enable: bool,
    minted_oidc: Option<&(String, String)>,
) -> Result<Vec<Step>> {
    let unchanged: BTreeSet<PathBuf> = diff
        .entries
        .iter()
        .filter(|e| matches!(e.kind, DiffKind::Unchanged))
        .map(|e| e.path.clone())
        .collect();

    let mut writes: Vec<Step> = Vec::new();
    let mut copies: Vec<Step> = Vec::new();
    let mut kept_caddyfile = false;
    let mut kept_quadlet = false;
    let caddyfile_path = caddy::caddyfile_path().ok();

    let home_dir = service_home(service_name)?;
    for step in &result.steps {
        match step {
            // Install-only — configure issues a Restart at the very end if needed.
            Step::StartService { .. } => continue,
            // Home dir already exists.
            Step::CreateDir(p) if p == &home_dir => continue,
            // Image pulls are idempotent and rare to need on configure.
            Step::PullImage { .. } => continue,
            // Defer until we know whether any write happened.
            Step::DaemonReload | Step::ReloadCaddy | Step::Symlink { .. } => continue,
            // Install-only Tailscale steps — configure decides via the
            // explicit lifecycle flags below.
            Step::TailscaleSetup | Step::TailscaleEnable { .. } | Step::TailscaleDisable { .. } => {
                continue;
            }
            Step::WriteFile(file) => {
                if unchanged.contains(&file.path) {
                    continue;
                }
                if Some(&file.path) == caddyfile_path.as_ref() {
                    kept_caddyfile = true;
                }
                // Quadlet files (`.container`, `.network`, `.volume`, …)
                // live in `service_home/<name>.<ext>` and are *symlinked*
                // into the quadlet dir. Detect by extension: the symlink
                // in quadlet_dir is what `systemctl --user daemon-reload`
                // picks up, but the target it points at is the write
                // path we see here.
                if is_quadlet_filename(&file.path) {
                    kept_quadlet = true;
                }
                writes.push(Step::WriteFile(GeneratedFile {
                    path: file.path.clone(),
                    content: file.content.clone(),
                }));
            }
            Step::CopyFile { src, dst } => {
                copies.push(Step::CopyFile {
                    src: src.clone(),
                    dst: dst.clone(),
                });
            }
            other => copies.push(clone_step(other)),
        }
    }

    // Removed files: planner didn't emit them; rebuild the delete steps.
    let mut removals: Vec<Step> = Vec::new();
    for entry in &diff.entries {
        if matches!(entry.kind, DiffKind::Removed) && entry.path.exists() {
            removals.push(Step::RemoveFile(entry.path.clone()));
        }
    }

    // Caddy route teardown: emit when configure removes the URL *or*
    // when changing to a non-Caddy exposure (Loopback / Tailscale). The
    // add path strips and re-adds the block atomically when the URL
    // changes from one Caddy-routed value to another, so we only need a
    // teardown here for the *leaving Caddy* case.
    let prior_exp = current_url
        .map(Exposure::from_url)
        .unwrap_or(Exposure::Loopback);
    let target_exp = target_url
        .map(Exposure::from_url)
        .unwrap_or(Exposure::Loopback);
    let prior_caddy = matches!(
        prior_exp,
        Exposure::Internal { .. } | Exposure::Public { .. }
    );
    let target_caddy = matches!(
        target_exp,
        Exposure::Internal { .. } | Exposure::Public { .. }
    );
    let mut url_teardown: Vec<Step> = Vec::new();
    if prior_caddy
        && !target_caddy
        && let Some(prev) = current_url
        && let Some(s) = caddy_remove_route_steps(service_name, prev)?
    {
        url_teardown = s;
        kept_caddyfile = true;
    }

    // OIDC unregister + Tailscale disable steps run on the *old* state.
    let mut unregister_steps: Vec<Step> = Vec::new();
    if needs_unregister {
        unregister_steps = authelia::unregister_oidc_client(service_name)?;
    }
    let mut tailscale_disable_steps: Vec<Step> = Vec::new();
    if needs_tailscale_disable
        && let Some(svc_name) = current_url
            .map(Exposure::from_url)
            .as_ref()
            .and_then(|e| e.tailscale_svc_name())
    {
        tailscale_disable_steps.push(Step::TailscaleDisable { svc_name });
    }

    // OIDC register + Tailscale enable steps run on the *new* state.
    let mut register_steps: Vec<Step> = Vec::new();
    if needs_register {
        let (client_id, client_secret) = match minted_oidc {
            Some((id, secret)) => (id.clone(), secret.clone()),
            None => {
                // URL change on a service that was already auth-enabled.
                // Reuse the existing credentials so authelia's new entry
                // matches whatever the service's `.env` already holds.
                let env = read_existing_env_keys(service_name)?;
                let id = service_def
                    .mappings
                    .auth
                    .iter()
                    .find(|(_, v)| v.trim() == "{{auth.client_id}}")
                    .and_then(|(k, _)| env.get(k).map(|v| trim_env_value(v)))
                    .ok_or_else(|| {
                        Error::AuthContext(format!(
                            "service '{service_name}' has auth=oidc in metadata but no \
                             OAUTH_CLIENT_ID-shaped env var found — cannot re-register OIDC \
                             client at the new URL"
                        ))
                    })?;
                let secret = service_def
                    .mappings
                    .auth
                    .iter()
                    .find(|(_, v)| v.trim() == "{{auth.client_secret}}")
                    .and_then(|(k, _)| env.get(k).map(|v| trim_env_value(v)))
                    .unwrap_or_default();
                (id, secret)
            }
        };
        let mut ctx: BTreeMap<String, String> = BTreeMap::new();
        ctx.insert("auth.client_id".into(), client_id);
        ctx.insert("auth.client_secret".into(), client_secret);
        if let Some(u) = target_url {
            ctx.insert("service.url".into(), u.to_string());
        }
        let paths = ConfigPaths::resolve()?;
        let cfg = config::load_or_default(&paths.config_file)?;
        let qdir = quadlet_dir()?;
        register_steps = authelia::register_oidc_client(
            service_name,
            service_def,
            target_url,
            &ctx,
            &cfg,
            &qdir,
        )?;
    }
    let mut tailscale_enable_steps: Vec<Step> = Vec::new();
    if needs_tailscale_enable
        && let Some(svc_name) = target_url
            .map(Exposure::from_url)
            .as_ref()
            .and_then(|e| e.tailscale_svc_name())
    {
        let primary = result
            .allocated_ports
            .iter()
            .find(|(n, _)| n.eq_ignore_ascii_case("http"))
            .or_else(|| result.allocated_ports.first())
            .map(|(_, p)| *p);
        let ts_ports =
            crate::plan::tailscale_ports(&service_def.ports, &result.allocated_ports, primary);
        if !ts_ports.is_empty() {
            tailscale_enable_steps.push(Step::TailscaleSetup);
            tailscale_enable_steps.push(Step::TailscaleEnable {
                svc_name,
                ports: ts_ports,
            });
        }
    }

    let any_file_change = !writes.is_empty() || !removals.is_empty() || !url_teardown.is_empty();
    let any_lifecycle = !unregister_steps.is_empty()
        || !register_steps.is_empty()
        || !tailscale_disable_steps.is_empty()
        || !tailscale_enable_steps.is_empty();
    if !any_file_change && !any_lifecycle {
        return Ok(Vec::new());
    }
    // Restart only when something the *container* actually sees has
    // changed: a quadlet rewrite, a `.env` rewrite, a script/cert
    // appearing or disappearing under service_home, a Caddyfile rewrite
    // that fronts this service, or an OIDC / Tailscale lifecycle step.
    // Metadata-only changes (backup_enabled, smtp_enabled flag) live in
    // `metadata.toml` and don't touch the running unit — restarting on
    // those eats systemd's `StartLimitBurst` budget for no reason.
    // ryra's own bookkeeping files (metadata.toml + service.manifest)
    // never reach the container — they're pure state for `ryra list`,
    // `ryra upgrade`, etc. A write that only touches these doesn't
    // warrant a restart.
    let manifest_file = manifest::manifest_path(service_name).ok();
    let metadata_file = manifest_file
        .as_ref()
        .and_then(|p| p.parent().map(|p| p.join("metadata.toml")));
    let writes_affect_runtime = writes.iter().any(|s| match s {
        Step::WriteFile(f) => {
            Some(&f.path) != metadata_file.as_ref() && Some(&f.path) != manifest_file.as_ref()
        }
        _ => false,
    });
    let needs_restart =
        writes_affect_runtime || !removals.is_empty() || !url_teardown.is_empty() || any_lifecycle;

    let mut steps: Vec<Step> = Vec::new();
    // Forward Symlinks alongside their WriteFile pairs.
    for step in &result.steps {
        if let Step::Symlink { link, target } = step
            && writes
                .iter()
                .any(|s| matches!(s, Step::WriteFile(f) if &f.path == target))
        {
            steps.push(Step::Symlink {
                link: link.clone(),
                target: target.clone(),
            });
        }
    }
    steps.splice(0..0, writes);
    steps.extend(copies);
    steps.extend(removals);
    steps.extend(url_teardown);
    steps.extend(unregister_steps);
    steps.extend(tailscale_disable_steps);
    if kept_quadlet {
        steps.push(Step::DaemonReload);
    }
    if kept_caddyfile {
        steps.push(Step::ReloadCaddy);
    }
    steps.extend(tailscale_enable_steps);
    steps.extend(register_steps);
    if needs_restart {
        steps.push(Step::RestartService {
            unit: service_name.to_string(),
        });
    }
    Ok(steps)
}

/// When configure is dropping a URL, emit the Caddyfile mutation that
/// strips the matching `# Service-Source: registry/<svc>` block, plus a
/// `ReloadCaddy` step. Returns `None` if Caddy isn't installed or no
/// block matches — both legitimate states for a non-Caddy-routed URL.
fn caddy_remove_route_steps(service_name: &str, prior_url: &str) -> Result<Option<Vec<Step>>> {
    use crate::{Capability, find_installed_provider};
    let installed = list_installed().unwrap_or_default();
    if find_installed_provider(&installed, Capability::ReverseProxy).is_none() {
        return Ok(None);
    }
    // Loopback / Tailscale never had a Caddy route — skip the rewrite.
    let prior_exp = Exposure::from_url(prior_url);
    if matches!(prior_exp, Exposure::Loopback | Exposure::Tailscale { .. }) {
        return Ok(None);
    }
    if WellKnownService::Caddy.matches(service_name) {
        return Ok(None);
    }
    let caddyfile_path = caddy::caddyfile_path()?;
    if !caddyfile_path.exists() {
        return Ok(None);
    }
    let existing = std::fs::read_to_string(&caddyfile_path).map_err(|source| Error::FileRead {
        path: caddyfile_path.clone(),
        source,
    })?;
    let updated = caddy::remove_route(&existing, service_name);
    if updated == existing {
        return Ok(None);
    }
    let mut out: Vec<Step> = Vec::new();
    out.push(Step::WriteFile(GeneratedFile {
        path: caddyfile_path,
        content: updated.clone(),
    }));
    if !updated.trim().is_empty() {
        out.push(Step::ReloadCaddy);
    }
    Ok(Some(out))
}

/// Read `.env` and reconstruct the template context entries the planner
/// would otherwise have to regenerate. Every `KEY=VALUE` line whose `KEY`
/// matches one of the service's `{{secret.<name>}}` or `{{auth.<name>}}`
/// references seeds the context with the on-disk value, so `add_service`
/// (called in upgrade mode) reuses the existing credentials verbatim
/// instead of minting fresh ones.
fn recover_template_ctx(
    service_name: &str,
    def: &registry::service_def::ServiceDef,
) -> Result<BTreeMap<String, String>> {
    let existing_env = read_existing_env_keys(service_name)?;
    if existing_env.is_empty() {
        return Ok(BTreeMap::new());
    }
    let mut ctx = BTreeMap::new();

    let collect_secrets = |value: &str, out: &mut Vec<String>| {
        let mut rest = value;
        while let Some(start) = rest.find("{{secret.") {
            let after = &rest[start + 9..];
            if let Some(end) = after.find("}}") {
                out.push(after[..end].to_string());
                rest = &after[end + 2..];
            } else {
                break;
            }
        }
    };
    let collect_auth = |value: &str, out: &mut Vec<String>| {
        for needle in ["{{auth.client_id", "{{auth.client_secret"] {
            if value.contains(needle) {
                let stripped = needle.trim_start_matches("{{auth.");
                out.push(stripped.to_string());
            }
        }
    };

    let mut secret_pairs: Vec<(String, String)> = Vec::new();
    let mut auth_keys: Vec<String> = Vec::new();

    let mut consider = |env: &registry::service_def::EnvVar| {
        let trimmed = env.value.trim();
        if let Some(name) = trimmed
            .strip_prefix("{{secret.")
            .and_then(|s| s.strip_suffix("}}"))
            && let Some(live) = existing_env.get(&env.name)
        {
            secret_pairs.push((name.to_string(), trim_env_value(live)));
        }
        let mut extras: Vec<String> = Vec::new();
        collect_secrets(&env.value, &mut extras);
        for n in extras {
            if !secret_pairs.iter().any(|(k, _)| k == &n) {
                secret_pairs.push((n, String::new()));
            }
        }
        let mut auth_refs: Vec<String> = Vec::new();
        collect_auth(&env.value, &mut auth_refs);
        for n in auth_refs {
            if !auth_keys.contains(&n) {
                auth_keys.push(n);
            }
        }
    };

    for e in &def.env {
        consider(e);
    }
    for g in &def.env_groups {
        for e in &g.env {
            consider(e);
        }
    }
    for (env_name, value_template) in &def.mappings.auth {
        let env = registry::service_def::EnvVar {
            name: env_name.clone(),
            value: value_template.clone(),
            kind: Default::default(),
            prompt: None,
            format: Default::default(),
            length: None,
            jwt_claims: None,
            jwt_signing_key: None,
        };
        consider(&env);
    }

    for (name, value) in &secret_pairs {
        if !value.is_empty() {
            ctx.insert(format!("secret.{name}"), value.clone());
        }
    }
    for (env_name, value_template) in &def.mappings.auth {
        let trimmed = value_template.trim();
        if let Some(rest) = trimmed
            .strip_prefix("{{auth.")
            .and_then(|s| s.strip_suffix("}}"))
            && let Some(live) = existing_env.get(env_name)
        {
            ctx.insert(format!("auth.{rest}"), trim_env_value(live));
        }
    }

    Ok(ctx)
}

fn trim_env_value(raw: &str) -> String {
    raw.trim_matches(|c: char| c == '"' || c == '\'')
        .to_string()
}

/// True when `path`'s filename ends in a podman-quadlet extension. Quadlet
/// regenerates a `.service` per matching file on every
/// `systemctl --user daemon-reload`, so a write to any of these means we
/// need to emit a reload before restarting.
fn is_quadlet_filename(path: &std::path::Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some("container" | "volume" | "network" | "kube" | "image" | "pod" | "build")
    )
}

/// Parse the on-disk `.env` for a service into a key→value map.
fn read_existing_env_keys(service_name: &str) -> Result<BTreeMap<String, String>> {
    let env_path = service_home(service_name)?.join(".env");
    let mut out: BTreeMap<String, String> = BTreeMap::new();
    let content = match std::fs::read_to_string(&env_path) {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
        Err(source) => {
            return Err(Error::FileRead {
                path: env_path,
                source,
            });
        }
    };
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some((k, v)) = line.split_once('=') {
            out.insert(k.trim().to_string(), v.to_string());
        }
    }
    Ok(out)
}

/// Pin existing host ports across re-renders.
fn read_existing_ports(service_name: &str) -> Result<BTreeMap<String, u16>> {
    let env_path = service_home(service_name)?.join(".env");
    let mut overrides = BTreeMap::new();
    let content = match std::fs::read_to_string(&env_path) {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(overrides),
        Err(source) => {
            return Err(Error::FileRead {
                path: env_path,
                source,
            });
        }
    };
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let Some(name) = key.strip_prefix("SERVICE_PORT_") else {
            continue;
        };
        if let Ok(port) = value.trim().parse::<u16>() {
            overrides.insert(name.to_ascii_lowercase(), port);
        }
    }
    Ok(overrides)
}

/// Clone a `Step` explicitly. `Step` carries non-`Clone` payloads in
/// places; we list each variant so a new one forces a compile error
/// here rather than silently being dropped.
fn clone_step(step: &Step) -> Step {
    match step {
        Step::WriteFile(f) => Step::WriteFile(GeneratedFile {
            path: f.path.clone(),
            content: f.content.clone(),
        }),
        Step::Symlink { link, target } => Step::Symlink {
            link: link.clone(),
            target: target.clone(),
        },
        Step::DaemonReload => Step::DaemonReload,
        Step::StartService { unit } => Step::StartService { unit: unit.clone() },
        Step::StopService { unit } => Step::StopService { unit: unit.clone() },
        Step::RestartService { unit } => Step::RestartService { unit: unit.clone() },
        Step::ReloadCaddy => Step::ReloadCaddy,
        Step::PullImage { image } => Step::PullImage {
            image: image.clone(),
        },
        Step::RemoveFile(p) => Step::RemoveFile(p.clone()),
        Step::RemoveDir(p) => Step::RemoveDir(p.clone()),
        Step::RemoveVolume { name } => Step::RemoveVolume { name: name.clone() },
        Step::RemoveNetwork { name } => Step::RemoveNetwork { name: name.clone() },
        Step::CreateDir(p) => Step::CreateDir(p.clone()),
        Step::WaitForFile { path, timeout_secs } => Step::WaitForFile {
            path: path.clone(),
            timeout_secs: *timeout_secs,
        },
        Step::CopyFile { src, dst } => Step::CopyFile {
            src: src.clone(),
            dst: dst.clone(),
        },
        Step::Build { dir, command } => Step::Build {
            dir: dir.clone(),
            command: command.clone(),
        },
        Step::TailscaleSetup => Step::TailscaleSetup,
        Step::TailscaleEnable { svc_name, ports } => Step::TailscaleEnable {
            svc_name: svc_name.clone(),
            ports: ports.clone(),
        },
        Step::TailscaleDisable { svc_name } => Step::TailscaleDisable {
            svc_name: svc_name.clone(),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The is_destructive matrix is the safety contract: it decides
    /// whether the CLI demands typed confirmation. One table-driven test
    /// makes it cheap to spot a regression in any cell.
    #[test]
    fn destructive_classification() {
        let url = |from: Option<&str>, to: Option<&str>| ConfigureChange::Url {
            from: from.map(str::to_string),
            to: to.map(str::to_string),
        };
        let cases: &[(ConfigureChange, bool)] = &[
            // URL: changing or removing destroys old routes / OAuth callbacks.
            (url(Some("https://old"), Some("https://new")), true),
            (url(Some("https://old"), None), true),
            (url(None, Some("https://new")), false),
            (url(Some("https://x"), Some("https://x")), false),
            // Toggles: only the off direction is destructive.
            (
                ConfigureChange::Smtp {
                    from: true,
                    to: false,
                },
                true,
            ),
            (
                ConfigureChange::Smtp {
                    from: false,
                    to: true,
                },
                false,
            ),
            (
                ConfigureChange::Backup {
                    from: true,
                    to: false,
                },
                true,
            ),
            (
                ConfigureChange::Backup {
                    from: false,
                    to: true,
                },
                false,
            ),
            (
                ConfigureChange::Auth {
                    from: true,
                    to: false,
                },
                true,
            ),
            (
                ConfigureChange::Auth {
                    from: false,
                    to: true,
                },
                false,
            ),
            // Group disable drops env vars; enable just adds them.
            (ConfigureChange::GroupDisabled("oauth".into()), true),
            (ConfigureChange::GroupEnabled("oauth".into()), false),
            // Explicit user override: never a surprise.
            (
                ConfigureChange::EnvOverride {
                    key: "ADMIN_EMAIL".into(),
                    from: Some("a".into()),
                    to: "b".into(),
                },
                false,
            ),
        ];
        for (change, expected) in cases {
            assert_eq!(
                change.is_destructive(),
                *expected,
                "wrong classification for {change:?}"
            );
        }
    }
}