ryra 0.1.1

A tool to test and deploy self-hosted services on a Linux server using rootless Podman and systemd. Built-in VM testing gives AI agents fast feedback loops for building infrastructure and deploying apps.
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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
use std::collections::{BTreeMap, BTreeSet};
use std::io::IsTerminal;

use anyhow::{Result, bail};
use dialoguer::{Confirm, Input};

use ryra_core::caddy::AcmeMode;
use ryra_core::config::ConfigPaths;
use ryra_core::config::schema::Config;
use ryra_core::registry::resolve::ServiceRef;
use ryra_core::registry::service_def::{AuthKind, HttpsRequirement, ServiceKind};
use ryra_core::{
    Capability, REGISTRY_BUNDLED, Warning, WellKnownService, find_installed_provider,
    service_provides,
};

use super::apply;
use super::prompts;

/// Default port for Caddy's HTTPS listener.
const DEFAULT_CADDY_HTTPS_PORT: u16 = 8443;
/// Default port for Authelia's HTTP listener.
const DEFAULT_AUTHELIA_PORT: u16 = 9091;
/// Inbucket's internal SMTP container port.
const INBUCKET_SMTP_PORT: u16 = 2500;

/// Non-interactive choice for `--smtp=…` on `ryra add`.
///
/// Modelled as an enum so the compiler rejects typos at the CLI boundary
/// and so we can grow additional providers (e.g. an explicit
/// `--smtp=custom --smtp-host=… --smtp-port=…` combo) without breaking
/// the existing call sites.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum SmtpProvider {
    /// Auto-install inbucket and wire `config.smtp` to it. For testing
    /// and local development — inbucket is a disposable SMTP sink with a
    /// web UI and an HTTP API for inspecting received mail.
    Inbucket,
}

