rc_conf 0.14.0

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

use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::os::unix::process::CommandExt;
use std::process::Command;
use std::time::SystemTime;

use biometrics::Counter;
use shvar::{PrefixingVariableProvider, VariableProvider};
use utf8path::Path;

///////////////////////////////////////////// constants ////////////////////////////////////////////

const RESTRICTED_VARIABLES: &[&str] = &["NAME"];

///////////////////////////////////////////// counters /////////////////////////////////////////////

static MISSING_ENABLED_VAR: Counter = Counter::new("rc_conf.service_switch.missing_enabled_var");
static SPLIT_FAILURE: Counter = Counter::new("rc_conf.service_switch.split_failure");
static INVALID_SWITCH_VALUE: Counter = Counter::new("rc_conf.service_switch.invalid_switch_value");
static NO_SERVICES_FOUND: Counter = Counter::new("rc_conf.service_switch.no_services_found");

/// Register all rc_conf counters with the provided collector.
pub fn register_counters(collector: &biometrics::Collector) {
    collector.register_counter(&MISSING_ENABLED_VAR);
    collector.register_counter(&SPLIT_FAILURE);
    collector.register_counter(&INVALID_SWITCH_VALUE);
    collector.register_counter(&NO_SERVICES_FOUND);
}

/////////////////////////////////////////////// Error //////////////////////////////////////////////

/// The Error type.
#[derive(Debug)]
pub enum Error {
    /// The file specified by `path` is too large to parse.
    FileTooLarge {
        /// The path that's too large to parse.
        path: Path<'static>,
    },
    /// The file specified by `path` ends with a r"\" or r"\\n".
    TrailingWhack {
        /// The path with a trailing \.
        path: Path<'static>,
    },
    /// The file specified by `path` contails the prohibited `character` in `string` on `line`.
    ProhibitedCharacter {
        /// The path with a prohibited character.
        path: Path<'static>,
        /// The line with a prohibited character.
        line: u32,
        /// The string with a prohibited characater.
        string: String,
        /// The prohibited character.
        character: char,
    },
    /// The file specified by `path` is invalid in the way specified by `message` on `line`.
    InvalidRcConf {
        /// The invalid rc_conf file.
        path: Path<'static>,
        /// The line that's invalid.
        line: u32,
        /// The reason for it being invalid.
        message: String,
    },
    /// An error for an invalid rc script.
    InvalidRcScript {
        /// The invalid rc.d service stub.
        path: Path<'static>,
        /// The line that's invalid.
        line: u32,
        /// The reason for it being invalid.
        message: String,
    },
    /// The invocation failed.
    InvalidInvocation {
        /// The reason the invocation failed.
        message: String,
    },
    /// Command execution failed.
    ExecFailed {
        /// The command that failed to execute.
        command: String,
        /// The underlying error from exec.
        error: std::io::Error,
    },
    /// An error from the standard library.
    IoError(std::io::Error),
    /// An error parsing variables or splitting strings.
    ShvarError(shvar::Error),
    /// An error relating to utf8.
    Utf8Error(std::str::Utf8Error),
    /// An error relating to utf8.
    FromUtf8Error(std::string::FromUtf8Error),
}

impl Error {
    /// Construct a new "FileTooLarge" variant.
    pub fn file_too_large(file: &Path) -> Self {
        Self::FileTooLarge {
            path: file.clone().into_owned(),
        }
    }

    /// Construct a new "TrailingWhack" variant.
    pub fn trailing_whack(file: &Path) -> Self {
        Self::TrailingWhack {
            path: file.clone().into_owned(),
        }
    }

    /// Construct a new "ProhibitedCharacter" variant.
    pub fn prohibited_character(
        file: &Path,
        line: u32,
        string: impl AsRef<str>,
        character: char,
    ) -> Self {
        Self::ProhibitedCharacter {
            path: file.clone().into_owned(),
            line,
            string: string.as_ref().to_string(),
            character,
        }
    }

    /// Construct a new "InvalidRcConf" variant.
    pub fn invalid_rc_conf(file: &Path, line: u32, message: impl AsRef<str>) -> Self {
        Self::InvalidRcConf {
            path: file.clone().into_owned(),
            line,
            message: message.as_ref().to_string(),
        }
    }

    /// Construct a new "InvalidRcScript" variant.
    pub fn invalid_rc_script(file: &Path, line: u32, message: impl AsRef<str>) -> Self {
        Self::InvalidRcScript {
            path: file.clone().into_owned(),
            line,
            message: message.as_ref().to_string(),
        }
    }

    /// Construct a new "InvalidInvocation" variant.
    pub fn invalid_invocation(message: impl AsRef<str>) -> Self {
        Self::InvalidInvocation {
            message: message.as_ref().to_string(),
        }
    }

    /// Construct a new "ExecFailed" variant.
    pub fn exec_failed(command: impl AsRef<str>, error: std::io::Error) -> Self {
        Self::ExecFailed {
            command: command.as_ref().to_string(),
            error,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Self::IoError(err)
    }
}

impl From<shvar::Error> for Error {
    fn from(err: shvar::Error) -> Self {
        Self::ShvarError(err)
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(err: std::str::Utf8Error) -> Self {
        Self::Utf8Error(err)
    }
}

impl From<std::string::FromUtf8Error> for Error {
    fn from(err: std::string::FromUtf8Error) -> Self {
        Self::FromUtf8Error(err)
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::FileTooLarge { path } => write!(f, "File too large to parse: {}", path.as_str()),
            Error::TrailingWhack { path } => {
                write!(f, "File ends with trailing backslash: {}", path.as_str())
            }
            Error::ProhibitedCharacter {
                path,
                line,
                string,
                character,
            } => {
                write!(
                    f,
                    "Prohibited character '{}' in file {} at line {}: {}",
                    character,
                    path.as_str(),
                    line,
                    string
                )
            }
            Error::InvalidRcConf {
                path,
                line,
                message,
            } => {
                write!(
                    f,
                    "Invalid rc.conf in file {} at line {}: {}",
                    path.as_str(),
                    line,
                    message
                )
            }
            Error::InvalidRcScript {
                path,
                line,
                message,
            } => {
                write!(
                    f,
                    "Invalid rc.d script in file {} at line {}: {}",
                    path.as_str(),
                    line,
                    message
                )
            }
            Error::InvalidInvocation { message } => write!(f, "Invalid invocation: {message}"),
            Error::ExecFailed { command, error } => {
                write!(f, "Command execution failed for '{command}': {error}")
            }
            Error::IoError(err) => write!(f, "IO error: {err}"),
            Error::ShvarError(err) => write!(f, "Shell variable error: {err}"),
            Error::Utf8Error(err) => write!(f, "UTF-8 error: {err}"),
            Error::FromUtf8Error(err) => write!(f, "UTF-8 conversion error: {err}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::IoError(err) => Some(err),
            Error::ShvarError(err) => Some(err),
            Error::Utf8Error(err) => Some(err),
            Error::FromUtf8Error(err) => Some(err),
            _ => None,
        }
    }
}

////////////////////////////////////////// SwitchPosition //////////////////////////////////////////

/// An enum representing the valid values for _ENABLED variables.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SwitchPosition {
    /// The service is disabled.  It cannot be run.  Even manually.
    No,
    /// The service is enabled.  It should be starated automatically.
    Yes,
    /// The service is provisionally enabled.  It will not be run automatically, but can be started
    /// manually or programmatically (e.g. by a cron-like daemon).
    Manual,
}

impl SwitchPosition {
    /// Parse the literal strings "YES", "NO", or "MANUAL" (no lowercasing) into a valid
    /// SwitchPosition enum.
    pub fn from_enable<S: AsRef<str>>(s: S) -> Option<Self> {
        let s = s.as_ref();
        match s {
            "YES" => Some(SwitchPosition::Yes),
            "NO" => Some(SwitchPosition::No),
            "MANUAL" => Some(SwitchPosition::Manual),
            _ => None,
        }
    }