#[allow(clippy::too_many_arguments)]
pub async fn run(
    services: &[String],
    url: Option<&str>,
    auth: bool,
    smtp: Option<SmtpProvider>,
    enable: &[String],
    tailscale: bool,
    acme: Option<&AcmeMode>,
    dry_run: bool,
    yes: bool,
) -> Result<()> {
    if url.is_some() && services.len() > 1 {
        bail!("--url can only be used when adding a single service");
    }
    if !enable.is_empty() && services.len() > 1 {
        bail!("--enable can only be used when adding a single service");
    }
    // --acme drives caddy's TLS mode. It's accepted on any `ryra add`:
    // when adding caddy directly it sets the snippet; when adding a
    // service with `--url <public>` it auto-installs caddy in ACME mode
    // before the service is added (non-interactive equivalent of the
    // TLS prompt below).

    // When this run is the one installing caddy in ACME mode, offer to
    // lower `net.ipv4.ip_unprivileged_port_start` so Caddy binds 80/443
    // directly. The check has to run before add_service, because that's
    // where the caddy quadlet's `PublishPort=` is generated based on the
    // current sysctl value. Skipped silently if already enabled, or for
    // LAN/Tailscale paths where 8080/8443 is fine.
    if acme.is_some()
        && services
            .iter()
            .any(|s| service_provides(s, Capability::ReverseProxy))
    {
        super::sysctl_low_ports::offer_enable().await?;
    }

    let preflight_paths = ryra_core::config::ConfigPaths::resolve()?;
    let preflight_config = ryra_core::config::load_or_default(&preflight_paths.config_file)?;
    let issues = ryra_core::system::doctor::check_all(&preflight_config);
    let blockers: Vec<&ryra_core::system::doctor::Issue> = issues
        .iter()
        .filter(|i| i.severity() == ryra_core::system::doctor::Severity::Blocker)
        .collect();
    if !blockers.is_empty() {
        let rendered = blockers
            .iter()
            .map(|i| i.to_string())
            .collect::<Vec<_>>()
            .join("\n\n");
        bail!("ryra doctor reports blockers:\n\n{rendered}");
    }
    // Surface non-blocking issues but don't gate the install — `ryra
    // doctor` is the place to see the full list with fixes.
    if issues.iter().any(|i| {
        matches!(
            i.severity(),
            ryra_core::system::doctor::Severity::Warning
                | ryra_core::system::doctor::Severity::Info
        )
    }) {
        eprintln!("Note: `ryra doctor` reports issues — run it to see them.");
    }

    // --tailscale check fires here so a missing CLI / unlogged tailnet
    // surfaces before any service planning. Stays separate from the
    // unified doctor view because tailscale issues are only relevant
    // when the user explicitly opts into the tailscale path.
    if tailscale && let Err(e) = ryra_core::system::doctor::check_tailscale_runtime() {
        bail!("--tailscale flag passed but {e}");
    }

    let interactive = super::is_interactive();

    // Tailscale admin API token acquisition: when `--tailscale` is set
    // and we don't already have one cached from a previous install,
    // prompt the user to paste one (or read TAILSCALE_API_KEY in
    // non-interactive runs). Saved to `config.tailscale.admin_api_key`.
    // Done up-front so a missing token fails fast, before any image
    // pulls or service planning. The token is needed at install time
    // (define service via API) and removal time (delete service).
    if tailscale && !dry_run {
        ensure_tailscale_admin_token(interactive).await?;
    }

    // "First add" = no ryra config on disk yet. Latch the answer before any
    // side-effect creates the file — we use this at the end to decide between
    // offering to enable lingering (ceremonial, worth the interaction) and
    // just warning (quieter, for every subsequent add).
    let first_run = !ryra_core::config::ConfigPaths::resolve()?
        .config_file
        .exists();

    // Auto-install authelia for --auth
    if !dry_run {
        ensure_dependencies(auth, tailscale, interactive).await?;
    }

    // --smtp=<provider>: non-interactive equivalent of the prompts below.
    // Runs once before the per-service loop so every SMTP-using service in
    // the same batch picks up the newly-written config.smtp.
    if let Some(provider) = smtp
        && !dry_run
    {
        ensure_smtp_for_add(provider).await?;
    }

    let paths = ryra_core::config::ConfigPaths::resolve()?;

    // Serialize concurrent `ryra add --auth` runs so two processes don't
    // clobber each other's client entries when editing authelia's
    // configuration.yml in-memory then writing it back. The lock is
    // released when _auth_lock drops at end of this function.
    let _auth_lock = if auth && !dry_run {
        paths.ensure_dirs()?;
        let lock_path = paths.config_dir.join(".authelia-oidc.lock");
        let file = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&lock_path)?;
        file.lock()?;
        Some(file)
    } else {
        None
    };

    for service_input in services {
        let service_ref = ServiceRef::parse(service_input)?;
        let repo_dir = ryra_core::resolve_registry_dir(&service_ref).await?;
        let service = service_ref.service_name();

        // Bail before prompts — the same check fires deeper in
        // `ryra_core::add_service`, but only after SMTP / auth prompts have
        // already burned the user's time. Surface it up-front instead.
        if !dry_run && ryra_core::is_service_installed(service) {
            bail!("service {service} is already installed");
        }

        // Load config once — previous iterations or ensure_dependencies may have
        // modified it on disk (e.g., installing caddy or authelia).
        let mut config = ryra_core::config::load_or_default(&paths.config_file)?;

        // Orphan-data check: `ryra remove <svc>` (preserve mode) drops the
        // service from config but leaves named volumes and data dirs on disk.
        // A fresh `ryra add` would silently inherit them — surprising when
        // the user wants a clean state. Surface it here so they choose.
        if !dry_run
            && !ryra_core::is_service_installed(service)
            && let Some(orphan) = ryra_core::data::enumerate_service(service)?
            && orphan.status == ryra_core::data::ServiceStatus::Orphan
            && (!orphan.volumes.is_empty() || !orphan.data_paths.is_empty())
        {
            println!("\n  '{service}' has data from a previous install (orphaned on disk):");
            for v in &orphan.volumes {
                println!("    volume: {}", v.name);
            }
            for p in &orphan.data_paths {
                println!("    data:   {}", p.display());
            }
            println!("\n  Proceeding will reuse this data (podman reuses named volumes by name).");
            if interactive && !yes {
                let proceed = Confirm::new()
                    .with_prompt(format!("Continue adding {service} with existing data?"))
                    .default(true)
                    .interact()?;
                if !proceed {
                    println!("\nCancelled. To purge and start clean:");
                    println!("  ryra remove {service} --purge");
                    println!("  ryra add {service}");
                    return Ok(());
                }
            } else {
                println!(
                    "  (use --yes to auto-accept, or run `ryra remove {service} --purge` first to start clean)"
                );
            }
        }

        // Look up the service definition
        let reg_service = ryra_core::registry::find_service(&repo_dir, service)?;

        // Check architecture compatibility before any prompts
        if let Some(msg) = reg_service.def.check_architecture() {
            bail!("{msg}");
        }

        // Warn about untrusted registry services — they can run arbitrary
        // scripts via quadlet ExecStartPre/Post and mount host directories.
        if service_ref.registry_name() != REGISTRY_BUNDLED && !yes && !dry_run {
            warn_untrusted_service(&reg_service.service_dir, service, interactive)?;
        }

        // SMTP — decide whether to wire this specific service into email.
        //   * Global SMTP already configured → Confirm default yes (reuse it).
        //   * No global SMTP yet → show Skip/Custom/Inbucket select, default Skip.
        //   * Non-interactive → opt in iff SMTP is already configured globally.
        let service_supports_smtp =
            reg_service.def.integrations.smtp && !reg_service.def.mappings.smtp.is_empty();
        let enable_smtp: bool = if !service_supports_smtp || dry_run {
            false
        } else if interactive {
            if config.smtp.is_some() {
                Confirm::new()
                    .with_prompt("Use SMTP for this service?")
                    .default(true)
                    .interact()?
            } else {
                match prompts::prompt_smtp()? {
                    prompts::SmtpSetupChoice::Custom(smtp) => {
                        let had_secrets_before = config.has_secrets();
                        config.smtp = Some(smtp);
                        paths.ensure_dirs()?;
                        ryra_core::config::save_config(&paths.config_file, &config)?;
                        println!(
                            "  SMTP configured. Saved to {}\n",
                            paths.config_file.display()
                        );
                        warn_if_first_secret_save(&paths, had_secrets_before, &config);
                        true
                    }
                    prompts::SmtpSetupChoice::Inbucket => {
                        if !ryra_core::is_service_installed("inbucket") {
                            println!("\nInstalling inbucket...\n");
                            Box::pin(run(
                                &[WellKnownService::Inbucket.to_string()],
                                None,
                                false,
                                None,
                                &[],
                                false,
                                None,
                                false,
                                true,
                            ))
                            .await?;
                            // Reload — inbucket install modified config on disk
                            config = ryra_core::config::load_or_default(&paths.config_file)?;
                        }
                        // Use container name for SMTP host — services on the
                        // caddy network can reach inbucket directly. The host
                        // port isn't reachable from --no-hosts containers.
                        let had_secrets_before = config.has_secrets();
                        config.smtp = Some(ryra_core::config::schema::SmtpCredentials {
                            host: "inbucket".to_string(),
                            port: INBUCKET_SMTP_PORT, // inbucket's internal container port
                            username: String::new(),
                            password: String::new(),
                            from: "noreply@example.com".to_string(),
                            security: ryra_core::config::schema::SmtpSecurity::Off,
                        });
                        paths.ensure_dirs()?;
                        ryra_core::config::save_config(&paths.config_file, &config)?;
                        println!(
                            "  SMTP configured (inbucket). Saved to {}\n",
                            paths.config_file.display()
                        );
                        warn_if_first_secret_save(&paths, had_secrets_before, &config);
                        true
                    }
                    prompts::SmtpSetupChoice::Skip => false,
                }
            }
        } else {
            config.smtp.is_some()
        };

        // Auth — determined by --auth flag or interactive prompt
        let auth_kind: Option<AuthKind> = resolve_auth_kind(
            auth,
            interactive,
            &reg_service.def.integrations.auth,
            config.auth.is_some(),
        )?;

        // Resolve exposure BEFORE auto-installing authelia so the provider
        // inherits the parent's choice. Picking the two separately let users
        // mismatch (authelia local + service tailnet → tailnet clients can't
        // reach `authelia.internal` for OIDC redirects). One prompt, one
        // decision, propagated.
        let needs_https = needs_https(
            reg_service.def.service.https.clone(),
            auth_kind.is_some(),
            url,
        );

        // True iff this run will auto-install authelia. Used both to show a
        // "(authelia will inherit this choice)" hint in the exposure prompt
        // and to drive the propagation below.
        let will_install_authelia = auth_kind.is_some() && config.auth.is_none();

        // Resolve a single typed `Exposure` once — replaces the prior
        // `(resolved_url, tailscale_enabled)` pair so downstream code
        // can pattern-match instead of juggling a parallel
        // `(Option<String>, bool)` that allowed silently invalid combos
        // like a `*.ts.net` URL with `tailscale_enabled = false`.
        //
        // Precedence:
        //   1. explicit --url (classified by hostname suffix)
        //   2. --tailscale → derive `<service>.<tailnet>.ts.net`
        //   3. Caddy installed + needs_https → auto-derive `*.internal`
        //   4. interactive prompt (Self-signed / Tailscale / Public+LE /
        //      External) when needs_https and Caddy isn't installed —
        //      Loopback isn't offered because the service rejects HTTP.
        //   5. interactive prompt for any user-facing app (kind=application)
        //      that doesn't require HTTPS — same options plus Loopback as
        //      the default. Surfaces tailscale/public exposure for services
        //      like vikunja that work fine over HTTP but the user might
        //      still want on a tailnet.
        //   6. Loopback — service runs on plain http://127.0.0.1:<port>
        //      (non-interactive default, and the choice for infrastructure
        //      services like inbucket that aren't user-facing).
        // Clap's `conflicts_with = "url"` on --tailscale means 1+2 don't collide.
        let is_user_facing_app = matches!(reg_service.def.service.kind, ServiceKind::Application);
        let exposure: ryra_core::Exposure = if let Some(u) = url {
            ryra_core::Exposure::from_url(u)
        } else if tailscale {
            let ts_url = derive_tailscale_url(service)?;
            println!("→ Using {ts_url} (Tailscale)");
            ryra_core::Exposure::Tailscale { url: ts_url }
        } else if needs_https {
            if ryra_core::is_service_installed("caddy") {
                let installed_all = ryra_core::list_installed().unwrap_or_default();
                let caddy_https_port =
                    find_installed_provider(&installed_all, Capability::ReverseProxy)
                        .and_then(|s| s.ports.get("https").copied())
                        .unwrap_or(DEFAULT_CADDY_HTTPS_PORT);
                let default_url = format!(
                    "https://{service}.{}:{caddy_https_port}",
                    ryra_core::config::schema::CADDY_LOCAL_DOMAIN
                );
                let chosen = if interactive && !dry_run {
                    Input::new()
                        .with_prompt(format!("URL for '{service}'"))
                        .default(default_url)
                        .interact_text()?
                } else {
                    default_url
                };
                ryra_core::Exposure::from_url(&chosen)
            } else if interactive && !dry_run {
                let chosen = prompt_exposure_for(service, will_install_authelia, false).await?;
                // Reload after potential Caddy install inside the prompt.
                config = ryra_core::config::load_or_default(&paths.config_file)?;
                chosen
            } else {
                bail!(
                    "service '{service}' requires HTTPS but no exposure was selected.\n\
                     Pass --tailscale, --url <X>, or `ryra add caddy` first to enable \
                     local HTTPS."
                );
            }
        } else if is_user_facing_app && interactive && !dry_run {
            let chosen = prompt_exposure_for(service, false, true).await?;
            // Reload — picking Self-signed / Public+LE installs Caddy, which
            // mutates config on disk.
            config = ryra_core::config::load_or_default(&paths.config_file)?;
            chosen
        } else {
            ryra_core::Exposure::Loopback
        };
        // Derive locals for downstream code that still threads the legacy
        // shape (env templating, OIDC client registration). Goes away as
        // each call site migrates to take `&Exposure` directly.
        let url: Option<&str> = exposure.url();
        let tailscale_enabled: bool = exposure.is_tailscale();

        // Auto-install Caddy when the user gives a public URL but Caddy
        // isn't installed yet. Without this, the install would succeed
        // but the URL wouldn't actually route anywhere — the user would
        // have to know to add Caddy first, which the previous flow
        // forced and most people forget.
        let caddy_already_installed = ryra_core::is_service_installed("caddy");
        let need_caddy_for_public_url = url.is_some_and(ryra_core::is_public_url)
            && !caddy_already_installed
            && !service_provides(service, Capability::ReverseProxy)
            && !tailscale_enabled
            && !dry_run;
        if need_caddy_for_public_url {
            let chosen = match acme {
                Some(mode) => Some(TlsHandling::LetsEncrypt(mode.clone())),
                None if interactive => Some(prompt_tls_for_public_url(url.unwrap_or("")).await?),
                None => None,
            };
            match chosen {
                Some(TlsHandling::LetsEncrypt(mode)) => {
                    if let Some(u) = url {
                        dns_preflight_for_acme(u, interactive).await?;
                    }
                    println!("\nInstalling caddy (Let's Encrypt mode)...\n");
                    Box::pin(run(
                        &[WellKnownService::Caddy.to_string()],
                        None,
                        false,
                        None,
                        &[],
                        false,
                        Some(&mode),
                        false,
                        true,
                    ))
                    .await?;
                    config = ryra_core::config::load_or_default(&paths.config_file)?;
                }
                Some(TlsHandling::SelfSigned) => {
                    println!("\nInstalling caddy (self-signed LAN mode)...\n");
                    Box::pin(run(
                        &[WellKnownService::Caddy.to_string()],
                        None,
                        false,
                        None,
                        &[],
                        false,
                        None,
                        false,
                        true,
                    ))
                    .await?;
                    config = ryra_core::config::load_or_default(&paths.config_file)?;
                }
                Some(TlsHandling::External) | None => {
                    // Skip Caddy install — user is fronting with their own
                    // reverse proxy (Cloudflare Tunnel, nginx, etc.). The
                    // existing `UrlWithoutReverseProxy` warning still fires
                    // from add_service so the user knows routing is on them.
                }
            }
        } else if acme.is_some()
            && caddy_already_installed
            && !service_provides(service, Capability::ReverseProxy)
        {
            // --acme passed but Caddy is already installed — the snippet
            // is set; flipping mode means editing tls.caddy directly.
            // Warn but don't bail; let the install proceed.
            eprintln!(
                "\nNote: --acme is ignored — caddy is already installed.\n  \
                 Edit ~/.local/share/services/caddy/config/tls.caddy to switch TLS mode.\n"
            );
        }

        // Authelia already exists — make sure its exposure isn't narrower
        // than the service we're about to add. Local-only authelia + tailnet
        // service silently breaks OIDC redirects for off-host clients.
        if auth_kind.is_some() && config.auth.is_some() {
            check_auth_exposure_compat(&config, service, url)?;
        }

        // If the user chose auth but no provider is configured, install one,
        // passing `tailscale_enabled` so authelia inherits the parent's
        // exposure (Local → caddy already up from the prompt → auto-derives
        // `*.internal`; Tailscale → propagates --tailscale; Custom → falls
        // through to authelia's own exposure resolution since custom URLs
        // are per-service and can't be inherited).
        if will_install_authelia {
            if !ensure_auth_for_add(&mut config, &paths, dry_run, tailscale_enabled).await? {
                return Ok(());
            }
            // Reload — ensure_auth_for_add may have installed authelia
            config = ryra_core::config::load_or_default(&paths.config_file)?;
        }

        // Prompt for env vars based on their kind
        use ryra_core::registry::service_def::EnvKind;

        let mut env_overrides = BTreeMap::new();
        let mut prompt_ctx: Option<BTreeMap<String, String>> = None;

        // Validate every --enable name up front — fail fast on typos rather
        // than silently ignoring unknown groups.
        let known_group_names: BTreeSet<&str> = reg_service
            .def
            .env_groups
            .iter()
            .map(|g| g.name.as_str())
            .collect();
        for g in enable {
            if !known_group_names.contains(g.as_str()) {
                let hint = if known_group_names.is_empty() {
                    format!("service '{service}' defines no env_groups")
                } else {
                    let known: Vec<&str> = known_group_names.iter().copied().collect();
                    format!(
                        "service '{service}' has no env_group '{g}' (known: {})",
                        known.join(", ")
                    )
                };
                bail!("{hint}");
            }
        }
        let mut enabled_groups: BTreeSet<String> = enable.iter().cloned().collect();

        let has_promptable_top = reg_service
            .def
            .env
            .iter()
            .any(|e| matches!(e.kind, EnvKind::Prompted | EnvKind::Required));
        let has_groups = !reg_service.def.env_groups.is_empty();

        if (has_promptable_top || has_groups) && interactive {
            // Resolve template variables in defaults so prompts show real values.
            // This context is reused by add_service so the secrets the user saw
            // during prompts match what gets written to .env.
            let default_ctx = ryra_core::generate::context::build_context(
                &config,
                &reg_service.def,
                None,
                auth_kind.as_ref(),
                url,
                enable_smtp,
            )?;
            prompt_ctx = Some(default_ctx.clone());

            println!("\nConfigure {service}:");

            // Interactive group toggles — ask y/N for each group, then prompt
            // its required/prompted members if the user opted in. Groups
            // passed via --enable are treated as already on (no re-prompt).
            for group in &reg_service.def.env_groups {
                if !enabled_groups.contains(&group.name) {
                    let enabled = Confirm::new()
                        .with_prompt(format!("  {}", group.prompt))
                        .default(false)
                        .interact()?;
                    if !enabled {
                        continue;
                    }
                    enabled_groups.insert(group.name.clone());
                }
                for env in &group.env {
                    if !matches!(env.kind, EnvKind::Prompted | EnvKind::Required) {
                        continue;
                    }
                    prompt_env(env, &default_ctx, &mut env_overrides)?;
                }
            }

            // Top-level prompted/required envs.
            for env in &reg_service.def.env {
                if !matches!(env.kind, EnvKind::Prompted | EnvKind::Required) {
                    continue;
                }
                prompt_env(env, &default_ctx, &mut env_overrides)?;
            }
            println!();
        } else if !interactive {
            // Non-interactive: read env vars from the process environment.
            // Required vars must be set; prompted vars use their default but
            // can be overridden via the environment. Members of groups that
            // aren't `--enable`d are ignored entirely — they won't be written
            // to `.env`, so missing them is not an error.
            let mut missing_required = Vec::new();
            for env in &reg_service.def.env {
                if !matches!(env.kind, EnvKind::Prompted | EnvKind::Required) {
                    continue;
                }
                collect_non_interactive(env, &mut env_overrides, &mut missing_required);
            }
            for group in &reg_service.def.env_groups {
                if !enabled_groups.contains(&group.name) {
                    continue;
                }
                for env in &group.env {
                    if !matches!(env.kind, EnvKind::Prompted | EnvKind::Required) {
                        continue;
                    }
                    collect_non_interactive(env, &mut env_overrides, &mut missing_required);
                }
            }
            if !missing_required.is_empty() {
                bail!(
                    "required env vars not provided (run interactively or set via env): {}",
                    missing_required.join(", ")
                );
            }
        }

        // --acme only takes effect when first installing the reverse
        // proxy itself — after that, the TLS snippet is user-managed.
        // Filter so it only flows for the reverse-proxy service (the
        // top-level guard already rejects other combos).
        let acme_for_service = if service_provides(service, Capability::ReverseProxy) {
            acme
        } else {
            None
        };

        // If a previous add failed partway, clean up before retrying.
        let result = match ryra_core::add_service(
            service,
            &exposure,
            auth_kind.clone(),
            auth || auth_kind.is_some(),
            enable_smtp,
            &env_overrides,
            &enabled_groups,
            service_ref.registry_name(),
            &repo_dir,
            prompt_ctx.clone(),
            &super::is_port_in_use,
            acme_for_service,
            ryra_core::PlanMode::Add,
            &BTreeMap::new(),
        ) {
            Err(ryra_core::error::Error::ServiceIncomplete(_)) => {
                // Two cases land here: a previous `ryra add` crashed mid-way
                // (config entry with installed=false), or the user ran
                // `ryra remove <svc>` without --purge and now wants to
                // re-add (no config entry but volumes/home-dir survive).
                // Both produce credential mismatches if we just regenerate
                // secrets on top of existing volumes — recover by purging
                // + reinstalling, but don't do that silently: data loss
                // deserves a confirmation.
                if interactive && !yes {
                    println!("\n  '{service}' has preserved data from a previous install.");
                    println!("  Reinstalling will delete the named volume(s) and service dir.");
                    println!("  Inspect with: ryra data ls\n");
                    let proceed = Confirm::new()
                        .with_prompt(format!("Purge existing data and reinstall {service}?"))
                        .default(false)
                        .interact()?;
                    if !proceed {
                        println!("\nCancelled. To purge and reinstall later:");
                        println!("  ryra remove {service} --purge");
                        println!("  ryra add {service}");
                        return Ok(());
                    }
                }
                println!("{service} has leftover state — cleaning up before retry...");

                // `remove_service` reconstructs metadata from the
                // quadlet headers when available — use it whenever the
                // marker'd `.container` is on disk. For pure-orphan
                // state (data only, no quadlet) fall back to the
                // orphan-purge path.
                if ryra_core::is_service_installed(service) {
                    let remove_result =
                        ryra_core::remove_service(service, ryra_core::RemoveMode::Purge)?;
                    apply::execute_all(&remove_result.steps).await?;
                    ryra_core::finalize_remove(service)?;
                } else {
                    let svc_data =
                        ryra_core::data::enumerate_service(service)?.ok_or_else(|| {
                            anyhow::anyhow!(
                                "internal: ServiceIncomplete for '{service}' but no state found"
                            )
                        })?;
                    let steps = ryra_core::orphan_purge_steps(&svc_data);
                    apply::execute_all(&steps).await?;
                }
                // The killed previous install may have reserved a Tailscale
                // port; cleanup just removed that reservation, so re-allocate
                // against the freshly-cleaned config to reclaim the originally
                // intended port (e.g. 443 instead of skipping to 8443).
                // (No URL re-resolution needed: with per-service tailnet
                // nodes, the URL is `https://<service>.<tailnet>/` and
                // doesn't depend on any pool that the killed previous
                // install might have reserved.)
                // Retry now that the partial state is gone
                ryra_core::add_service(
                    service,
                    &exposure,
                    auth_kind.clone(),
                    auth || auth_kind.is_some(),
                    enable_smtp,
                    &env_overrides,
                    &enabled_groups,
                    service_ref.registry_name(),
                    &repo_dir,
                    prompt_ctx.clone(),
                    &super::is_port_in_use,
                    acme_for_service,
                    ryra_core::PlanMode::Add,
                    &BTreeMap::new(),
                )?
            }
            other => other?,
        };

        // (--tailscale: the per-service sidecar quadlet — `ts-<service>` —
        // gets generated by add_service when `tailscale_enabled` is set.
        // No host-side `tailscale serve` step is needed; each service has
        // its own tailscaled now.)

        // Show warnings and confirm
        // Show port reassignment notes + reverse-proxy hints (both informational).
        for warning in &result.warnings {
            match warning {
                Warning::PortReassigned {
                    port_name,
                    original_port,
                    assigned_port,
                    reason,
                    ..
                } => {
                    // Privileged ports are just informational — nothing the user can do
                    // in rootless podman. "In use" ports are actionable — the user might
                    // want to stop whatever is occupying the port.
                    if *original_port < 1024 {
                        println!("  {port_name} port {original_port}{assigned_port} ({reason})");
                    } else {
                        println!(
                            "  {} {port_name} port {original_port}{assigned_port} ({reason})",
                            super::style::warning()
                        );
                    }
                }
                Warning::UrlWithoutReverseProxy {
                    service_name,
                    url,
                    host_port,
                } => {
                    println!(
                        "  {} --url was set for {service_name} but no bundled reverse proxy \
                         (Caddy) is installed. Ryra will template {url} into the service but \
                         won't configure routing — point your own reverse proxy (nginx, \
                         Cloudflare Tunnel, Tailscale Funnel, etc.) at 127.0.0.1:{host_port}, \
                         or run `ryra add caddy` to let ryra handle it.",
                        super::style::note()
                    );
                }
                Warning::RamBelowMinimum { .. } | Warning::RamBelowRecommended { .. } => {}
            }
        }

        // Collect warnings that need confirmation (RAM + port conflicts)
        let needs_confirm: Vec<_> = result
            .warnings
            .iter()
            .filter(|w| match w {
                Warning::RamBelowMinimum { .. } | Warning::RamBelowRecommended { .. } => true,
                Warning::PortReassigned { original_port, .. } => *original_port >= 1024,
                Warning::UrlWithoutReverseProxy { .. } => false,
            })
            .collect();

        if !needs_confirm.is_empty() {
            // Show RAM warnings
            for warning in &needs_confirm {
                match warning {
                    Warning::RamBelowMinimum {
                        service_name,
                        min_mb,
                        available_mb,
                    } => {
                        println!(
                            "  {} {service_name} requires at least {min_mb} MB RAM, \
                         but this system has {available_mb} MB — service may fail to start",
                            super::style::warning()
                        );
                    }
                    Warning::RamBelowRecommended {
                        service_name,
                        recommended_mb,
                        available_mb,
                    } => {
                        println!(
                            "  {} {service_name} recommends {recommended_mb} MB RAM, \
                         but this system has {available_mb} MB — performance may be degraded",
                            super::style::note()
                        );
                    }
                    Warning::PortReassigned { .. } | Warning::UrlWithoutReverseProxy { .. } => {}
                }
            }
            println!();

            if interactive && !dry_run {
                let confirmed = Confirm::new()
                    .with_prompt("Continue?")
                    .default(true)
                    .interact()?;
                if !confirmed {
                    println!("Cancelled.");
                    return Ok(());
                }
            }
        }

        if dry_run {
            super::print_dry_run(&result.steps);
            println!("{service} will be started.");
        } else {
            // Record the service as pending before executing steps.
            // If execution fails, ryra knows about the service and can clean up.
            ryra_core::record_pending(ryra_core::RecordPendingParams {
                service_name: service,
                auth_kind,
                registry_name: service_ref.registry_name(),
                allocated_ports: &result.allocated_ports,
                repo_dir: &repo_dir,
                exposure: &exposure,
            })?;

            // Preview what's about to happen — the user sees "pulls / writes /
            // starts" before the steps run. If --url wasn't set, fall back to
            // the primary loopback address so the line always ends with a URL.
            let url_display = result.url.clone().or_else(|| {
                result
                    .allocated_ports
                    .iter()
                    .find(|(name, _)| name.eq_ignore_ascii_case("http"))
                    .or_else(|| result.allocated_ports.first())
                    .map(|(_, p)| format!("http://127.0.0.1:{p}"))
            });
            super::print_plan_header(&result.steps, service, url_display.as_deref());

            if let Err(e) = apply::execute_all(&result.steps).await {
                eprintln!(
                    "\n{} {e}",
                    super::style::error_prefix("Error during setup:")
                );
                eprintln!("Cleaning up partial installation...");
                // Attempt cleanup so the user doesn't have to do it manually.
                // If cleanup fails, fall back to telling the user how to do it.
                match ryra_core::remove_service(service, ryra_core::RemoveMode::Purge) {
                    Ok(remove_result) => {
                        if let Err(cleanup_err) = apply::execute_all(&remove_result.steps).await {
                            eprintln!("Cleanup also failed: {cleanup_err}");
                            eprintln!("Run manually: ryra remove {service}");
                        } else {
                            if let Err(e) = ryra_core::finalize_remove(service) {
                                eprintln!("Warning: finalize_remove failed: {e}");
                            }
                            // Clear lingering `failed` flags on user units so the
                            // next `ryra add` isn't poisoned by stale systemd state.
                            let _ = std::process::Command::new("systemctl")
                                .args(["--user", "reset-failed"])
                                .status();
                            eprintln!("Cleaned up. Retry with: ryra add {service}");
                        }
                    }
                    Err(_) => {
                        eprintln!("Could not clean up automatically.");
                        eprintln!("Run manually: ryra remove {service}");
                    }
                }
                return Err(e);
            }

            // Trust Caddy's self-signed CA, and register the service's
            // hostname in /etc/hosts for browser access. Only fires for
            // *.internal URLs (Caddy local) — Tailscale's MagicDNS handles
            // *.ts.net for free, and External hostnames are the user's
            // DNS to manage.
            if let Some(service_url) = result.url.as_deref()
                && service_url_is_caddy_local(service_url)
            {
                setup_host_access(service, &[service_url]);
            }

            let home_dir = ryra_core::service_home(service)?;
            if let Some(ref url) = result.url {
                println!("\n{service} is running at {url}");
                // Tailnet URLs route via Tailscale Service VIPs, which a
                // host advertising the service can't reach back through —
                // tailscaled doesn't add a route to its own service VIPs.
                // Without this nudge the user opens the URL in their
                // browser on the same machine, gets a hang, and assumes
                // the install is broken. The loopback fallback is HTTP
                // only — services that mandate HTTPS (vaultwarden,
                // authelia) won't accept it, so we flag that too.
                if ryra_core::is_tailscale_url(url) {
                    println!("  Note: tailnet URLs don't loop back to this host. From other");
                    println!("        tailnet devices, the URL above works (HTTPS via Tailscale).");
                    if let Some((_, p)) = result.allocated_ports.first() {
                        println!("        Locally on this host: http://127.0.0.1:{p} (HTTP only —");
                        println!("        services that require HTTPS won't accept it; reinstall");
                        println!(
                            "        without --tailscale for Caddy-local HTTPS at *.internal)."
                        );
                    }
                }
            } else {
                println!("\n{service} is running.");
            }
            println!("  May take a moment to start. Check: systemctl --user status {service}");

            // Connection info — skip localhost URLs when a proper URL is displayed
            if result.url.is_none() && !result.allocated_ports.is_empty() {
                for (_, host_port) in &result.allocated_ports {
                    println!("  URL: http://127.0.0.1:{host_port}");
                }
            }
            if !result.generated_secrets.is_empty() {
                // Show generated secret values so the user can log in
                let env_path = home_dir.join(".env");
                let env_content = match std::fs::read_to_string(&env_path) {
                    Ok(content) => content,
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
                    Err(e) => {
                        eprintln!("  Warning: could not read {}: {e}", env_path.display());
                        String::new()
                    }
                };
                println!("  Secrets (auto-generated):");
                for secret_name in &result.generated_secrets {
                    // Find the env var that used this secret template
                    let matching_env = env_content.lines().find(|l| {
                        l.split_once('=')
                            .map(|(k, _)| k.to_lowercase().contains(secret_name))
                            .unwrap_or(false)
                    });
                    if let Some(line) = matching_env
                        && let Some((key, val)) = line.split_once('=')
                    {
                        println!("    {key}={val}");
                        continue;
                    }
                    println!("    {secret_name} (see .env)");
                }
            }
            println!("  Config:  {}", home_dir.display());

            let env_path = home_dir.join(".env");
            println!();
            println!("Commands:");
            println!("  cat {}  # view config", env_path.display());
            println!("  systemctl --user restart {service}  # restart (picks up .env changes)");
            println!("  journalctl --user-unit {service}.service -f  # follow logs");

            // Caddy-only: tell the user which TLS mode they got and where
            // to switch to a different one. The snippet path is the only
            // thing they need to know to swap in Cloudflare DNS-01,
            // wildcards, BYO certs, plain HTTP for Tunnel, etc.
            if WellKnownService::Caddy.matches(service) {
                let snippet_pathbuf = ryra_core::caddy::tls_snippet_path().ok();
                let snippet_path = snippet_pathbuf
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|| {
                        "~/.local/share/services/caddy/config/tls.caddy".to_string()
                    });
                // Read tls.caddy from disk and report what's actually in
                // effect — not what `--acme` asked for. This matters when a
                // pre-existing snippet was preserved across re-installs
                // (or hand-edited to a custom shape ryra doesn't write).
                // Falls back to the flag value if the read fails or the
                // snippet doesn't match a known ryra-written shape.
                let detected_mode: Option<AcmeMode> = snippet_pathbuf
                    .as_ref()
                    .and_then(|p| std::fs::read_to_string(p).ok())
                    .and_then(|s| AcmeMode::detect_from_snippet(&s));
                println!();
                let displayed_mode: AcmeMode = detected_mode
                    .clone()
                    .or_else(|| acme_for_service.cloned())
                    .unwrap_or(AcmeMode::Internal);
                match &displayed_mode {
                    AcmeMode::WithEmail(email) => {
                        println!("TLS: Let's Encrypt ({email})");
                    }
                    AcmeMode::Anonymous => {
                        println!("TLS: Let's Encrypt (anonymous — no renewal notices)");
                    }
                    AcmeMode::Internal => {
                        println!(
                            "TLS: self-signed (LAN — browsers warn unless ryra's CA is trusted)"
                        );
                    }
                }
                // If the snippet on disk doesn't match a ryra-written
                // shape at all, say so explicitly so the user isn't misled
                // into thinking ryra is managing it.
                if detected_mode.is_none() && acme_for_service.is_none() {
                    println!("  (note: tls.caddy looks user-customized — leaving it untouched)");
                }
                if matches!(displayed_mode, AcmeMode::WithEmail(_) | AcmeMode::Anonymous) {
                    let (http_port, https_port) = result.allocated_ports.iter().fold(
                        (8080u16, 8443u16),
                        |(h, hs), (n, p)| match n.as_str() {
                            "http" => (*p, hs),
                            "https" => (h, *p),
                            _ => (h, hs),
                        },
                    );
                    println!("  For LE to issue certs Caddy must be reachable from the internet:");
                    println!("    - DNS A/AAAA for each --url host must point at this machine");
                    if http_port == 80 && https_port == 443 {
                        println!(
                            "    - Caddy listens on host 80/443; forward router 80→80 and 443→443"
                        );
                        println!("    - Firewall must allow 80/443 (ufw / firewalld / nft varies)");
                    } else {
                        println!(
                            "    - Caddy listens on host {http_port}/{https_port} (rootless); \
                             forward router 80→{http_port} and 443→{https_port}"
                        );
                        println!(
                            "    - Firewall must allow {http_port}/{https_port} \
                             (ufw / firewalld / nft varies)"
                        );
                    }
                    println!("  Cert issuance is async — watch progress with:");
                    println!("    journalctl --user -u caddy -f");
                } else {
                    println!(
                        "  For Let's Encrypt:  ryra remove caddy && ryra add caddy --acme you@example.com"
                    );
                }
                println!("  For Cloudflare DNS-01, wildcards, or BYO certs: edit {snippet_path}");
            }
        }
    } // end for service_input in services

    // Remind the user about lingering — if they reboot or log out without
    // it, every service we just wrote a quadlet for will silently stop.
    // On the very first `ryra add`, offer to enable it inline (the user's
    // paying attention). On later adds, just warn so we're not noisy.
    // Skip in dry-run; a plan shouldn't produce system-state prompts.
    if !dry_run {
        if first_run {
            super::linger::offer_enable().await?;
        } else {
            super::linger::warn_if_disabled().await?;
        }
    }

    Ok(())
}

/// Prompt for a single `prompted`/`required` env var during interactive add.
/// Shared between top-level `[[env]]` and group members so both follow the
/// same default-resolution + override-capture rules.
fn prompt_env(
    env: &ryra_core::registry::service_def::EnvVar,
    default_ctx: &BTreeMap<String, String>,
    env_overrides: &mut BTreeMap<String, String>,
) -> Result<()> {
    use ryra_core::registry::service_def::EnvKind;
    let prompt_text = env.prompt.as_deref().unwrap_or(&env.name);
    if env.kind == EnvKind::Required {
        let value: String = Input::new()
            .with_prompt(format!("    {prompt_text} (required)"))
            .interact_text()?;
        env_overrides.insert(env.name.clone(), value);
    } else {
        let resolved_default = ryra_core::generate::template::render(&env.value, default_ctx)
            .unwrap_or_else(|_| env.value.clone());
        let value: String = Input::new()
            .with_prompt(format!("    {prompt_text}"))
            .default(resolved_default.clone())
            .interact_text()?;
        // Always save for secret-templated values — re-rendering would
        // generate a different random secret.
        if value != resolved_default {
            env_overrides.insert(env.name.clone(), value);
        } else if env.value.contains("{{secret.") {
            env_overrides.insert(env.name.clone(), resolved_default);
        }
    }
    Ok(())
}