    /// True if the service can run.
    pub fn can_be_started(self) -> bool {
        match self {
            Self::Yes => true,
            Self::Manual => true,
            Self::No => false,
        }
    }
}

///////////////////////////////////////////// RcScript /////////////////////////////////////////////

/// An RcScript implements the rc.d service interface in a declarative way.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RcScript {
    /// The name of the rcscript.
    name: String,
    describe: String,
    command: String,
}

impl RcScript {
    /// Create a new RcScript using the provided name, description, and command.
    ///
    /// # Arguments
    /// * `name` - The service name
    /// * `describe` - Human-readable description of the service
    /// * `command` - Shell command to execute for this service
    ///
    /// # Examples
    /// ```
    /// # use rc_conf::RcScript;
    /// let script = RcScript::new("myservice", "A sample service", "echo hello");
    /// assert_eq!(script.name(), "myservice");
    /// ```
    pub fn new(
        name: impl Into<String>,
        describe: impl Into<String>,
        command: impl Into<String>,
    ) -> Self {
        let name = name.into();
        let describe = describe.into();
        let command = command.into();
        Self {
            name,
            describe,
            command,
        }
    }

    /// Parse the file at path assuming its contents are contents.  It will not re-read path.
    ///
    /// # Arguments
    /// * `path` - Path to the file being parsed (for error reporting)
    /// * `contents` - File contents to parse
    ///
    /// # Returns
    /// Parsed RcScript or an error describing what went wrong
    pub fn parse(path: &Path, contents: &str) -> Result<Self, Error> {
        let name = if let Ok(path) = std::env::var("RCVAR_ARGV0") {
            path.to_string()
        } else {
            name_from_path(path)
        };
        let mut describe = None;
        let mut command = None;
        for (number, line, _) in linearize(path, contents)? {
            if line.trim().starts_with('#') || line.trim().is_empty() {
                continue;
            }
            if let Some((var, val)) = line.split_once('=') {
                match var {
                    "DESCRIBE" if describe.is_none() => {
                        if val.contains('$') {
                            return Err(Error::invalid_rc_script(
                                path,
                                number,
                                "DESCRIBE takes no variables",
                            ));
                        }
                        describe = Some(val.to_string());
                    }
                    "COMMAND" if command.is_none() => {
                        command = Some(val.to_string());
                    }
                    "DESCRIBE" | "COMMAND" => {
                        return Err(Error::invalid_rc_script(
                            path,
                            number,
                            format!("{var} was repeated"),
                        ));
                    }
                    _ => {
                        return Err(Error::invalid_rc_script(
                            path,
                            number,
                            "unsupported command",
                        ));
                    }
                }
            } else {
                return Err(Error::invalid_rc_script(
                    path,
                    number,
                    "missing an '=' sign",
                ));
            }
        }
        match (describe, command) {
            (Some(describe), Some(command)) => {
                let rc = RcScript {
                    name,
                    describe,
                    command,
                };
                rc.rcvar()?;
                Ok(rc)
            }
            (None, _) => Err(Error::invalid_rc_script(
                path,
                1,
                "missing a DESCRIBE declaration",
            )),
            (_, None) => Err(Error::invalid_rc_script(
                path,
                1,
                "missing a COMMAND declaration",
            )),
        }
    }

    /// The name of the rcscript.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Set the name of the rcscript.
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = name.into();
    }

    /// The description of the command provided in the RcScript.
    pub fn describe(&self) -> &str {
        &self.describe
    }

    /// The command to be run, interpreted as a shell-quoted string suitable for splitting.
    pub fn command(&self) -> &str {
        &self.command
    }

    /// Return the set of rc_conf variables to be set for this service stub.
    pub fn rcvar(&self) -> Result<Vec<String>, Error> {
        let name = var_prefix_from_service(&self.name);
        Ok(shvar::rcvar(&self.command)?
            .into_iter()
            .filter(|v| !RESTRICTED_VARIABLES.iter().any(|r| *r == v))
            .map(|v| format!("{name}{v}"))
            .collect())
    }

    /// Invoke the RcScript, providing args to the invocation.  If args is non-empty, it will be
    /// appened with an additional '--' to separate it from the args interpreted from the RcScript
    /// command field.
    pub fn invoke(&self, args: &[impl AsRef<str>]) -> Result<(), Error> {
        if args.is_empty() {
            Err(Error::invalid_invocation("must provide arguments"))
        } else {
            let args = args.iter().map(|s| s.as_ref()).collect::<Vec<_>>();
            match args[0] {
                "run" => self.run(&args[1..]),
                "describe" => {
                    if args.len() != 1 {
                        eprintln!("arguments ignored");
                    }
                    println!("{self:#?}");
                    Ok(())
                }
                "rcvar" => {
                    if args.len() != 1 {
                        eprintln!("arguments ignored");
                    }
                    for rcvar in self.rcvar()?.into_iter() {
                        println!("{rcvar}");
                    }
                    Ok(())
                }
                _ => Err(Error::invalid_invocation(format!(
                    "unknown command {:?}",
                    args[0]
                ))),
            }
        }
    }

    fn run(&self, args: &[&str]) -> Result<(), Error> {
        let name = var_prefix_from_service(&self.name);
        let evp = EnvironmentVariableProvider::new(Some(name));
        let meta = HashMap::from([("NAME".to_string(), self.name.to_string())]);

        for arg in args {
            if arg.contains('\0') {
                return Err(Error::invalid_invocation(
                    "arguments cannot contain null bytes",
                ));
            }
        }

        let exp = shvar::expand_recursive(&(&meta, &evp), &self.command)?;
        let mut cmd = shvar::split(&exp)?;
        if !args.is_empty() {
            cmd.push("--".to_string());
        }
        cmd.extend(args.iter().map(|s| s.to_string()));

        let status = Command::new(&cmd[0])
            .args(&cmd[1..])
            .status()
            .map_err(|err| Error::exec_failed(&cmd[0], err))?;

        if !status.success() {
            return Err(Error::invalid_invocation(format!(
                "command {} failed with exit code {:?}",
                &cmd[0],
                status.code()
            )));
        }

        Ok(())
    }
}

//////////////////////////////////// EnvironmentVariableProvider ///////////////////////////////////

/// A shvar VariableProvider that pulls from the environment (optionally) with a given prefix.  If
/// the prefix exists, it will be preferred.  Note that it is necessary to check both foo_VAR and
/// VAR for prefix foo_ in order to have global values in an rc.conf.  Consider the case of setting
/// all logging options in one parameter that gets expanded to the universally-agreed-upon value.
#[derive(Debug)]
pub struct EnvironmentVariableProvider {
    prefix: Option<String>,
}

impl EnvironmentVariableProvider {
    /// Create a new environmental variable provider that looks values up in the environment,
    /// optionally under some prefix.
    pub const fn new(prefix: Option<String>) -> Self {
        Self { prefix }
    }
}

/// Check if a string is a valid environment variable name.
/// Must start with a letter or underscore, and contain only letters, digits, and underscores.
fn is_valid_env_var_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Check if a source path is safe to include (prevent directory traversal attacks).
fn is_safe_source_path(path: &str) -> bool {
    // Reject empty paths or paths containing null bytes
    if path.is_empty() || path.contains('\0') {
        return false;
    }

    // Reject paths that attempt directory traversal
    if path.contains("..") || path.starts_with('/') {
        return false;
    }

    // Additional safety: reject paths with suspicious characters
    if path.contains('\\') || path.contains('\n') || path.contains('\r') {
        return false;
    }

    true
}

impl shvar::VariableProvider for EnvironmentVariableProvider {
    fn lookup(&self, ident: &str) -> Option<String> {
        // Sanitize environment variable name: must be valid identifier
        if !is_valid_env_var_name(ident) {
            return None;
        }

        let key = if let Some(prefix) = self.prefix.as_ref() {
            prefix.to_string() + ident
        } else {
            ident.to_string()
        };

        // Get environment variable value and sanitize it
        std::env::var(key).ok().and_then(|value| {
            if value.contains('\0') {
                None // Reject values containing null bytes
            } else {
                Some(value)
            }
        })
    }
}

/////////////////////////////////////////////// Alias //////////////////////////////////////////////

#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct Alias {
    // The physical service stub this service aliases.
    aliases: String,
    // True if this alias inherits from what it aliases in rc.conf.
    inherit: bool,
    // Values to inject into the bound values map.
    vp: HashMap<String, String>,
}

////////////////////////////////////////////// RcConf //////////////////////////////////////////////

/// An RcConf is a parsed RcFile.  All IO happens in parse, so behavior should be deterministc
/// after parsing.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct RcConf {
    items: HashMap<String, String>,
    aliases: HashMap<String, Alias>,
    autogens: HashSet<String>,
    values: HashMap<String, RcConf>,
    filters: HashMap<String, RcConf>,
}

impl RcConf {
    /// Parse `path` to get a new RcConf.
    pub fn parse(path: &str) -> Result<Self, Error> {
        let mut seen = HashSet::default();
        let mut items = HashMap::default();
        for piece in path.split(':') {
            let piece = Path::from(piece);
            if !piece.exists() {
                continue;
            }
            Self::parse_recursive(&piece, &mut seen, &mut items)?;
        }
        Self::validate_alias_control_variables(&Path::from(path), &items)?;
        let mut aliases = HashMap::default();
        let mut autogens = HashSet::default();
        for (varname, alias) in items.iter() {
            let Some(name) = varname.strip_suffix("_ALIASES") else {
                continue;
            };
            let inherit = if let Some(flag) = items.lookup(&(name.to_string() + "_INHERIT")) {
                if flag == "NO" {
                    false
                } else if flag == "YES" {
                    true
                } else {
                    return Err(Error::invalid_rc_conf(
                        &Path::from(path),
                        0,
                        format!("invalid _INHERIT binding for {name}"),
                    ));
                }
            } else {
                false
            };
            if items.lookup(&(name.to_string() + "_AUTOGEN")).is_some() {
                autogens.insert(name.to_string());
            }
            aliases.insert(
                name.to_string(),
                Alias {
                    aliases: alias.clone(),
                    inherit,
                    vp: HashMap::new(),
                },
            );
        }
        let mut values = HashMap::new();
        for (varname, values_conf) in items.iter() {
            let Some(name) = varname.strip_prefix("VALUES_") else {
                continue;
            };
            let mut values_items = HashMap::default();
            Self::parse_error_on_source(&Path::from(values_conf.clone()), &mut values_items)?;
            values.insert(
                name.to_string(),
                RcConf {
                    items: values_items,
                    aliases: HashMap::default(),
                    autogens: HashSet::default(),
                    values: HashMap::default(),
                    filters: HashMap::default(),
                },
            );
        }
        let mut filters = HashMap::new();
        for (varname, filters_conf) in items.iter() {
            let Some(name) = varname.strip_prefix("FILTER_") else {
                continue;
            };
            let mut filters_items = HashMap::default();
            Self::parse_error_on_source(&Path::from(filters_conf.clone()), &mut filters_items)?;
            let filters_conf = Path::from(filters_conf.as_str());
            let (sep, vars) = split_for_filter(name);
            let name = vars.join(&sep);
            for varname in filters_items.keys() {
                let pieces = varname.split(&sep).collect::<Vec<_>>();
                if pieces.len() != vars.len() {
                    return Err(Error::invalid_rc_conf(
                        &filters_conf,
                        0,
                        format!("{pieces:?} doesn't match format {name:?}"),
                    ));
                }
                for (value, binding) in std::iter::zip(vars.iter(), pieces.iter()) {
                    let Some(values) = values.get(value) else {
                        return Err(Error::invalid_rc_conf(
                            &filters_conf,
                            0,
                            format!("VALUES_{value} not declared"),
                        ));
                    };
                    if values.lookup(binding).is_none() {
                        return Err(Error::invalid_rc_conf(
                            &filters_conf,
                            0,
                            format!("{binding} not declared as {value}"),
                        ));
                    }
                }
            }
            filters.insert(
                name.to_string(),
                RcConf {
                    items: filters_items,
                    aliases: HashMap::default(),
                    autogens: HashSet::default(),
                    values: HashMap::default(),
                    filters: HashMap::default(),
                },
            );
        }
        for (varname, autogen_switch) in items.iter() {
            let Some(alias) = varname.strip_suffix("_AUTOGEN") else {
                continue;
            };
            if autogen_switch == "NO" {
                continue;
            } else if autogen_switch != "YES" {
                return Err(Error::invalid_rc_conf(
                    &Path::from(path),
                    0,
                    format!("{varname} must be set to YES or NO"),
                ));
            }
            let (template, variables, filter) = strip_prefix_values(&values, alias);
            if variables.is_empty() {
                return Err(Error::invalid_rc_conf(
                    &Path::from(path),
                    0,
                    "autogen requires one or more VALUES_-declared variables",
                ));
            }
            let filter_rc_conf = filters.get(&variables.join("_"));
            let bindings = variables
                .iter()
                .filter_map(|v| values.get(v).map(|rc| rc.variables()))
                .collect::<Vec<_>>();
            if variables.len() != bindings.len() {
                return Err(Error::invalid_rc_conf(
                    &Path::from(path),
                    0,
                    "inconsistent autogen statement (you'll have to pull code to debug this one)",
                ));
            }
            let mut cursors = vec![0; bindings.len()];
            while cursors[0] < bindings[0].len() {
                let candidate = bindings
                    .iter()
                    .enumerate()
                    .map(|(idx, set)| &set[cursors[idx]])
                    .collect::<Vec<_>>();
                let vp = std::iter::zip(variables.iter(), candidate)
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect::<HashMap<_, _>>();
                let candidate = shvar::expand_recursive(&vp, &template)?;
                let filter_key = shvar::expand_recursive(&vp, &filter)?;
                let insert = if let Some(filter_rc_conf) = filter_rc_conf.as_ref() {
                    filter_rc_conf.lookup(&filter_key).is_some()
                } else {
                    true
                };
                if insert {
                    if aliases.contains_key(&candidate) {
                        return Err(Error::invalid_rc_conf(
                            &Path::from(path),
                            0,
                            format!("{candidate} comes from both autogen and alias"),
                        ));
                    }
                    aliases.insert(
                        candidate,
                        Alias {
                            aliases: alias.to_string(),
                            inherit: true,
                            vp,
                        },
                    );
                }
                for idx in (0..bindings.len()).rev() {
                    cursors[idx] = cursors[idx].saturating_add(1);
                    if idx > 0 && cursors[idx] >= bindings[idx].len() {
                        cursors[idx] = 0;
                    } else {
                        break;
                    }
                }
            }
        }
        Self::validate_aliases(&Path::from(path), &aliases)?;
        Ok(Self {
            items,
            aliases,
            autogens,
            values,
            filters,
        })
    }

    fn parse_recursive(
        path: &Path,
        seen: &mut HashSet<Path>,
        items: &mut HashMap<String, String>,
    ) -> Result<(), Error> {
        if seen.contains(path) {
            return Ok(());
        }
        seen.insert(path.clone().into_owned());
        let contents = std::fs::read_to_string(path.as_str())?;
        for (number, line, _) in linearize(path, &contents)? {
            if line.trim().starts_with('#') || line.trim().is_empty() {
                continue;
            }
            if let Some(source) = line.trim().strip_prefix("source ") {
                if is_safe_source_path(source) {
                    Self::parse_recursive(&Path::from(source), seen, items)?;
                } else {
                    return Err(Error::invalid_rc_conf(path, number, "unsafe source path"));
                }
            } else if let Some((var, val)) = line.split_once('=') {
                let split = shvar::split(val)?;
                if split.is_empty() {
                    items.insert(var.to_string(), String::new());
                } else if split.len() == 1 {
                    items.insert(var.to_string(), split[0].clone());
                } else {
                    return Err(Error::invalid_rc_conf(path, number, line));
                }
            } else {
                return Err(Error::invalid_rc_conf(path, number, line));
            }
        }
        Ok(())
    }