/// Pull a single env var's value from the process environment for
/// non-interactive add. `Required` vars go on the `missing` list if absent
/// so the caller can bail with a single consolidated error.
fn collect_non_interactive<'a>(
    env: &'a ryra_core::registry::service_def::EnvVar,
    env_overrides: &mut BTreeMap<String, String>,
    missing: &mut Vec<&'a str>,
) {
    use ryra_core::registry::service_def::EnvKind;
    if let Ok(val) = std::env::var(&env.name) {
        env_overrides.insert(env.name.clone(), val);
    } else if env.kind == EnvKind::Required {
        missing.push(env.name.as_str());
    }
}

/// Register Caddy's CA with every rootless trust store we can reach, and
/// print (but never run) hints for the stores that need sudo — `/etc/hosts`
/// for any hostname the user's resolver can't reach (including
/// `*.internal`, which unlike `*.localhost` does not auto-resolve), and
/// the system trust bundle for curl/wget/Firefox-on-p11-kit users.
///
/// The rootless work covers Chromium-family browsers (via the user's
/// `~/.pki/nssdb`) and every Firefox profile with a `cert9.db`. That's the
/// mkcert pattern and enough for ~95% of browser traffic on Linux.
fn setup_host_access(service: &str, domains: &[&str]) {
    use std::process::Command;

    // --- CA source: whatever Caddy's first start wrote out ---
    let ca_source = ryra_core::service_home("caddy")
        .map(|h| h.parent().map(|p| p.join("caddy-root-ca.crt")))
        .unwrap_or_else(|e| {
            eprintln!("  Warning: could not resolve caddy service home: {e}");
            None
        })
        .filter(|p| p.exists());

    // certutil (from `nss-tools` / `libnss3-tools`) drives every rootless
    // trust step below. If it's missing, skip them all and point the user
    // at the package — otherwise each certutil call would fail with a
    // confusing `No such file or directory` warning.
    let have_certutil = Command::new("certutil").arg("-V").output().is_ok();
    if !have_certutil {
        println!();
        println!("  Note: `certutil` is not installed, so ryra can't register the Caddy CA");
        println!("  with Chromium or Firefox automatically. To enable rootless trust:");
        println!("    Fedora/RHEL:   sudo dnf install nss-tools");
        println!("    Debian/Ubuntu: sudo apt install libnss3-tools");
        println!("    Arch:          sudo pacman -S nss");
        println!("  Then re-run `ryra add caddy` (or click through the browser warning).");
    }

    // --- Rootless: user NSS DB (Chromium, Edge, Brave, Opera, Vivaldi) ---
    if have_certutil && let (Some(nssdb_path), Some(ca)) = (super::nssdb_dir(), ca_source.as_ref())
    {
        if !nssdb_path.exists() {
            if let Err(e) = std::fs::create_dir_all(&nssdb_path) {
                eprintln!("  Warning: could not create {}: {e}", nssdb_path.display());
            } else {
                let init = Command::new("certutil")
                    .args([
                        "-N",
                        "-d",
                        &format!("sql:{}", nssdb_path.display()),
                        "--empty-password",
                    ])
                    .status();
                match init {
                    Ok(s) if s.success() => {}
                    _ => eprintln!(
                        "  Warning: could not initialize NSS DB at {}",
                        nssdb_path.display()
                    ),
                }
            }
        }
        if nssdb_path.exists() {
            add_ca_to_nssdb(
                &format!("sql:{}", nssdb_path.display()),
                ca,
                "Chromium family",
            );
        }
    }

    // --- Rootless: every Firefox profile we can find ---
    if have_certutil && let Some(ca) = ca_source.as_ref() {
        for profile in super::firefox_profile_dirs() {
            add_ca_to_nssdb(
                &format!("sql:{}", profile.display()),
                ca,
                &format!("Firefox profile {}", profile.display()),
            );
        }
    }

    // --- /etc/hosts: write via sudo -n if available, else print hint ---
    //
    // `.internal` doesn't auto-resolve; ryra-managed services need a
    // `127.0.0.1 <host>` entry. We try `sudo -n` (non-interactive) first
    // so CI/test VMs with passwordless sudo get it transparently, and
    // fall back to a printed hint for interactive users whose sudo
    // requires a password.
    let hostnames: Vec<String> = domains
        .iter()
        .filter_map(|d| {
            url::Url::parse(d)
                .ok()
                .and_then(|u| u.host_str().map(String::from))
        })
        // Tailscale MagicDNS already resolves *.ts.net — skip /etc/hosts dance.
        .filter(|h| !h.to_ascii_lowercase().ends_with(".ts.net"))
        .collect();
    let hosts_content = std::fs::read_to_string("/etc/hosts").unwrap_or_default();
    let mut missing_hosts: Vec<&str> = hostnames
        .iter()
        .filter(|h| {
            !hosts_content.lines().any(|l| {
                let l = l.trim();
                !l.starts_with('#') && l.split_whitespace().any(|w| w == h.as_str())
            })
        })
        .map(String::as_str)
        .collect();

    if !missing_hosts.is_empty() {
        // Append a sentinel comment so `ryra remove` can later identify
        // and remove only entries it added — handwritten entries (no
        // marker) are left alone.
        let line = format!(
            "127.0.0.1 {}  # Service-Source: registry/{service}",
            missing_hosts.join(" ")
        );
        // First, try non-interactive sudo — works on CI/test VMs with
        // passwordless sudo and is silent otherwise. If that fails AND
        // stderr is a TTY, escalate to interactive sudo so the user can
        // punch in their password. In headless contexts (stderr not a
        // TTY, e.g. `ryra test --no-vm` capturing output) we skip the
        // interactive prompt and just surface a loud warning below.
        let cmd = format!("echo '{line}' >> /etc/hosts");
        let sudo_n = Command::new("sudo")
            .args(["-n", "sh", "-c", &cmd])
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        let wrote = if sudo_n {
            true
        } else if std::io::stderr().is_terminal() {
            eprintln!(
                "  Adding {} to /etc/hosts (sudo required):",
                missing_hosts.join(", ")
            );
            Command::new("sudo")
                .args(["sh", "-c", &cmd])
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        } else {
            false
        };
        if wrote {
            println!(
                "  Added {} to /etc/hosts (via sudo).",
                missing_hosts.join(", ")
            );
            missing_hosts.clear();
        } else {
            // Emit a loud warning to stderr so it survives stdout capture
            // in test harnesses. Without this entry, the service's URL
            // won't resolve and subsequent health probes will silently
            // spin until they hit the polling limit.
            eprintln!();
            eprintln!(
                "  WARN: {} not in /etc/hosts — the service URL won't resolve.",
                missing_hosts.join(", ")
            );
            eprintln!("        Run:  echo '{line}' | sudo tee -a /etc/hosts");
            eprintln!();
        }
    }

    let ca_target = super::CA_TARGETS.iter().find(|t| {
        let dir = std::path::Path::new(t.cert_path)
            .parent()
            .unwrap_or(std::path::Path::new("/"));
        dir.is_dir()
    });
    let need_system_ca = ca_source.is_some()
        && ca_target.is_some()
        && !super::CA_TARGETS
            .iter()
            .any(|t| std::path::Path::new(t.cert_path).exists());

    if missing_hosts.is_empty() && !need_system_ca {
        return;
    }

    println!();
    println!("  Optional (requires sudo) — run yourself if you need these:");
    if !missing_hosts.is_empty() {
        println!(
            "    echo '127.0.0.1 {}' | sudo tee -a /etc/hosts",
            missing_hosts.join(" ")
        );
    }
    if let (true, Some(ca), Some(target)) = (need_system_ca, ca_source.as_ref(), ca_target) {
        println!(
            "    sudo cp {} {} && sudo {}",
            ca.display(),
            target.cert_path,
            target.update_cmd,
        );
        println!("    (lets curl/wget and Firefox with p11-kit trust the Caddy CA too)");
    }
    println!();
}

/// Try to add the Caddy CA to an NSS DB at `nss_arg` (e.g. `sql:~/.pki/nssdb`
/// or `sql:<firefox-profile-dir>`). No-op if it's already there. The `context`
/// is included in any warning so the user can tell which store failed.
fn add_ca_to_nssdb(nss_arg: &str, ca: &std::path::Path, context: &str) {
    use std::process::Command;
    let present = Command::new("certutil")
        .args(["-d", nss_arg, "-L", "-n", super::CADDY_CA_NICKNAME])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    if present {
        return;
    }
    let status = Command::new("certutil")
        .args([
            "-d",
            nss_arg,
            "-A",
            "-t",
            "C,,",
            "-n",
            super::CADDY_CA_NICKNAME,
            "-i",
            &ca.display().to_string(),
        ])
        .status();
    match status {
        Ok(s) if s.success() => println!("  Caddy CA added to {context}."),
        Ok(s) => eprintln!("  Warning: certutil exited with {s} for {context}"),
        Err(e) => eprintln!("  Warning: could not run certutil for {context}: {e}"),
    }
}

/// Ensure `config.tailscale.admin_api_key` is set, prompting (interactive)
/// or reading from `TAILSCALE_API_KEY` (non-interactive) if not.
///
/// Persists to preferences.toml so the user pastes their token once and every
/// subsequent `--tailscale` install + remove reuses it for service
/// definition + ACL setup via the admin API.
async fn ensure_tailscale_admin_token(interactive: bool) -> Result<()> {
    let paths = ryra_core::config::ConfigPaths::resolve()?;
    let mut config = ryra_core::config::load_or_default(&paths.config_file)?;
    if config.tailscale.is_some() {
        return Ok(()); // already cached
    }

    let admin_api_key = if interactive {
        prompt_tailscale_admin_token()?
    } else {
        std::env::var("TAILSCALE_API_KEY").map_err(|_| {
            anyhow::anyhow!(
                "--tailscale needs a Tailscale admin API token. Set TAILSCALE_API_KEY \
                 (tskey-api-…) or run interactively to be prompted.\n\
                 Generate one at https://login.tailscale.com/admin/settings/keys \
                 (use the \"API access token\" type, not an auth key)"
            )
        })?
    };

    let had_secrets_before = config.has_secrets();
    config.tailscale = Some(ryra_core::config::schema::TailscaleConfig {
        admin_api_key,
        tailnet: None,
    });
    paths.ensure_dirs()?;
    ryra_core::config::save_config(&paths.config_file, &config)?;
    println!(
        "  ✓ Tailscale admin token saved to {}",
        paths.config_file.display()
    );
    warn_if_first_secret_save(&paths, had_secrets_before, &config);
    Ok(())
}