    fn validate_alias_control_variables(
        path: &Path,
        items: &HashMap<String, String>,
    ) -> Result<(), Error> {
        let mut variables = items.keys().collect::<Vec<_>>();
        variables.sort();
        for varname in variables {
            let Some(name) = varname.strip_suffix("_INHERIT") else {
                continue;
            };
            let inherit = items
                .get(varname)
                .expect("varname came from items keys and must exist");
            if inherit != "NO" && inherit != "YES" {
                return Err(Error::invalid_rc_conf(
                    path,
                    0,
                    format!("invalid _INHERIT binding for {name}"),
                ));
            }
            let aliases = name.to_string() + "_ALIASES";
            if !items.contains_key(&aliases) {
                return Err(Error::invalid_rc_conf(
                    path,
                    0,
                    format!("{varname} declared without {aliases}"),
                ));
            }
        }
        Ok(())
    }

    fn validate_aliases(path: &Path, aliases: &HashMap<String, Alias>) -> Result<(), Error> {
        let mut alias_names = aliases.keys().collect::<Vec<_>>();
        alias_names.sort();

        let mut prefixes: HashMap<String, &str> = HashMap::default();
        for name in alias_names.iter() {
            if name.is_empty() {
                return Err(Error::invalid_rc_conf(path, 0, "empty alias name"));
            }
            let prefix = var_name_from_service(name);
            match prefixes.entry(prefix.clone()) {
                Entry::Occupied(entry) => {
                    return Err(Error::invalid_rc_conf(
                        path,
                        0,
                        format!(
                            "aliases {} and {} use the same variable prefix {}",
                            entry.get(),
                            name,
                            prefix
                        ),
                    ));
                }
                Entry::Vacant(entry) => {
                    entry.insert(name.as_str());
                }
            }
        }

        for name in alias_names {
            let mut chain = Vec::new();
            let mut positions: HashMap<&str, usize> = HashMap::default();
            let mut current = name.as_str();
            while let Some(alias) = aliases.get(current) {
                if alias.aliases.is_empty() {
                    return Err(Error::invalid_rc_conf(
                        path,
                        0,
                        format!("{current} aliases an empty service name"),
                    ));
                }
                if let Some(position) = positions.get(current) {
                    let mut cycle = chain[*position..].to_vec();
                    cycle.push(current);
                    return Err(Error::invalid_rc_conf(
                        path,
                        0,
                        format!("alias cycle: {}", cycle.join(" -> ")),
                    ));
                }
                positions.insert(current, chain.len());
                chain.push(current);
                current = alias.aliases.as_str();
            }
        }
        Ok(())
    }

    fn parse_error_on_source(
        path: &Path,
        items: &mut HashMap<String, String>,
    ) -> Result<(), Error> {
        let contents = std::fs::read_to_string(path.as_str())?;
        for (number, line, _) in linearize(path, &contents)? {
            if line.trim().starts_with('#') || line.trim().is_empty() {
                continue;
            }
            if let Some((var, val)) = line.split_once('=') {
                let split = shvar::split(val)?;
                if split.is_empty() {
                    items.insert(var.to_string(), String::new());
                } else if split.len() == 1 {
                    items.insert(var.to_string(), split[0].clone());
                } else {
                    return Err(Error::invalid_rc_conf(path, number, line));
                }
            } else {
                return Err(Error::invalid_rc_conf(path, number, line));
            }
        }
        Ok(())
    }

    /// Examine the rc_conf and output the rc_conf as a string, showing how the parser sees it.
    pub fn examine(path: &str) -> Result<String, Error> {
        let mut seen = HashSet::default();
        let mut rc_conf = String::new();
        for (idx, piece) in path.split(':').enumerate() {
            let piece = Path::from(piece);
            if !piece.exists() {
                continue;
            }
            if seen.contains(&piece) {
                rc_conf += &format!(
                    "# rc_conf[{}] = {:?}; already sourced\n",
                    idx,
                    piece.as_str()
                );
                continue;
            }
            rc_conf += &format!("# rc_conf[{}] = {:?}\n", idx, piece.as_str());
            seen.insert(piece.clone().into_owned());
            Self::examine_recursive(&piece, &mut seen, &mut rc_conf)?;
        }
        Ok(rc_conf)
    }

    fn examine_recursive(
        path: &Path,
        seen: &mut HashSet<Path>,
        rc_conf: &mut String,
    ) -> Result<(), Error> {
        seen.insert(path.clone().into_owned());
        let contents = std::fs::read_to_string(path.as_str())?;
        for (number, line, raw) in linearize(path, &contents)? {
            if let Some(source) = line.trim().strip_prefix("source ") {
                if !is_safe_source_path(source) {
                    return Err(Error::invalid_rc_conf(path, number, "unsafe source path"));
                }
                let source = Path::from(source);
                if !seen.contains(&source) {
                    *rc_conf += &format!("# begin source {source:?}\n");
                    seen.insert(path.clone().into_owned());
                    Self::examine_recursive(&source, seen, rc_conf)?;
                    *rc_conf += &format!("# end source {source:?}\n");
                } else {
                    *rc_conf += &format!("# already sourced {source:?}\n");
                }
            } else {
                for line in raw {
                    *rc_conf += &line;
                    rc_conf.push('\n');
                }
            }
        }
        Ok(())
    }

    /// The variables defined within this RcConf.
    pub fn variables(&self) -> Vec<String> {
        self.items.keys().cloned().collect()
    }

    /// Merge the other rc_conf into this one, overwriting values where necessary.
    ///
    /// Note that merge does not perform parameter expansion on the variables, so merging
    /// "${FOO:+${FOO} more foo}" won't do anything except overwrite the value of FOO to be a
    /// self-referential expansion.
    pub fn merge(&mut self, other: Self) {
        for (key, value) in other.items.into_iter() {
            self.items.insert(key, value);
        }
    }

    /// List all services and aliases inferrable from the rc.conf.
    pub fn list(&self) -> Result<impl Iterator<Item = String> + '_, Error> {
        let mut services = vec![];
        let aliases = self.aliases();

        // Collect canonical forms of all aliases for deduplication
        let alias_canonical: std::collections::HashSet<String> = aliases
            .iter()
            .map(|alias| service_from_var_name(&var_name_from_service(alias)))
            .collect();