/// Interactive prompt for a Tailscale admin API token.
///
/// Validates the `tskey-api-` prefix so pastes of the wrong thing (e.g.
/// a pre-auth key, an OAuth client secret) get rejected with a clear
/// hint instead of failing later when the API call returns 401.
fn prompt_tailscale_admin_token() -> Result<String> {
    println!();
    println!("First-time Tailscale setup — paste an admin API token.");
    println!("  Generate at: https://login.tailscale.com/admin/settings/keys");
    println!("  Type:        \"API access token\" (NOT an auth key)");
    println!();
    println!("  ryra uses this to define Tailscale Services in your tailnet,");
    println!("  set up the ACL with auto-approval, and apply tag:ryra-host");
    println!("  to this machine — all so `ryra add … --tailscale` is one step.");
    println!();

    let raw: String = Input::new()
        .with_prompt("Tailnet admin API token")
        .validate_with(|input: &String| -> std::result::Result<(), &str> {
            let s = input.trim();
            if s.starts_with("tskey-api-") {
                Ok(())
            } else {
                Err(
                    "Admin API tokens start with `tskey-api-`. The other tskey-* \
                     prefixes (auth-, client-) are for joining devices, not for \
                     admin operations. Generate one at \
                     https://login.tailscale.com/admin/settings/keys with type \
                     \"API access token\".",
                )
            }
        })
        .interact_text()?;
    Ok(raw.trim().to_string())
}

/// Build the `https://<service>-<host>.<tailnet>/` URL for a service
/// installed with `--tailscale`. The svc-name (first DNS label) is
/// scoped by the local node's short hostname so two ryra machines on
/// the same tailnet don't collide on the global Tailscale Service
/// namespace — `ryra add vikunja --tailscale` on machine A produces
/// `vikunja-machineA.<tailnet>.ts.net`, and the same command on
/// machine B produces `vikunja-machineB.<tailnet>.ts.net`. A
/// `ryra reset` on either host only tears down its own scoped svc
/// definition and leaves the other intact. Tailscale already enforces
/// host name uniqueness across a tailnet, so the suffix is unique by
/// construction.
///
/// No port — `tailscale serve --https=443` from the host runs at the
/// standard HTTPS port, and putting `:443` in the URL trips up OIDC
/// libraries that string-compare issuer URLs.
fn derive_tailscale_url(service: &str) -> Result<String> {
    let node = ryra_core::system::tailscale::self_dns_name().ok_or_else(|| {
        anyhow::anyhow!("--tailscale: no logged-in tailnet (preflight should have caught this)")
    })?;
    let host = ryra_core::system::tailscale::self_short_hostname().ok_or_else(|| {
        anyhow::anyhow!(
            "--tailscale: couldn't extract host label from MagicDNS name '{node}' \
             (expected three-label `<host>.<tailnet>.ts.net`)"
        )
    })?;
    let tailnet = ryra_core::system::tailscale::tailnet_suffix(&node).ok_or_else(|| {
        anyhow::anyhow!(
            "--tailscale: couldn't extract tailnet from MagicDNS name '{node}' \
             (expected three-label `<host>.<tailnet>.ts.net`)"
        )
    })?;
    Ok(format!("https://{service}-{host}.{tailnet}"))
}

/// True when a service URL targets Caddy's local-CA `*.internal` domain.
/// Used to gate `/etc/hosts` writes and CA trust setup — Tailscale and
/// External URLs handle DNS / trust through other paths.
fn service_url_is_caddy_local(url: &str) -> bool {
    url::Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(|h| h.to_ascii_lowercase()))
        .is_some_and(|h| {
            h.ends_with(&format!(
                ".{}",
                ryra_core::config::schema::CADDY_LOCAL_DOMAIN
            ))
        })
}

/// Bail when authelia is exposed locally (`*.internal`) but the service we're
/// about to add will be reachable somewhere broader (tailnet, custom URL).
/// In that combination, off-host clients (a phone on the tailnet, a public
/// browser) hit the service fine but can't follow the OIDC redirect to
/// `authelia.internal` because that hostname only resolves on the ryra host.
///
/// The reverse — authelia broader than the service — is fine: the local
/// browser reaches both, and `*.ts.net` resolves on the host via MagicDNS.
fn check_auth_exposure_compat(
    config: &Config,
    service: &str,
    service_url: Option<&str>,
) -> Result<()> {
    let Some(auth) = &config.auth else {
        return Ok(());
    };
    let auth_url = auth.url();
    let auth_is_local = service_url_is_caddy_local(auth_url);
    if !auth_is_local {
        return Ok(());
    }
    let Some(svc_url) = service_url else {
        return Ok(());
    };
    if service_url_is_caddy_local(svc_url) {
        return Ok(());
    }
    bail!(
        "authelia is local-only at {auth_url}, but {service} will be reachable at \
         {svc_url}. Off-host clients (e.g., other devices on your tailnet) can't \
         resolve `*.internal` hostnames, so the OIDC redirect from {service} back \
         to authelia would fail.\n\n\
         Fix: re-install authelia at the same exposure as {service}:\n  \
         ryra remove authelia --purge\n  \
         ryra add authelia --tailscale  (or --url <public-https-url>)"
    );
}

/// Smoke-test DNS for `host` so we can warn before burning a Let's Encrypt
/// validation slot on a hostname that isn't pointed anywhere yet. Only
/// catches the "DNS not configured at all" case — a record pointing at
/// the wrong IP would still fail in Caddy. That's fine: this exists to
/// stop the most common rate-limit pitfall, not validate the full setup.
async fn dns_resolves(host: &str) -> bool {
    tokio::net::lookup_host((host, 0u16))
        .await
        .map(|mut it| it.next().is_some())
        .unwrap_or(false)
}

/// Before we hand a public URL to Caddy in ACME mode, check that DNS
/// resolves for it. If it doesn't, warn loudly about LE rate limits and
/// (if interactive) ask the user to confirm before continuing — failed
/// validations count against ~5/hour limits per registered domain, so
/// looping `ryra add` against a half-configured domain can lock you out
/// of real issuance for hours.
async fn dns_preflight_for_acme(url: &str, interactive: bool) -> Result<()> {
    let Some(host) = url::Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(|s| s.to_string()))
    else {
        return Ok(());
    };
    if dns_resolves(&host).await {
        return Ok(());
    }
    eprintln!("\n  Warning: DNS for '{host}' doesn't resolve.");
    eprintln!("  Caddy will request a Let's Encrypt cert and fail repeatedly until DNS is fixed.");
    eprintln!(
        "  Each failure counts against LE rate limits (~5 failed validations/hour per domain)."
    );
    if !interactive {
        eprintln!("  (Continuing — you're running non-interactively.)");
        return Ok(());
    }
    let proceed = Confirm::new()
        .with_prompt(format!("Continue installing Caddy with LE for '{host}'?"))
        .default(false)
        .interact()?;
    if !proceed {
        bail!("aborted: fix DNS for '{host}' and re-run, or pick a different TLS option");
    }
    Ok(())
}

/// User's choice for how Caddy should issue TLS for a public URL.
/// The `LetsEncrypt` variant carries an [`AcmeMode`] — the LE-specific
/// subset is `Anonymous` or `WithEmail(...)` — so the install-time
/// translation to the snippet is a single match instead of an
/// `if email.is_empty()` branch.
enum TlsHandling {
    /// Caddy auto-issues real certs from Let's Encrypt. Requires DNS
    /// pointing at this host and Caddy reachable from the internet
    /// (ACME challenge).
    LetsEncrypt(AcmeMode),
    /// Caddy issues self-signed certs from its internal CA. Browsers warn
    /// unless the CA is trusted. LAN-friendly default.
    SelfSigned,
    /// Don't install Caddy — the user is fronting with their own reverse
    /// proxy (Cloudflare Tunnel, nginx, external Caddy, etc.).
    External,
}

/// Convert an interactive email input into the right [`AcmeMode`] —
/// empty string (user hit Enter) means anonymous LE, anything else
/// means LE with that email for renewal notices.
fn acme_mode_from_email(email: String) -> AcmeMode {
    if email.is_empty() {
        AcmeMode::Anonymous
    } else {
        AcmeMode::WithEmail(email)
    }
}

/// Prompt the user how TLS should be handled for `url` when Caddy isn't
/// installed. Fires from the per-service add when `--url` points at a
/// public host. Picks the email inline for the LE branch.
async fn prompt_tls_for_public_url(url: &str) -> Result<TlsHandling> {
    let host = url::Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(|s| s.to_string()))
        .unwrap_or_else(|| url.to_string());
    println!();
    println!("'{host}' is a public URL but Caddy (reverse proxy) isn't installed.");
    let items = &[
        "Let's Encrypt — Caddy auto-issues real certs (DNS + Caddy reachable from the internet)",
        "Self-signed (LAN) — Caddy local CA, browsers warn unless trusted",
        "External — I'll handle TLS myself (Cloudflare Tunnel, nginx, etc.)",
    ];
    let selection = dialoguer::Select::new()
        .with_prompt("How should TLS be handled?")
        .items(items)
        .default(0)
        .interact()?;
    match selection {
        0 => {
            let email: String = Input::new()
                .with_prompt(
                    "Email for Let's Encrypt (optional — for renewal notices, press Enter to skip)",
                )
                .allow_empty(true)
                .interact_text()?;
            Ok(TlsHandling::LetsEncrypt(acme_mode_from_email(email)))
        }
        1 => Ok(TlsHandling::SelfSigned),
        _ => Ok(TlsHandling::External),
    }
}

/// Interactive prompt: how should this service be reachable? Returns
/// the typed [`Exposure`] decision after applying any side-effects the
/// choice implies (installing Caddy, running tailscale preflight, etc.).
///
/// Called from the per-service URL resolver in two cases:
///   * `needs_https = true` and neither `--url` nor `--tailscale` was
///     given: `allow_loopback = false`, default = Tailscale (recommended).
///   * `kind = Application` without an HTTPS requirement: surfaces the
///     same exposure choices (so users can put e.g. vikunja on a tailnet)
///     with `allow_loopback = true`, default = Loopback.
async fn prompt_exposure_for(
    service: &str,
    auth_will_inherit: bool,
    allow_loopback: bool,
) -> Result<ryra_core::Exposure> {
    // Keep Loopback as option 0 when allowed so default-Enter preserves
    // the previous "no exposure prompt" behavior. The match arms below
    // adjust their indices via `loopback_offset` to absorb the shift.
    let mut items: Vec<&str> = Vec::with_capacity(5);
    if allow_loopback {
        items.push("Local only — http://127.0.0.1 on this machine (no proxy)");
    }
    items.extend_from_slice(&[
        "Tailscale (recommended): access from anywhere in your own global network",
        "Self-signed (LAN) — Caddy local CA at *.internal (browsers warn unless trusted)",
        "Public + Let's Encrypt — Caddy issues real certs (DNS + Caddy reachable from the internet)",
        "External — I have my own reverse proxy (Cloudflare Tunnel, nginx, etc.)",
    ]);
    if auth_will_inherit {
        println!(
            "(authelia will inherit this choice — install it separately first if you need a different exposure)"
        );
    }
    let selection = dialoguer::Select::new()
        .with_prompt(format!("How will '{service}' be reachable?"))
        .items(&items)
        .default(0)
        .interact()?;

    let loopback_offset: usize = if allow_loopback { 1 } else { 0 };
    if allow_loopback && selection == 0 {
        return Ok(ryra_core::Exposure::Loopback);
    }
    match selection - loopback_offset {
        0 => {
            // Tailscale: same path as `--tailscale` flag — preflight,
            // ensure auth key, derive `https://<service>.<tailnet>/`.
            // Failures bail rather than save partial state.
            if let Err(e) = ryra_core::system::doctor::check_tailscale_runtime() {
                bail!("Tailscale not ready:\n\n{e}");
            }
            ensure_tailscale_admin_token(true).await?;
            Ok(ryra_core::Exposure::Tailscale {
                url: derive_tailscale_url(service)?,
            })
        }
        1 => {
            // Self-signed (LAN): install Caddy in default mode if it isn't
            // already there, then derive the *.internal URL using its
            // allocated HTTPS port. Match the planner's `installed`-aware
            // check — a stale `installed = false` entry from a killed
            // previous install must not count as ready.
            if !ryra_core::is_service_installed("caddy") {
                println!("\nInstalling caddy (self-signed LAN mode)...\n");
                Box::pin(run(
                    &[WellKnownService::Caddy.to_string()],
                    None,
                    false,
                    None,
                    &[],
                    false,
                    None,
                    false,
                    true,
                ))
                .await?;
            }
            let installed_all = ryra_core::list_installed().unwrap_or_default();
            let caddy_https_port =
                find_installed_provider(&installed_all, Capability::ReverseProxy)
                    .and_then(|s| s.ports.get("https").copied())
                    .unwrap_or(DEFAULT_CADDY_HTTPS_PORT);
            Ok(ryra_core::Exposure::Internal {
                url: format!(
                    "https://{service}.{}:{caddy_https_port}",
                    ryra_core::config::schema::CADDY_LOCAL_DOMAIN
                ),
            })
        }
        2 => {
            // Public + Let's Encrypt: ask for the public URL and the LE
            // registration email, install Caddy in ACME mode if it isn't
            // already there, then return the URL. If Caddy is already
            // installed (rare here — this prompt only fires when caddy is
            // missing — but still possible if a prior step installed it),
            // skip re-installing and warn that tls.caddy may need editing.
            let url: String = Input::new()
                .with_prompt(format!("Public URL for '{service}'"))
                .interact_text()?;
            if !ryra_core::is_service_installed("caddy") {
                let email: String = Input::new()
                    .with_prompt("Email for Let's Encrypt (optional — for renewal notices, press Enter to skip)")
                    .allow_empty(true)
                    .interact_text()?;
                dns_preflight_for_acme(&url, true).await?;
                let mode = acme_mode_from_email(email);
                println!("\nInstalling caddy (Let's Encrypt mode)...\n");
                Box::pin(run(
                    &[WellKnownService::Caddy.to_string()],
                    None,
                    false,
                    None,
                    &[],
                    false,
                    Some(&mode),
                    false,
                    true,
                ))
                .await?;
            } else {
                eprintln!(
                    "  Note: caddy is already installed — using its existing TLS mode.\n  \
                     Edit ~/.local/share/services/caddy/config/tls.caddy to switch to Let's Encrypt."
                );
            }
            Ok(ryra_core::Exposure::Public { url })
        }
        _ => {
            // External: user is fronting with their own reverse proxy.
            // Prompt for the URL but don't touch Caddy.
            let url: String = Input::new()
                .with_prompt(format!("Public URL for '{service}'"))
                .interact_text()?;
            Ok(ryra_core::Exposure::Public { url })
        }
    }
}

/// Fire a one-time security note when preferences.toml just acquired its
/// first credential (SMTP, Tailscale token, etc.). Compares pre- and
/// post-save state so the message only prints on the transition, not on
/// every save. Terse on purpose: the file mode is already 0600.
fn warn_if_first_secret_save(
    paths: &ryra_core::config::ConfigPaths,
    had_secrets_before: bool,
    config: &ryra_core::config::schema::Config,
) {
    if !had_secrets_before && config.has_secrets() {
        println!(
            "  Note: credentials saved to {} (mode 0600 / do not commit or share).",
            paths.config_file.display()
        );
    }
}

/// Auto-install inbucket and point `config.smtp` at it for `--smtp=inbucket`.
/// Idempotent: does nothing if `config.smtp` is already set.
async fn ensure_smtp_for_add(provider: SmtpProvider) -> Result<()> {
    let paths = ConfigPaths::resolve()?;
    let mut config = ryra_core::config::load_or_default(&paths.config_file)?;

    if config.smtp.is_some() {
        // Already configured — whether by a previous --smtp, prompt, or a
        // hand-edited preferences.toml. Don't clobber it.
        return Ok(());
    }

    match provider {
        SmtpProvider::Inbucket => {
            if !ryra_core::is_service_installed("inbucket") {
                println!("\nInstalling inbucket...\n");
                Box::pin(run(
                    &[WellKnownService::Inbucket.to_string()],
                    None,
                    false,
                    None,
                    &[],
                    false,
                    None,
                    false,
                    true,
                ))
                .await?;
                // Reload — the inner run() mutated config on disk.
                config = ryra_core::config::load_or_default(&paths.config_file)?;
            }
            // Target inbucket by container name — services on the same
            // podman network resolve it via DNS. `:2500` is inbucket's
            // internal SMTP port; the host-side PublishPort isn't used.
            let had_secrets_before = config.has_secrets();
            config.smtp = Some(ryra_core::config::schema::SmtpCredentials {
                host: "inbucket".to_string(),
                port: INBUCKET_SMTP_PORT,
                username: String::new(),
                password: String::new(),
                from: "noreply@example.com".to_string(),
                security: ryra_core::config::schema::SmtpSecurity::Off,
            });
            paths.ensure_dirs()?;
            ryra_core::config::save_config(&paths.config_file, &config)?;
            println!(
                "  SMTP configured (inbucket). Saved to {}\n",
                paths.config_file.display()
            );
            warn_if_first_secret_save(&paths, had_secrets_before, &config);
        }
    }

    Ok(())
}

/// Auto-install authelia when `--auth` requires it.
///
/// Propagates the parent invocation's `--tailscale` flag so that
/// `ryra add seafile --auth --tailscale` ends up with both seafile *and*
/// authelia exposed on the tailnet — without that propagation, seafile
/// would hit a tailnet hostname and authelia would fall back to Caddy
/// local, which a tailnet device can't resolve.
///
/// Authelia's URL is otherwise resolved by the recursive `run()` call:
/// it goes through the same `--url` / `--tailscale` / Caddy-auto / prompt
/// flow as any service install, so all the URL logic lives in one place.
async fn ensure_dependencies(auth: bool, tailscale: bool, interactive: bool) -> Result<()> {
    let config = ryra_core::config::load_or_default(
        &ryra_core::config::ConfigPaths::resolve()?.config_file,
    )?;
    let needs_authelia =
        auth && !ryra_core::is_service_installed("authelia") && config.auth.is_none();

    if !needs_authelia {
        return Ok(());
    }

    if interactive {
        let confirm = Confirm::new()
            .with_prompt("Authelia (SSO provider) is not installed. Install it?")
            .default(true)
            .interact()?;
        if !confirm {
            bail!("authelia is required for --auth");
        }
    }

    println!("\nInstalling authelia...\n");
    Box::pin(run(
        &[WellKnownService::Authelia.to_string()],
        None,
        false,
        None,
        &[],
        tailscale,
        None,
        false,
        true,
    ))
    .await?;

    Ok(())
}