        for var in self.variables() {
            if let Some(service) = var.strip_suffix("_ENABLED") {
                if self.lookup_suffix_direct(service, "AUTOGEN").is_some() {
                    continue;
                }
                let canonical_service = service_from_var_name(service);
                // Only add if there's no alias that represents the same service
                if !alias_canonical.contains(&canonical_service) {
                    services.push(canonical_service);
                }
            }
        }
        services.extend(aliases);
        services.sort();
        Ok(services.into_iter())
    }

    /// List the services with the ServiceSwitch::Yes flag.  This will return the canonical service
    /// name for each _ENABLED="YES" variable or alias.
    pub fn list_services(&self) -> Result<impl Iterator<Item = String> + '_, Error> {
        Ok(self
            .list()?
            .filter(|s| self.service_switch(s) == SwitchPosition::Yes))
    }

    /// List the tasks with the ServiceSwitch::Manual flag.  This will return the canonical service
    /// name for each _ENABLED="MANUAL" variable or alias.
    pub fn list_tasks(&self) -> Result<impl Iterator<Item = String> + '_, Error> {
        Ok(self
            .list()?
            .filter(|s| self.service_switch(s) == SwitchPosition::Manual))
    }

    /// Create a variable provider that will lookup variables for service.
    /// `service`.
    pub fn variable_provider_for(
        &self,
        service: &str,
    ) -> Result<impl VariableProvider + '_, Error> {
        // NOTE(rescrv):  Don't use lookup_suffix here because we need the full variable provider
        // to be able to expand the suffix.
        let (alias_lookup_order, pre_lookup) = self.alias_lookup_order(service);
        let mut vp = Vec::with_capacity(alias_lookup_order.len());
        for a in alias_lookup_order.iter() {
            vp.push(PrefixingVariableProvider {
                nested: self,
                prefix: var_prefix_from_service(a),
            });
            if !self
                .aliases
                .get(a.to_string().as_str())
                .map(|a| a.inherit)
                .unwrap_or(false)
            {
                break;
            }
        }
        let vp = (pre_lookup, vp, self);
        Ok(vp)
    }

    /// Generate the set of rcvariables that are expected by the script at `path` when invoked as
    /// `service`.
    pub fn bind_for_invoke(
        &self,
        service: &str,
        path: &Path,
    ) -> Result<HashMap<String, String>, Error> {
        let output = Command::new(path.clone().into_std())
            .arg("rcvar")
            .env("RCVAR_ARGV0", var_name_from_service(service))
            .output()?;
        if !output.status.success() {
            return Err(Error::InvalidInvocation {
                message: "rcvar command failed".to_string(),
            });
        }
        let keys = String::from_utf8(output.stdout)?;
        let keys = keys.split_whitespace().collect::<Vec<_>>();
        self.generate_rcvars(service, &keys)
    }

    /// Generate the set of rcvariables that are expected by the script at `path` when invoked as
    /// `service`.
    pub fn bind_for_container(
        &self,
        command: &str,
        container: &str,
        service: &str,
    ) -> Result<HashMap<String, String>, Error> {
        let output = Command::new(command)
            .arg("run")
            .arg("-t")
            .arg("-e")
            .arg(format!("RCVAR_ARGV0={}", var_name_from_service(service)))
            .arg("-e")
            .arg("RCCONF_OVERRIDE_SERVICE_SWITCH=true")
            .arg("--entrypoint")
            .arg("rcvar")
            .arg(container)
            .arg(service)
            .output()?;
        if !output.status.success() {
            return Err(Error::InvalidInvocation {
                message: "rcvar command failed".to_string(),
            });
        }
        let keys = String::from_utf8(output.stdout)?;
        let keys = keys.split_whitespace().collect::<Vec<_>>();
        self.generate_rcvars(service, &keys)
    }

    /// Generate the set of rcvariables from the provided set of keys.
    pub fn generate_rcvars(
        &self,
        service: &str,
        keys: &[&str],
    ) -> Result<HashMap<String, String>, Error> {
        let mut bindings = HashMap::new();
        let vp = self.variable_provider_for(service)?;
        let prefix = var_prefix_from_service(service);
        for var in keys {
            let Some(short) = var.strip_prefix(&prefix) else {
                continue;
            };
            if let Some(value) = vp.lookup(short) {
                let value = shvar::expand_recursive(&vp, &value)?;
                let quoted = shvar::quote(shvar::split(&value)?);
                bindings.insert(var.to_string(), quoted);
            }
        }
        Ok(bindings)
    }

    /// Return a vector of strings suitable for passing to exec.
    pub fn argv(
        &self,
        service: &str,
        variable: &str,
        additional: &impl VariableProvider,
    ) -> Result<Vec<String>, Error> {
        let meta = HashMap::from([("NAME".to_string(), service.to_string())]);
        let vp = self.variable_provider_for(service)?;
        let vp = (additional, &meta, &vp);
        let Some(argv) = self.lookup_suffix(service, variable) else {
            return Ok(vec![]);
        };
        let argv = shvar::expand_recursive(&vp, &argv)?;
        if argv.trim().is_empty() {
            return Ok(vec![]);
        }
        Ok(shvar::split(&argv)?)
    }

    /// Lookup the service switch for `service`.
    pub fn service_switch(&self, service: &str) -> SwitchPosition {
        let (alias_lookup_order, _) = self.alias_lookup_order(service);
        for service in alias_lookup_order {
            let Some(enable) = self.lookup_suffix_direct(service, "ENABLED") else {
                MISSING_ENABLED_VAR.click();
                continue;
            };
            let Ok(split) = shvar::split(&enable) else {
                SPLIT_FAILURE.click();
                return SwitchPosition::No;
            };
            let enable = if split.len() == 1 {
                // SAFETY(rescrv): Length is one, so pop will succeed.
                &split[0]
            } else {
                &enable
            };
            let Some(switch) = SwitchPosition::from_enable(enable) else {
                INVALID_SWITCH_VALUE.click();
                return SwitchPosition::No;
            };
            return switch;
        }
        NO_SERVICES_FOUND.click();
        SwitchPosition::No
    }

    /// Lookup the value of the variable as service_SUFFIX, any alias_SUFFIX, and finally SUFFIX.
    pub fn lookup_suffix(&self, service: &str, suffix: &str) -> Option<String> {
        self.variable_provider_for(service).ok()?.lookup(suffix)
    }

    fn lookup_suffix_direct(&self, service: &str, suffix: &str) -> Option<String> {
        let mut varname = var_prefix_from_service(service);
        varname += suffix;
        self.lookup(&varname)
    }

    /// Return the list of aliases.
    pub fn aliases(&self) -> Vec<String> {
        let mut aliases = self
            .aliases
            .keys()
            .filter(|a| !self.autogens.contains(*a))
            .cloned()
            .collect::<Vec<_>>();
        aliases.sort();
        aliases
    }

    /// Resolve the alias `service` one-hop.
    pub fn direct_alias<'a>(&'a self, service: &'a str) -> &'a str {
        if let Some(alias) = self.aliases.get(service) {
            &alias.aliases
        } else {
            service
        }
    }

    /// Recursively resolve the alias `service`.
    pub fn resolve_alias<'a>(&'a self, service: &'a str) -> &'a str {
        let mut direct_alias = service;
        let mut seen = HashSet::new();
        while let Some(alias) = self.aliases.get(direct_alias) {
            if !seen.insert(direct_alias) {
                break;
            }
            direct_alias = &alias.aliases;
        }
        direct_alias
    }

    /// Generate the alias lookup order for `service` and a cascade of variables.
    pub fn alias_lookup_order<'a>(
        &'a self,
        service: &'a str,
    ) -> (Vec<&'a str>, HashMap<String, String>) {
        let mut alias_lookup_order = vec![service];
        let mut direct_alias = service;
        let mut pre_lookup = HashMap::new();
        let mut seen = HashSet::new();
        while let Some(alias) = self.aliases.get(direct_alias) {
            if !seen.insert(direct_alias) {
                break;
            }
            for (k, v) in alias.vp.iter() {
                if !pre_lookup.contains_key(k) {
                    pre_lookup.insert(k.clone(), v.clone());
                }
            }
            let next = alias.aliases.as_str();
            if seen.contains(next) {
                break;
            }
            alias_lookup_order.push(next);
            direct_alias = next;
        }
        (alias_lookup_order, pre_lookup)
    }
}

impl shvar::VariableProvider for RcConf {
    fn lookup(&self, ident: &str) -> Option<String> {
        self.items.get(ident).cloned()
    }
}

/////////////////////////////////////////////// rc.d ///////////////////////////////////////////////