/// Ensure auth is configured, possibly installing authelia inline.
/// Returns true if auth is ready, false if user cancelled.
async fn ensure_auth_for_add(
    config: &mut Config,
    paths: &ConfigPaths,
    dry_run: bool,
    parent_tailscale: bool,
) -> Result<bool> {
    match prompts::ensure_auth_configured(config, paths).await? {
        prompts::AuthSetupChoice::External(_) => Ok(true),
        prompts::AuthSetupChoice::InstallAuthelia => {
            // Check if authelia is already installed but auth wasn't configured
            if ryra_core::is_service_installed("authelia") {
                println!();
                println!("Authelia is already installed — configuring auth...");
                if try_configure_auth_from_installed(config, paths)? {
                    return Ok(true);
                }
                println!("Could not auto-configure auth from installed authelia.");
                return Ok(false);
            }

            println!("\nInstalling authelia...\n");
            // Inherit the parent service's exposure choice instead of asking
            // the user a second time (which let them pick mismatched setups,
            // e.g. local authelia + tailscale service → tailnet OIDC broken).
            // For Local: caddy is already installed by the parent's prompt,
            // so authelia's recursive URL resolution auto-derives `*.internal`.
            // For Tailscale: pass --tailscale through.
            // For Custom: fall through (custom URLs are per-service — authelia
            // gets its own exposure prompt).
            Box::pin(run(
                &[WellKnownService::Authelia.to_string()],
                None,
                false,
                None,
                &[],
                parent_tailscale,
                None,
                dry_run,
                true,
            ))
            .await?;
            // Reload config — authelia's finalize_add auto-configures [auth]
            *config = ryra_core::config::load_or_default(&paths.config_file)?;
            if config.auth.is_some() {
                println!();
                Ok(true)
            } else {
                println!("Auth was not configured after installing authelia.");
                Ok(false)
            }
        }
        prompts::AuthSetupChoice::Skip => {
            println!("Skipped auth setup.");
            Ok(false)
        }
    }
}

/// Determine which auth kind to use based on CLI flags and service capabilities.
///
/// The prompt's default tracks whether an auth provider is already configured
/// globally: first install → default no (don't push users into auth setup);
/// after Authelia is up → default yes (reuse it by habit).
fn resolve_auth_kind(
    auth_flag: bool,
    interactive: bool,
    supported: &[AuthKind],
    auth_configured: bool,
) -> Result<Option<AuthKind>> {
    // --auth flag: use the first supported auth kind (core validates further)
    if auth_flag {
        return Ok(supported.first().cloned());
    }

    // No auth support in service definition
    if supported.is_empty() || !interactive {
        return Ok(None);
    }

    // Single auth option: simple yes/no prompt
    if supported.len() == 1 {
        let kind = &supported[0];
        let enable = Confirm::new()
            .with_prompt(format!("Enable {kind} auth?"))
            .default(auth_configured)
            .interact()?;
        return Ok(if enable { Some(kind.clone()) } else { None });
    }

    // Multiple options: selection prompt
    let items: Vec<String> = std::iter::once("None".to_string())
        .chain(supported.iter().map(|k| k.to_string()))
        .collect();
    let selection = dialoguer::Select::new()
        .with_prompt("Auth mode")
        .items(&items)
        .default(if auth_configured { 1 } else { 0 })
        .interact()?;
    Ok(if selection == 0 {
        None
    } else {
        Some(supported[selection - 1].clone())
    })
}

/// Warn about services from untrusted (non-bundled) registries.
/// Shows scripts and volume mounts that will run on the host, requires y/n.
fn warn_untrusted_service(
    service_dir: &std::path::Path,
    service: &str,
    interactive: bool,
) -> Result<()> {
    // Collect scripts (ExecStartPre/Post in quadlets)
    let quadlet_dir = service_dir.join("quadlets");
    let mut scripts: Vec<String> = Vec::new();
    let mut volumes: Vec<String> = Vec::new();

    if let Ok(entries) = std::fs::read_dir(&quadlet_dir) {
        for entry in entries.flatten() {
            if let Ok(content) = std::fs::read_to_string(entry.path()) {
                for line in content.lines() {
                    let trimmed = line.trim();
                    if trimmed.starts_with("ExecStartPre=") || trimmed.starts_with("ExecStartPost=")
                    {
                        scripts.push(trimmed.to_string());
                    }
                    if trimmed.starts_with("Volume=") {
                        let vol = trimmed.strip_prefix("Volume=").unwrap_or(trimmed);
                        // Only flag host bind mounts (contain %h or start with /)
                        if vol.contains("%h") || vol.starts_with('/') {
                            volumes.push(vol.to_string());
                        }
                    }
                }
            }
        }
    }

    // Collect config scripts
    let scripts_dir = service_dir.join("configs").join("scripts");
    let mut config_scripts: Vec<String> = Vec::new();
    if let Ok(entries) = std::fs::read_dir(&scripts_dir) {
        for entry in entries.flatten() {
            if let Some(name) = entry.file_name().to_str() {
                config_scripts.push(name.to_string());
            }
        }
    }

    println!();
    println!(
        "  {} {service} is from an external registry.",
        super::style::warning()
    );
    println!("  External services can run arbitrary code on your host.");
    if !scripts.is_empty() {
        println!();
        println!("  Quadlet hooks (run as your user):");
        for s in &scripts {
            println!("    {s}");
        }
    }
    if !config_scripts.is_empty() {
        println!();
        println!("  Scripts (copied to service data dir):");
        for s in &config_scripts {
            println!("    {s}");
        }
    }
    if !volumes.is_empty() {
        println!();
        println!("  Host bind mounts:");
        for v in &volumes {
            println!("    {v}");
        }
    }
    println!();

    if !interactive {
        bail!("{service} is from an external registry — use --yes to accept or run interactively");
    }

    let proceed = Confirm::new()
        .with_prompt("  Install this service?")
        .default(false)
        .interact()?;
    if !proceed {
        bail!("cancelled");
    }

    Ok(())
}

/// Try to configure auth from an already-installed authelia instance.
/// The .env is user-readable under ~/.local/share/services/authelia/.env.
fn try_configure_auth_from_installed(config: &mut Config, paths: &ConfigPaths) -> Result<bool> {
    let env_path = ryra_core::service_home(WellKnownService::Authelia.as_str())?.join(".env");
    let env_content = match std::fs::read_to_string(&env_path) {
        Ok(content) => content,
        Err(_) => return Ok(false),
    };

    // Find the port from the quadlet-derived InstalledService view.
    let installed_all = ryra_core::list_installed().unwrap_or_default();
    let port = find_installed_provider(&installed_all, Capability::OidcProvider)
        .and_then(|s| s.ports.values().next().copied())
        .unwrap_or(DEFAULT_AUTHELIA_PORT);

    // Verify the .env file looks valid (has at least a port reference)
    if env_content.is_empty() {
        return Ok(false);
    }

    let url = format!("http://localhost:{port}");

    config.auth = Some(ryra_core::config::schema::AuthCredentials::Authelia { url, port });
    paths.ensure_dirs()?;
    ryra_core::config::save_config(&paths.config_file, config)?;
    println!(
        "  Auth configured. Saved to {}",
        paths.config_file.display()
    );
    Ok(true)
}

/// Decide whether this `ryra add` invocation must be promoted to HTTPS.
///
/// HTTPS is required when any of these hold:
///   1. The service declares `https = "always"` (e.g. authelia, vaultwarden).
///   2. The service declares `https = "auth"` AND the user chose OIDC auth
///      (via `--auth` or the interactive prompt). This is for services whose
///      OIDC stack refuses plain HTTP even on loopback (e.g. Nextcloud's
///      user_oidc won't render the SSO button over HTTP). Most OIDC-capable
///      services don't need this — RFC 8252 permits HTTP loopback callbacks.
///   3. The user passed an `https://…` URL explicitly.
fn needs_https(
    https_requirement: HttpsRequirement,
    auth_requested: bool,
    url: Option<&str>,
) -> bool {
    matches!(https_requirement, HttpsRequirement::Always)
        || (matches!(https_requirement, HttpsRequirement::Auth) && auth_requested)
        || url.is_some_and(|u| u.starts_with("https://"))
}

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

    #[test]
    fn never_service_stays_http() {
        assert!(!needs_https(HttpsRequirement::Never, false, None));
        // Even with --auth, a service that didn't opt into HTTPS stays HTTP.
        // This is the RFC 8252 loopback case: http://127.0.0.1 is a valid
        // OIDC redirect_uri and most services (forgejo, etc.) work fine
        // that way.
        assert!(!needs_https(HttpsRequirement::Never, true, None));
        // Explicit http:// URL also stays HTTP.
        assert!(!needs_https(
            HttpsRequirement::Never,
            true,
            Some("http://foo.example.com"),
        ));
    }

    #[test]
    fn always_service_always_promotes() {
        assert!(needs_https(HttpsRequirement::Always, false, None));
        assert!(needs_https(
            HttpsRequirement::Always,
            false,
            Some("http://foo.example.com"),
        ));
    }

    #[test]
    fn auth_service_promotes_only_with_auth() {
        // The regression this guards: `ryra add nextcloud --auth` without
        // --url used to quietly install over HTTP and the SSO button never
        // rendered (user_oidc refuses to show it without HTTPS).
        assert!(needs_https(HttpsRequirement::Auth, true, None));
        // Without --auth, even an `https = "auth"` service stays HTTP.
        assert!(!needs_https(HttpsRequirement::Auth, false, None));
    }

    #[test]
    fn explicit_https_url_promotes() {
        assert!(needs_https(
            HttpsRequirement::Never,
            false,
            Some("https://foo.example.com"),
        ));
    }
}