/// Load the rc.d services from a given rc.d path.
pub fn load_services(
    rc_d_path: &str,
) -> Result<HashMap<String, Result<Path<'static>, String>>, Error> {
    let mut services = HashMap::default();
    for rc_d in rc_d_path.split(':') {
        if !Path::from(rc_d).exists() {
            continue;
        }
        for dirent in std::fs::read_dir(rc_d)? {
            let dirent = dirent?;
            let path = Path::try_from(dirent.path())?.into_owned();
            let name = dirent.file_name().to_string_lossy().to_string();
            match services.entry(name) {
                Entry::Occupied(mut entry) => {
                    let value: &mut Result<Path<'static>, String> = entry.get_mut();
                    if value.is_ok() {
                        *value = Err("duplicate service definition".to_string());
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(Ok(path));
                }
            };
        }
    }
    Ok(services)
}

////////////////////////////////////////////// exec_rc /////////////////////////////////////////////

/// Exec a service using the provided rc_conf_path, rc_d_path, service name, and command arguments.
///
/// This does not return.
pub fn exec_rc(rc_conf_path: &str, rc_d_path: &str, service: &str, cmd: &[&str]) -> ! {
    exec_rc_with_override(rc_conf_path, rc_d_path, false, service, cmd)
}

fn exec_rc_with_override(
    rc_conf_path: &str,
    rc_d_path: &str,
    override_service_switch: bool,
    service: &str,
    cmd: &[&str],
) -> ! {
    let rc_conf = RcConf::parse(rc_conf_path).unwrap_or_else(|e| {
        eprintln!("failed to parse rc_conf: {e}");
        std::process::exit(133);
    });
    let rc_d = load_services(rc_d_path).unwrap_or_else(|e| {
        eprintln!("failed to load services: {e}");
        std::process::exit(134);
    });
    if !override_service_switch && !rc_conf.service_switch(service).can_be_started() {
        eprintln!("service not enabled");
        std::process::exit(132);
    }
    let mut env = HashMap::new();
    let path = if let Some(alias) = rc_conf.aliases.get(service) {
        let Some(path) = rc_d.get(rc_conf.resolve_alias(&alias.aliases)) else {
            eprintln!("expected alias of service to be available via --rc-d-path");
            std::process::exit(130);
        };
        env.insert("RCVAR_ARGV0".to_string(), var_name_from_service(service));
        path
    } else {
        let Some(path) = rc_d.get(service) else {
            eprintln!("expected service to be available via --rc-d-path");
            std::process::exit(130);
        };
        env.insert("RCVAR_ARGV0".to_string(), var_name_from_service(service));
        path
    };
    let path = match path {
        Ok(path) => path,
        Err(err) => {
            eprintln!("service encountered an error: {err:?}");
            std::process::exit(131);
        }
    };
    let mut bound = rc_conf.bind_for_invoke(service, path).unwrap_or_else(|e| {
        eprintln!("failed to bind variables for service: {e}");
        std::process::exit(135);
    });
    bound.extend(env);
    let argv = rc_conf.argv(service, "WRAPPER", &()).unwrap_or_else(|e| {
        eprintln!("failed to generate argv: {e}");
        std::process::exit(136);
    });
    let err = if !argv.is_empty() {
        Command::new(&argv[0])
            .args(&argv[1..])
            .arg(path.as_str())
            .args(cmd)
            .envs(bound)
            .exec()
    } else {
        Command::new(path.as_str()).args(cmd).envs(bound).exec()
    };
    eprintln!("command unexpectedly failed: {err}");
    std::process::exit(137);
}

////////////////////////////////////////// exec_container //////////////////////////////////////////

/// Exec a service using the provided rc_conf_path, rc_d_path, service name, and command arguments.
///
/// This does not return.
pub fn exec_container(
    rc_conf_path: &str,
    _: &str,
    command: &str,
    container: &str,
    service: &str,
    cmd: &[&str],
) -> ! {
    let rc_conf = RcConf::parse(rc_conf_path).unwrap_or_else(|e| {
        eprintln!("failed to parse rc_conf: {e}");
        std::process::exit(133);
    });
    if !rc_conf.service_switch(service).can_be_started() {
        eprintln!("service not enabled");
        std::process::exit(132);
    }
    let mut env = HashMap::new();
    env.insert("RCVAR_ARGV0".to_string(), var_name_from_service(service));
    let mut bound = rc_conf
        .bind_for_container(command, container, service)
        .unwrap_or_else(|e| {
            eprintln!("failed to bind variables for container: {e}");
            std::process::exit(135);
        });
    bound.extend(env);
    let mut argv = vec![command.to_string(), "run".to_string(), "-t".to_string()];
    for (key, value) in bound.iter() {
        argv.push("--env".to_string());
        argv.push(format!("{key}={value}"));
    }
    argv.push("--env".to_string());
    argv.push("RCCONF_OVERRIDE_SERVICE_SWITCH=true".to_string());
    argv.push(container.to_string());
    argv.extend(rc_conf.argv(service, "WRAPPER", &()).unwrap_or_else(|e| {
        eprintln!("failed to generate argv: {e}");
        std::process::exit(136);
    }));
    let err = Command::new(&argv[0])
        .args(&argv[1..])
        .arg(service)
        .args(cmd)
        .envs(bound)
        .exec();
    eprintln!("command unexpectedly failed: {err}");
    std::process::exit(137);
}

///////////////////////////////////////////// rcinvoke /////////////////////////////////////////////

/// exec_rc the service in a way that runs it.
pub fn invoke(rc_conf_path: &str, rc_d_path: &str, service: &str, args: &[&str]) -> ! {
    let mut cmd = vec!["run"];
    cmd.extend(args);
    let override_service_switch = std::env::var("RCCONF_OVERRIDE_SERVICE_SWITCH").is_ok();
    exec_rc_with_override(
        rc_conf_path,
        rc_d_path,
        override_service_switch,
        service,
        &cmd,
    )
}

/////////////////////////////////////////////// rcvar //////////////////////////////////////////////

/// exec_rc the service in a way that prints rcvariables.
pub fn rcvar(rc_conf_path: &str, rc_d_path: &str, service: &str) -> ! {
    let override_service_switch = std::env::var("RCCONF_OVERRIDE_SERVICE_SWITCH").is_ok();
    exec_rc_with_override(
        rc_conf_path,
        rc_d_path,
        override_service_switch,
        service,
        &["rcvar"],
    )
}

///////////////////////////////////////////// bootstrap ////////////////////////////////////////////

fn vendor(path: utf8path::Path, crate_name: &str, spec: &str) -> Result<(), Error> {
    let tmp = std::env::temp_dir().join(format!(
        "{}_{}_{}",
        crate_name,
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .expect("Time should not go before UNIX epoch")
            .as_millis(),
        std::process::id()
    ));
    std::fs::create_dir(&tmp)?;
    std::fs::create_dir(tmp.join("src"))?;
    std::fs::write(tmp.join("src/lib.rs"), [])?;
    let tmp = tmp.join("Cargo.toml");
    std::fs::write(
        &tmp,
        format!(
            r#"
[package]
name = "rc-conf-dummy"
version = "0.1.0"
edition = "2021"

[dependencies]
{crate_name} = {spec}
"#
        ),
    )?;
    std::process::Command::new("cargo")
        .arg("vendor")
        .arg("--no-delete")
        .arg("--manifest-path")
        .arg(tmp)
        .arg(path.as_str())
        .output()?;
    Ok(())
}

/// Prepare the output directory for running the provided rc_conf_path.  Return the minimal
/// rc_d_path that will allow it to run.
pub fn bootstrap<'a>(
    rc_conf_path: &str,
    output: impl Into<utf8path::Path<'a>>,
) -> Result<String, Error> {
    let output = output.into();
    let rc_conf = RcConf::parse(rc_conf_path)?;
    let mut rc_d_path = String::new();
    for variable in rc_conf.variables() {
        if let Some(crate_name) = variable.strip_suffix("_SPEC") {
            if !rc_d_path.is_empty() {
                rc_d_path.push(':');
            }
            // SAFETY(rescrv):  We got the value from variables above and it's a hash map.  It's
            // still in there, so lookup should succeed.
            vendor(
                output.clone(),
                crate_name,
                &rc_conf.lookup(&variable).unwrap(),
            )?;
            rc_d_path.push_str(output.join(crate_name).join("rc.d").as_str());
        }
    }
    Ok(rc_d_path)
}

///////////////////////////////////////////// utilities ////////////////////////////////////////////

/// Turn the contents of a file into numbered lines, while respecting line continuation markers.
///
/// This function processes configuration file contents and handles line continuation
/// using backslash (`\`) characters at the end of lines.
///
/// # Arguments
/// * `path` - File path for error reporting
/// * `contents` - Raw file contents to process
///
/// # Returns
/// A vector of tuples containing:
/// * Line number (1-based)
/// * Processed line content with continuations resolved
/// * Raw lines that contributed to this logical line
///
/// # Errors
/// Returns an error if:
/// * File is too large (more than u32::MAX lines)
/// * Invalid backslash usage (not at end of line, or multiple backslashes)
/// * File ends with a trailing backslash
pub fn linearize(path: &Path, contents: &str) -> Result<Vec<(u32, String, Vec<String>)>, Error> {
    let mut start = 1;
    let mut acc = String::new();
    let mut raw = vec![];
    let mut lines = vec![];
    for (number, line) in contents.split_terminator('\n').enumerate() {
        if number as u64 >= u32::MAX as u64 {
            return Err(Error::file_too_large(path));
        }
        let has_whack = line.contains('\\');
        let end_whack = line.ends_with('\\');
        if has_whack && line.chars().filter(|c| *c == '\\').count() > 1 {
            return Err(Error::prohibited_character(
                path,
                number as u32 + 1,
                line,
                '\\',
            ));
        }
        if has_whack && !end_whack {
            return Err(Error::prohibited_character(
                path,
                number as u32 + 1,
                line,
                '\\',
            ));
        }
        if !acc.is_empty() {
            acc.push(' ');
        }
        if !end_whack {
            acc += line.trim();
            raw.push(line.to_string());
            let line = std::mem::take(&mut acc);
            let raw = std::mem::take(&mut raw);
            lines.push((start, line, raw));
            start = number as u32 + 1;
        } else {
            acc += line[..line.len() - 1].trim();
            raw.push(line.to_string());
        }
    }
    if !acc.is_empty() {
        return Err(Error::trailing_whack(path));
    }
    Ok(lines)
}

/// Return the service name from the given path.
pub fn name_from_path(path: &Path) -> String {
    path.basename().as_str().to_string()
}

/// Return the var name for a service.  Converts non-alphanumerics to underscores.
pub fn var_name_from_service(service: &str) -> String {
    service
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '_' })
        .collect()
}

/// Return _a_ canonical service name from a variable name.
pub fn service_from_var_name(var_name: &str) -> String {
    var_name
        .chars()
        .flat_map(|c| {
            if c.is_alphanumeric() {
                c.to_lowercase()
            } else {
                '-'.to_lowercase()
            }
        })
        .collect()
}

/// Return the variable prefix for a service or alias.
pub fn var_prefix_from_service(service: &str) -> String {
    var_name_from_service(service) + "_"
}

////////////////////////////////////////////// filters /////////////////////////////////////////////

fn split_for_filter(var: &str) -> (String, Vec<String>) {
    if var.contains("__") {
        (
            "__".to_string(),
            var.split("__").map(String::from).collect(),
        )
    } else {
        ("_".to_string(), var.split('_').map(String::from).collect())
    }
}

fn strip_prefix_values(
    values: &HashMap<String, RcConf>,
    template: &str,
) -> (String, Vec<String>, String) {
    let mut still_pulling_values = true;
    let mut vars = vec![];
    let mut built = vec![];
    let mut filter = vec![];
    let pieces = template.split('_').collect::<Vec<_>>();
    for piece in pieces.iter() {
        let contains = values.contains_key(&piece.to_string());
        if !piece.is_empty() {
            if contains && still_pulling_values {
                vars.push(piece.to_string());
                let var = format!("${{{piece}}}");
                built.push(var.clone());
                filter.push(var);
            } else if !contains || !still_pulling_values {
                still_pulling_values = false;
                built.push(piece.to_string());
            }
        } else {
            built.push(piece.to_string());
        }
    }
    (built.join("_"), vars, filter.join("_"))
}

/////////////////////////////////////////////// tests //////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::sync::atomic::{AtomicU64, Ordering};

    static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn write_rc_conf(contents: &str) -> String {
        let id = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
        let path =
            std::env::temp_dir().join(format!("rc_conf_test_{}_{}.conf", std::process::id(), id));
        std::fs::write(&path, contents).expect("temp rc.conf should be writable");
        path.into_os_string()
            .into_string()
            .expect("temp path should be UTF-8")
    }

    fn parse_rc_conf(contents: &str) -> Result<super::RcConf, super::Error> {
        let path = write_rc_conf(contents);
        let result = super::RcConf::parse(&path);
        let _ = std::fs::remove_file(path);
        result
    }

    fn examine_rc_conf(contents: &str) -> Result<String, super::Error> {
        let path = write_rc_conf(contents);
        let result = super::RcConf::examine(&path);
        let _ = std::fs::remove_file(path);
        result
    }

    fn invalid_rc_conf_message(contents: &str) -> String {
        match parse_rc_conf(contents) {
            Err(super::Error::InvalidRcConf { message, .. }) => message,
            Err(err) => panic!("expected InvalidRcConf; got {err:?}"),
            Ok(_) => panic!("expected InvalidRcConf; got Ok"),
        }
    }

    mod rc_script {
        use super::super::*;

        #[test]
        fn new() {
            RcScript::new("name", "describe", "command");
        }

        #[test]
        fn from() {
            let rc_script = RcScript::parse(
                &Path::from("name"),
                r#"
DESCRIBE=my description
COMMAND=my-command --option
"#,
            )
            .unwrap();
            assert_eq!(
                RcScript::new("name", "my description", "my-command --option"),
                rc_script
            );
        }

        #[test]
        fn quoted() {
            let rc_script = RcScript::parse(
                &Path::from("name"),
                r#"
DESCRIBE=my description
COMMAND="my-command" "--option"
"#,
            )
            .unwrap();
            assert_eq!(
                RcScript::new("name", "my description", "\"my-command\" \"--option\""),
                rc_script
            );
        }

        #[test]
        fn with_newline() {
            let rc_script = RcScript::parse(
                &Path::from("name"),
                r#"
DESCRIBE=my description
COMMAND=my-command \
    --option
"#,
            )
            .unwrap();
            assert_eq!(
                RcScript::new("name", "my description", "my-command --option"),
                rc_script
            );
        }

        #[test]
        fn rcvar() {
            let rc_script = RcScript::parse(
                &Path::from("name"),
                r#"
DESCRIBE=my description
COMMAND=my-command \
    --option ${MY_VARIABLE}
"#,
            )
            .unwrap();
            assert_eq!(
                vec!["name_MY_VARIABLE".to_string()],
                rc_script.rcvar().unwrap()
            );
        }

        #[test]
        fn rcvar_omits_restricted_name() {
            let rc_script = RcScript::parse(
                &Path::from("name"),
                r#"
DESCRIBE=my description
COMMAND=my-command ${NAME} ${FIELD}
"#,
            )
            .unwrap();
            assert_eq!(vec!["name_FIELD".to_string()], rc_script.rcvar().unwrap());
        }
    }

    mod rcexamine {
        use super::super::RcConf;

        #[test]
        fn examine() {
            let examined =
                RcConf::examine("bar.conf:foo.conf").expect("examine should always succeed");
            assert_eq!(
                r#"
# rc_conf[0] = "bar.conf"
# begin source "foo.conf"
foo_ENABLE=YES
# end source "foo.conf"

bar_ENABLE=YES

# already sourced "foo.conf"
# rc_conf[1] = "foo.conf"; already sourced
            "#
                .trim(),
                examined.trim()
            );
        }
    }

    mod rclist {
        use std::collections::HashMap;

        use utf8path::Path;

        #[test]
        fn list_rc_d_once() {
            let services =
                super::super::load_services("rc.d").expect("load_services should always succeed");
            assert_eq!(
                HashMap::from([
                    ("example1".to_string(), Ok(Path::from("rc.d/example1"))),
                    ("example2".to_string(), Ok(Path::from("rc.d/example2"))),
                    ("runbook1".to_string(), Ok(Path::from("rc.d/runbook1"))),
                ]),
                services
            );
        }

        #[test]
        fn list_rc_d_twice() {
            let services = super::super::load_services("rc.d:rc.d")
                .expect("load_services should always succeed");
            assert_eq!(
                HashMap::from([
                    (
                        "example1".to_string(),
                        Err("duplicate service definition".to_string())
                    ),
                    (
                        "example2".to_string(),
                        Err("duplicate service definition".to_string())
                    ),
                    (
                        "runbook1".to_string(),
                        Err("duplicate service definition".to_string())
                    ),
                ]),
                services
            );
        }
    }

    #[test]
    fn strip_prefix_values() {
        let values = HashMap::from([
            ("FOO".to_string(), super::RcConf::default()),
            ("BAR".to_string(), super::RcConf::default()),
        ]);
        assert_eq!(
            (
                "${FOO}_${BAR}_service".to_string(),
                vec!["FOO".to_string(), "BAR".to_string()],
                "${FOO}_${BAR}".to_string(),
            ),
            super::strip_prefix_values(&values, "FOO_BAR_service")
        );
    }

    #[test]
    fn error_handling_invalid_switch() {
        let mut rc_conf = super::RcConf::default();
        rc_conf
            .items
            .insert("test_ENABLED".to_string(), "INVALID".to_string());
        assert_eq!(rc_conf.service_switch("test"), super::SwitchPosition::No);
    }

    #[test]
    fn error_handling_split_failure() {
        let mut rc_conf = super::RcConf::default();
        // Insert a value that would cause shvar::split to fail
        rc_conf
            .items
            .insert("test_ENABLED".to_string(), "\"unclosed".to_string());
        assert_eq!(rc_conf.service_switch("test"), super::SwitchPosition::No);
    }

    #[test]
    fn switch_position_from_enable() {
        assert_eq!(
            super::SwitchPosition::from_enable("YES"),
            Some(super::SwitchPosition::Yes)
        );
        assert_eq!(
            super::SwitchPosition::from_enable("NO"),
            Some(super::SwitchPosition::No)
        );
        assert_eq!(
            super::SwitchPosition::from_enable("MANUAL"),
            Some(super::SwitchPosition::Manual)
        );
        assert_eq!(super::SwitchPosition::from_enable("invalid"), None);
    }

    #[test]
    fn switch_position_can_be_started() {
        assert!(super::SwitchPosition::Yes.can_be_started());
        assert!(super::SwitchPosition::Manual.can_be_started());
        assert!(!super::SwitchPosition::No.can_be_started());
    }

    #[test]
    fn alias_cycle_is_invalid() {
        let message = invalid_rc_conf_message(
            r#"
alpha_ALIASES="beta"
alpha_INHERIT="YES"
beta_ALIASES="alpha"
beta_INHERIT="YES"
"#,
        );
        assert_eq!("alias cycle: alpha -> beta -> alpha", message);
    }

    #[test]
    fn alias_self_cycle_is_invalid() {
        let message = invalid_rc_conf_message(
            r#"
alpha_ALIASES="alpha"
alpha_INHERIT="YES"
"#,
        );
        assert_eq!("alias cycle: alpha -> alpha", message);
    }

    #[test]
    fn alias_variable_prefix_collision_is_invalid() {
        let message = invalid_rc_conf_message(
            r#"
edit-auto_ALIASES="edit"
edit-auto_INHERIT="YES"
edit_auto_ALIASES="edit"
edit_auto_INHERIT="YES"
"#,
        );
        assert_eq!(
            "aliases edit-auto and edit_auto use the same variable prefix edit_auto",
            message
        );
    }

    #[test]
    fn orphan_inherit_target_is_invalid() {
        let message = invalid_rc_conf_message(
            r#"
edit_auto_INHERIT="edit"
"#,
        );
        assert_eq!("invalid _INHERIT binding for edit_auto", message);
    }

    #[test]
    fn orphan_inherit_flag_is_invalid() {
        let message = invalid_rc_conf_message(
            r#"
edit_auto_INHERIT="YES"
"#,
        );
        assert_eq!(
            "edit_auto_INHERIT declared without edit_auto_ALIASES",
            message
        );
    }

    #[test]
    fn examine_rejects_unsafe_source_path() {
        let result = examine_rc_conf("source ../unsafe.conf\n");
        match result {
            Err(super::Error::InvalidRcConf { message, .. }) => {
                assert_eq!("unsafe source path", message);
            }
            Err(err) => panic!("expected InvalidRcConf; got {err:?}"),
            Ok(examined) => panic!("expected InvalidRcConf; got {examined:?}"),
        }
    }

    #[test]
    fn duplication_issue_test() {
        // Create a test rc_conf with the same pattern as the real one
        let mut items = HashMap::new();

        // Add autogen setup
        items.insert(
            "METRO_CUSTOMER_example4_AUTOGEN".to_string(),
            "YES".to_string(),
        );
        items.insert(
            "METRO_CUSTOMER_example4_ENABLED".to_string(),
            "YES".to_string(),
        );
        items.insert(
            "METRO_CUSTOMER_example4_ALIASES".to_string(),
            "example4".to_string(),
        );
        items.insert(
            "METRO_CUSTOMER_example4_INHERIT".to_string(),
            "YES".to_string(),
        );
        items.insert("VALUES_METRO".to_string(), "metros.conf".to_string());
        items.insert("VALUES_CUSTOMER".to_string(), "customers.conf".to_string());

        // Add manual enabled for the same service
        items.insert(
            "Jfk_PlanetExpress_example4_ENABLED".to_string(),
            "YES".to_string(),
        );
        items.insert(
            "Jfk_PlanetExpress_example4_FIELD1".to_string(),
            "Good News".to_string(),
        );

        // Create a mock rc_conf - this won't work directly but shows the concept
        let rc_conf = super::RcConf::parse("rc.conf").unwrap();
        let services: Vec<_> = rc_conf.list().unwrap().collect();

        // Check for duplicates
        let jfk_planet_services: Vec<_> = services
            .iter()
            .filter(|s| s.to_lowercase().contains("jfk") && s.to_lowercase().contains("planet"))
            .collect();

        println!("JFK Planet services found: {jfk_planet_services:?}");

        // Should only appear once, either as autogen or manual, not both
        assert!(
            jfk_planet_services.len() <= 1,
            "jfk-planetexpress-example4 should appear at most once, found: {jfk_planet_services:?}"
        );
    }

    #[test]
    fn fragmented_services() {
        let rc_conf = super::RcConf::parse("rc.conf").unwrap();
        assert_eq!(
            vec![
                "Jfk_PlanetExpress_example4",
                "Jfk_TyrellCorp_example4",
                "Sac_Acme_example4",
                "Sfo_ApertureScience_example4",
                "Sjc_CyberDyne_example4",
                "example3",
            ],
            rc_conf.aliases(),
        );
        assert_eq!(
            vec![
                "Jfk_PlanetExpress_example4",
                "Jfk_TyrellCorp_example4",
                "Sac_Acme_example4",
                "Sfo_ApertureScience_example4",
                "Sjc_CyberDyne_example4",
                "example1",
                "example2",
                "example3",
                "rcdemo",
                "runbook1",
            ],
            rc_conf.list().unwrap().collect::<Vec<_>>()
        );
    }
}