ferroday-cage-cli 0.4.1

Run a command inside an unprivileged Linux sandbox from a shell prompt: fresh namespaces, a root filesystem you supply or bootstrap from Debian, Alpine, or Gentoo, seccomp and Landlock hardening, and a clean environment. Installs the fcage binary
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
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
//! The ferroday-cage command-line interface.
//!
//! `fcage` runs a command inside an unprivileged Linux sandbox built by the
//! ferroday-cage library: fresh namespaces, the given root filesystem
//! presented at `/` with the default mount profile assembled over it, and
//! the calling user mapped to root inside. Almost every flag maps onto a call
//! on the library's builder, and `--profile` loads a TOML sandbox
//! specification through the library's `serde` feature; the binary contains
//! no sandboxing logic of its own. `--restrict` selects the library's
//! restriction fallback instead: Landlock and seccomp confinement of a
//! plain process, for hosts without unprivileged user namespaces.
//!
//! Not every flag configures a launch. The `--provision-*` family publishes a
//! rootfs before the command runs, and given without a command provisions and
//! exits. `--remove-rootfs` deletes a provisioned rootfs and `--export-rootfs`
//! writes one to a tar archive, each a mode of its own that accepts no other
//! option. All three carry the library's `provision` calls to a shell prompt,
//! which is the whole lifecycle of a rootfs: make it, ship it, delete it.
//!
//! The binary is built with every library feature enabled, so any profile the
//! library accepts loads here, and every capability of the launch builder --
//! `CageBuilder`, and the `RestrictionBuilder` behind `--restrict` -- has a
//! flag. Two library seams have no command-line form, because neither is
//! expressible as an argument: `Stdio::Fd`, which hands the command an open
//! descriptor, and `CageBuilder::id_mapper`, which supplies an identity-map
//! delegate as code. `--stdin` therefore offers the two dispositions a profile
//! can name, and `--identity-map` the delegates the library bundles. The output
//! pair has no flag at all: a shell already spells both of its dispositions,
//! and a profile carries `stdout` and `stderr` where they belong.
//!
//! The same holds for the native network stack: every `NetStackBuilder` setting
//! has a `--netstack-*` flag. The provisioners are narrower, and deliberately:
//! each one's bootstrap surface has flags, including the plan and pin documents
//! that make an install reproducible, but a *layered* build has none. A
//! provisioner given a base layer produces an increment in a disposable overlay
//! upper rather than a published rootfs, which is a mode `fcage` does not have;
//! and only Gentoo has read-only inspection modes, because only its archive
//! publishes the enumerations they print. `tools/parity.toml` records the whole
//! comparison, setting by setting, and a check holds it to the code.

mod terminal;

use std::ffi::{OsStr, OsString};
use std::net::{Ipv4Addr, Ipv6Addr};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

use ferroday_cage::provision::alpine::KeySet as AlpineKeySet;
use ferroday_cage::provision::debian::{Priority, Repository};
use ferroday_cage::relay::{Escalation, RelayError, Signals};
use ferroday_cage::{
    Bind, Cage, CageBuilder, Capability, Error, ExitStatus, FsAccess, IdRange, Identity,
    IdentityMap, Limit, Mount, NetAccess, NetStack, Network, Overlay, RawMount, Resource,
    RestrictedProfile, Restriction, Running, SeccompArg, SeccompArgLen, SeccompCompare,
    SeccompPolicy, SeccompRules, Stdio,
};
use serde::Deserialize as _;

/// What follows a flag's name on the command line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Arity {
    /// Nothing: the flag is the whole argument.
    Bare,
    /// One value, written `--flag VALUE` or `--flag=VALUE`.
    One,
    /// Two, written `--flag FIRST SECOND`. Only the mount and environment
    /// flags take a pair, and none of them has a joined form: `--bind=A B`
    /// would put one of the two on the wrong side of the `=`.
    Two,
}

/// The invocation a flag belongs to.
///
/// `fcage` is several programs behind one name, and each mode's parser accepts
/// only its own flags. What the modes share is where the command begins, which
/// is why every flag is here whether a launch takes it or not: the pre-scan
/// that routes an invocation has to walk past a flag's value to find the first
/// positional argument, and it can only do that if it knows what each flag
/// takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    /// The ordinary invocation: build a sandbox and run a command in it.
    Launch,
    /// `--remove-rootfs`.
    Remove,
    /// `--export-rootfs`.
    Export,
    /// `--gentoo-variants`.
    GentooVariants,
    /// `--gentoo-packages`.
    GentooPackages,
    /// `--gentoo-installed`.
    GentooInstalled,
    /// `--gentoo-keyring-horizon`.
    GentooKeyring,
    /// `--help`.
    Help,
    /// `--version`.
    Version,
}

/// Where `--help` lists a flag.
///
/// The order here is the order the sections are printed in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Section {
    Provisioning,
    Profiles,
    Identity,
    Command,
    Networking,
    Hardening,
    Off,
    Help,
    /// Named in the closing prose rather than listed: the counterpart toggles,
    /// each of which overrides a profile in the direction its named partner
    /// does not.
    Counterpart,
}

impl Section {
    /// Every section, in the order `--help` prints them.
    const ALL: &'static [Section] = &[
        Section::Provisioning,
        Section::Profiles,
        Section::Identity,
        Section::Command,
        Section::Networking,
        Section::Hardening,
        Section::Off,
        Section::Help,
        Section::Counterpart,
    ];

    /// The heading `--help` prints above it, or `None` for the flags the
    /// closing prose names instead of listing.
    const fn heading(self) -> Option<&'static str> {
        match self {
            Section::Provisioning => Some("Provisioning the root filesystem"),
            Section::Profiles => Some("Profiles, overlays, and mounts"),
            Section::Identity => Some("Identity and limits"),
            Section::Command => Some("The command and its process"),
            Section::Networking => Some("Networking"),
            Section::Hardening => Some("Hardening"),
            Section::Off => Some("Turning off what is on by default"),
            Section::Help => Some("Help and version"),
            Section::Counterpart => None,
        }
    }
}

/// What a launch does with a flag, and what the flag takes.
///
/// The two are one field rather than two, so that a flag's arity is the shape
/// of the function that applies it and cannot disagree with it.
#[derive(Clone, Copy)]
enum Take {
    /// A flag with nothing after it.
    Bare(fn(&mut Options)),
    /// A flag taking one value.
    One(fn(&mut Options, &'static str, OsString) -> Result<(), String>),
    /// A flag taking two.
    Two(fn(&mut Options, &'static str, OsString, OsString) -> Result<(), String>),
    /// A flag a launch refuses, because it belongs to another mode. The arity
    /// is still recorded: the pre-scan walks past such a flag's value like any
    /// other's, and reading its value as the command is how a mode used to be
    /// chosen by accident.
    Refused(Arity),
}

/// One flag `fcage` accepts, wherever it accepts it.
///
/// This is the parser's vocabulary, the help's contents, and the suggester's
/// candidate list, declared once. Each of those used to be derived from one of
/// the others by scraping text -- the help read out of a 371-line string
/// constant, and the parser's vocabulary read out of this file's own source --
/// which meant a pattern that stopped matching produced an empty list and an
/// empty list passed.
#[derive(Clone, Copy)]
struct Flag {
    /// The name, with its leading dashes.
    long: &'static str,
    /// A one-letter alias, where the flag has one.
    short: Option<&'static str>,
    /// What `--help` writes after the name: `DIR`, `SRC DEST`, or nothing.
    placeholder: &'static str,
    /// Where `--help` lists it.
    section: Section,
    /// What `--help` says about it, one entry per line of the entry's body.
    ///
    /// Held as written rather than as a paragraph to wrap: the help is prose
    /// broken where it reads well rather than at a column, and re-wrapping it
    /// would move a line break the person who wrote the sentence chose.
    help: &'static [&'static str],
    /// Whether a roster generated from the library follows the entry.
    roster: bool,
    /// The invocation it belongs to.
    mode: Mode,
    /// Whether naming this flag is what selects its mode.
    selects: bool,
    /// What a missing value is reported as: `--flag requires {needs}`.
    needs: &'static str,
    /// What a launch does with it, and what it takes.
    take: Take,
}

impl Flag {
    /// The fields most flags share, so an entry states only what is its own.
    const DEFAULTS: Flag = Flag {
        long: "",
        short: None,
        placeholder: "",
        section: Section::Command,
        help: &[],
        roster: false,
        mode: Mode::Launch,
        selects: false,
        needs: "a value",
        take: Take::Refused(Arity::Bare),
    };

    /// What follows this flag's name.
    const fn arity(&self) -> Arity {
        match self.take {
            Take::Bare(_) => Arity::Bare,
            Take::One(_) => Arity::One,
            Take::Two(_) => Arity::Two,
            Take::Refused(arity) => arity,
        }
    }

    /// The name and its placeholder, as `--help` writes them.
    fn spelled(&self) -> String {
        let mut out = String::new();
        if let Some(short) = self.short {
            out.push_str(short);
            out.push_str(", ");
        }
        out.push_str(self.long);
        if !self.placeholder.is_empty() {
            out.push(' ');
            out.push_str(self.placeholder);
        }
        out
    }
}

/// Every flag `fcage` accepts, in the order `--help` lists them.
const FLAGS: &[Flag] = &[
    Flag {
        long: "--rootfs",
        section: Section::Provisioning,
        placeholder: "DIR",
        help: &["Directory to present as the sandbox root filesystem"],
        take: Take::One(|options, _flag, value| {
            options.rootfs = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--provision-tar",
        section: Section::Provisioning,
        placeholder: "FILE",
        help: &[
            "Provision --rootfs from a tar archive (plain, gzip,",
            "xz, or zstd) when the directory does not exist yet",
        ],
        take: Take::One(|options, _flag, value| {
            options.provision_tar = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--provision-debian",
        section: Section::Provisioning,
        placeholder: "SUITE",
        help: &[
            "Bootstrap --rootfs as a Debian SUITE (e.g. trixie)",
            "from the archive; given without a command, provision",
            "and exit",
        ],
        take: Take::One(|options, flag, value| {
            options.provision_debian = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-arch",
        section: Section::Provisioning,
        placeholder: "ARCH",
        help: &[
            "Target architecture for --provision-debian (default:",
            "the host architecture)",
        ],
        take: Take::One(|options, flag, value| {
            options.debian_arch = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-mirror",
        section: Section::Provisioning,
        placeholder: "URL",
        help: &["Archive mirror (default: http://deb.debian.org/debian)"],
        take: Take::One(|options, flag, value| {
            options.debian_mirror = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-components",
        section: Section::Provisioning,
        placeholder: "L",
        help: &["Comma-separated components (default: main; repeatable)"],
        take: Take::One(|options, flag, value| {
            extend_comma(&mut options.debian_components, &into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-include",
        section: Section::Provisioning,
        placeholder: "L",
        help: &["Extra packages to install (comma-separated, repeatable)"],
        take: Take::One(|options, flag, value| {
            extend_comma(&mut options.debian_include, &into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-exclude",
        section: Section::Provisioning,
        placeholder: "L",
        help: &[
            "Packages to keep out of the resolution, with their",
            "dependents (comma-separated, repeatable)",
        ],
        take: Take::One(|options, flag, value| {
            extend_comma(&mut options.debian_exclude, &into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-plan",
        section: Section::Provisioning,
        placeholder: "FILE",
        help: &[
            "Install exactly the packages FILE names, resolving",
            "nothing. FILE is a plan document a previous resolution",
            "wrote; it supersedes --debian-include and",
            "--debian-exclude",
        ],
        take: Take::One(|options, _flag, value| {
            options.debian_plan = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-pin",
        section: Section::Provisioning,
        placeholder: "FILE",
        help: &[
            "Hold the resolution to the versions the plan document",
            "FILE records, resolving everything it does not name.",
            "Where --debian-plan replaces a resolution, this",
            "constrains one",
        ],
        take: Take::One(|options, _flag, value| {
            options.debian_pin = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-extract-only",
        section: Section::Provisioning,
        help: &[
            "Lay out files without configuring them (runs no",
            "maintainer scripts; for a foreign architecture)",
        ],
        take: Take::Bare(|options| {
            options.debian_extract_only = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-cache",
        section: Section::Provisioning,
        placeholder: "DIR",
        help: &["Cache downloaded packages in DIR, reused across runs"],
        take: Take::One(|options, _flag, value| {
            options.debian_cache = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-keyring",
        section: Section::Provisioning,
        placeholder: "FILE",
        help: &["Verify the archive with FILE, not the embedded keyring"],
        take: Take::One(|options, _flag, value| {
            options.debian_keyring = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-mirror-fallback",
        section: Section::Provisioning,
        placeholder: "URL",
        help: &[
            "A further URL for the same archive, tried when the",
            "primary mirror does not serve a resource (repeatable,",
            "in order)",
        ],
        take: Take::One(|options, flag, value| {
            options
                .debian_mirror_fallback
                .push(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-base-priority",
        section: Section::Provisioning,
        placeholder: "P",
        help: &[
            "The priority floor the base set is drawn from:",
            "required (default), important, standard, optional,",
            "or extra",
        ],
        take: Take::One(|options, flag, value| {
            options.debian_base_priority = Some(parse_priority(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-trust-unsigned",
        section: Section::Provisioning,
        help: &[
            "Accept the archive without verifying its signature.",
            "Every mirror must then be file:// or https://, the",
            "transports that authenticate what they serve",
        ],
        take: Take::Bare(|options| {
            options.debian_trust_unsigned = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-allow-stale-release",
        section: Section::Provisioning,
        help: &["Accept a signed release whose validity has expired"],
        take: Take::Bare(|options| {
            options.debian_allow_stale_release = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-pre-configure-overlay",
        section: Section::Provisioning,
        placeholder: "DIR",
        help: &[
            "Overlay DIR onto the root after the files are laid",
            "out and before any maintainer script runs",
        ],
        take: Take::One(|options, _flag, value| {
            options.debian_pre_configure_overlay = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-identity-map",
        section: Section::Provisioning,
        placeholder: "M",
        help: &[
            "Identity map for the bootstrap's own cages, in the",
            "form --identity-map takes; a range map records real",
            "ownership instead of the single-map stubs",
        ],
        take: Take::One(|options, flag, value| {
            options.debian_identity_map =
                Some(parse_identity_map(flag, &into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--debian-repository",
        section: Section::Provisioning,
        placeholder: "SPEC",
        help: &[
            "An additional archive source, merged into the same",
            "resolution. SPEC is space-separated key=value fields:",
            "'suite=S mirror=URL [mirror-fallback=URL]",
            "[components=a,b] [keyring=PATH] [name=NAME]",
            "[trust-unsigned] [allow-stale-release]'. Repeatable",
        ],
        take: Take::One(|options, flag, value| {
            options
                .debian_repositories
                .push(parse_repository(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--provision-alpine",
        section: Section::Provisioning,
        placeholder: "RELEASE",
        help: &[
            "Bootstrap --rootfs as an Alpine RELEASE (e.g. v3.23)",
            "from the archive; given without a command, provision",
            "and exit",
        ],
        take: Take::One(|options, flag, value| {
            options.provision_alpine = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-arch",
        section: Section::Provisioning,
        placeholder: "ARCH",
        help: &[
            "Target architecture for --provision-alpine (default:",
            "the host architecture)",
        ],
        take: Take::One(|options, flag, value| {
            options.alpine_arch = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-mirror",
        section: Section::Provisioning,
        placeholder: "URL",
        help: &[
            "Archive mirror (default:",
            "http://dl-cdn.alpinelinux.org/alpine)",
        ],
        take: Take::One(|options, flag, value| {
            options.alpine_mirror = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-components",
        section: Section::Provisioning,
        placeholder: "L",
        help: &["Comma-separated components (default: main; repeatable)"],
        take: Take::One(|options, flag, value| {
            extend_comma(&mut options.alpine_components, &into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-include",
        section: Section::Provisioning,
        placeholder: "L",
        help: &[
            "Packages to install (comma-separated, repeatable).",
            "apk has no priority band, so nothing is installed that",
            "was not named here or required by something that was",
        ],
        take: Take::One(|options, flag, value| {
            extend_comma(&mut options.alpine_include, &into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-exclude",
        section: Section::Provisioning,
        placeholder: "L",
        help: &[
            "Packages to keep out of the resolution (comma-separated,",
            "repeatable)",
        ],
        take: Take::One(|options, flag, value| {
            extend_comma(&mut options.alpine_exclude, &into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-plan",
        section: Section::Provisioning,
        placeholder: "FILE",
        help: &[
            "Install exactly the packages FILE names, resolving",
            "nothing. FILE is a plan document a previous resolution",
            "wrote; it supersedes --alpine-include and",
            "--alpine-exclude",
        ],
        take: Take::One(|options, _flag, value| {
            options.alpine_plan = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-pin",
        section: Section::Provisioning,
        placeholder: "FILE",
        help: &[
            "Hold the resolution to the versions the plan document",
            "FILE records, resolving everything it does not name.",
            "Where --alpine-plan replaces a resolution, this",
            "constrains one",
        ],
        take: Take::One(|options, _flag, value| {
            options.alpine_pin = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-extract-only",
        section: Section::Provisioning,
        help: &[
            "Lay out files and register them without running any",
            "install script (for a foreign architecture)",
        ],
        take: Take::Bare(|options| {
            options.alpine_extract_only = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-cache",
        section: Section::Provisioning,
        placeholder: "DIR",
        help: &["Cache downloaded packages in DIR, reused across runs"],
        take: Take::One(|options, _flag, value| {
            options.alpine_cache = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-keys",
        section: Section::Provisioning,
        placeholder: "SOURCE",
        help: &[
            "The keys the archive is verified against: 'alpine' (the",
            "bundled set for the target architecture, the default),",
            "'postmarketos', or a directory of PEM public keys named",
            "as the repository publishes them",
        ],
        take: Take::One(|options, flag, value| {
            options.alpine_keys = Some(parse_alpine_keys(flag, &into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-mirror-fallback",
        section: Section::Provisioning,
        placeholder: "URL",
        help: &[
            "A further URL for the same archive, tried when the",
            "primary mirror does not serve a resource (repeatable,",
            "in order)",
        ],
        take: Take::One(|options, flag, value| {
            options
                .alpine_mirror_fallback
                .push(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-pre-configure-overlay",
        section: Section::Provisioning,
        placeholder: "DIR",
        help: &[
            "Overlay DIR onto the root after the files are laid",
            "out and before any install script runs",
        ],
        take: Take::One(|options, _flag, value| {
            options.alpine_pre_configure_overlay = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-identity-map",
        section: Section::Provisioning,
        placeholder: "M",
        help: &[
            "Identity map for the bootstrap's own cages, in the",
            "form --identity-map takes",
        ],
        take: Take::One(|options, flag, value| {
            options.alpine_identity_map =
                Some(parse_identity_map(flag, &into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--alpine-repository",
        section: Section::Provisioning,
        placeholder: "SPEC",
        help: &[
            "An additional archive source, merged into the same",
            "resolution. SPEC is space-separated key=value fields:",
            "'release=R mirror=URL keys=SOURCE [mirror-fallback=URL]",
            "[components=a,b]'. Naming no components selects the",
            "<release>/<architecture> layout postmarketOS publishes.",
            "Repeatable",
        ],
        take: Take::One(|options, flag, value| {
            options
                .alpine_repositories
                .push(parse_alpine_repository(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--provision-gentoo",
        section: Section::Provisioning,
        placeholder: "ARCH",
        help: &[
            "Bootstrap --rootfs from a signed Gentoo stage3 for",
            "ARCH (e.g. amd64); given without a command, provision",
            "and exit. Gentoo publishes one tree per architecture",
            "rather than a release, so ARCH is the coordinate",
        ],
        take: Take::One(|options, flag, value| {
            options.provision_gentoo = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-variant",
        section: Section::Provisioning,
        placeholder: "NAME",
        help: &[
            "The stage3 to install, as the archive spells it:",
            "'amd64-openrc', 'amd64-hardened-systemd', 'x32-openrc'.",
            "--gentoo-variants lists what an architecture offers",
        ],
        take: Take::One(|options, flag, value| {
            options.gentoo_variant = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-build-id",
        section: Section::Provisioning,
        placeholder: "ID",
        help: &[
            "Install the build in directory ID (e.g.",
            "20260810T204554Z) rather than the current one. The",
            "archive keeps about five weeks of builds, so a pinned",
            "id resolves against it for roughly a month and against",
            "a populated --gentoo-cache indefinitely",
        ],
        take: Take::One(|options, flag, value| {
            options.gentoo_build_id = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-binhost",
        section: Section::Provisioning,
        placeholder: "SUBARCH",
        help: &[
            "Install binary packages from the binhost tree for",
            "SUBARCH ('x86-64', 'x86-64-v3', 'x86-64_hardened',",
            "'x32'). There is no default: nothing signed enumerates",
            "the trees, so a wrong one is a 404 rather than a",
            "silently different userland",
        ],
        take: Take::One(|options, flag, value| {
            options.gentoo_binhost = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-install",
        section: Section::Provisioning,
        placeholder: "ATOM",
        help: &[
            "Install ATOM and its runtime dependencies from the",
            "binhost, in Gentoo's own dependency grammar:",
            "'dev-vcs/git', '>=dev-lang/python-3.12',",
            "'dev-libs/openssl:0'. Repeatable. A USE dependency in",
            "an atom is a constraint -- 'dev-vcs/git[keyring]'",
            "refuses to install a build without the flag",
        ],
        take: Take::One(|options, flag, value| {
            options.gentoo_install.push(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-prefer-use",
        section: Section::Provisioning,
        placeholder: "FLAGS",
        help: &[
            "Prefer builds carrying these space-separated USE flags,",
            "and builds without the ones written '-flag'. A",
            "preference, not a constraint: it reorders the candidate",
            "builds and cannot make an atom unsatisfiable. Repeatable",
        ],
        take: Take::One(|options, flag, value| {
            options.gentoo_prefer_use.extend(
                into_string(flag, value)?
                    .split_ascii_whitespace()
                    .map(str::to_string),
            );
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-plan",
        section: Section::Provisioning,
        placeholder: "FILE",
        help: &[
            "Install exactly the packages FILE names, resolving",
            "nothing. FILE is a plan document a previous run wrote;",
            "it supersedes --gentoo-install and --gentoo-prefer-use",
        ],
        take: Take::One(|options, _flag, value| {
            options.gentoo_plan = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-mirror",
        section: Section::Provisioning,
        placeholder: "URL",
        help: &["Archive mirror (default:", "http://distfiles.gentoo.org)"],
        take: Take::One(|options, flag, value| {
            options.gentoo_mirror = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-mirror-fallback",
        section: Section::Provisioning,
        placeholder: "URL",
        help: &[
            "A further URL for the same archive, tried when the",
            "primary mirror does not serve a resource (repeatable,",
            "in order)",
        ],
        take: Take::One(|options, flag, value| {
            options
                .gentoo_mirror_fallback
                .push(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-cache",
        section: Section::Provisioning,
        placeholder: "DIR",
        help: &[
            "Cache the downloaded stage3 and binary packages in DIR,",
            "reused across runs",
        ],
        take: Take::One(|options, _flag, value| {
            options.gentoo_cache = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-max-pointer-age",
        section: Section::Provisioning,
        placeholder: "DAYS",
        help: &[
            "Refuse a signed pointer document regenerated more than",
            "DAYS ago (default: 30), or 'none' to accept one of any",
            "age. Gentoo publishes no expiry of any kind, so this",
            "timestamp is the only thing that says when a document",
            "stopped being current; clearing the bound accepts a",
            "replayed one, which is what an archived mirror needs",
        ],
        take: Take::One(|options, flag, value| {
            options.gentoo_max_pointer_age = Some(parse_pointer_age(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-variants",
        section: Section::Provisioning,
        placeholder: "ARCH",
        help: &[
            "Print the stage3 variants ARCH publishes, from the",
            "signed enumeration, and exit. Takes --gentoo-mirror,",
            "--gentoo-mirror-fallback and --gentoo-max-pointer-age",
        ],
        mode: Mode::GentooVariants,
        selects: true,
        take: Take::Refused(Arity::One),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-packages",
        section: Section::Provisioning,
        placeholder: "ARCH",
        help: &[
            "Print what the binhost publishes for ARCH: every",
            "package name and its versions, and exit. Takes",
            "--gentoo-binhost, --gentoo-mirror and",
            "--gentoo-mirror-fallback",
        ],
        mode: Mode::GentooPackages,
        selects: true,
        take: Take::Refused(Arity::One),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-installed",
        section: Section::Provisioning,
        placeholder: "ROOT",
        help: &[
            "Print what the Gentoo root at ROOT already has",
            "installed, from its own package database, and exit.",
            "Reaches no network",
        ],
        mode: Mode::GentooInstalled,
        selects: true,
        take: Take::Refused(Arity::One),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--gentoo-keyring-horizon",
        section: Section::Provisioning,
        help: &[
            "Print the vendored Gentoo keyring: every certificate,",
            "whether it can still sign, and when its authority",
            "lapses. Reaches no network",
        ],
        mode: Mode::GentooKeyring,
        selects: true,
        take: Take::Refused(Arity::Bare),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--remove-rootfs",
        section: Section::Provisioning,
        placeholder: "DIR",
        help: &[
            "Delete the provisioned rootfs at DIR and exit,",
            "including one a range-mapped sandbox wrote and a plain",
            "'rm -rf' cannot remove. Give the --identity-map the",
            "tree was provisioned under; the default is",
            "'subordinate'. Removing a path that is not there",
            "succeeds, so the call is repeatable. Takes no other",
            "option: it removes a rootfs rather than running a",
            "command in one",
        ],
        mode: Mode::Remove,
        selects: true,
        take: Take::Refused(Arity::One),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--export-rootfs",
        section: Section::Provisioning,
        placeholder: "DIR",
        help: &[
            "Write the provisioned rootfs at DIR to a tar archive",
            "and exit, preserving the ownership the tree intends",
            "and the extended attributes a host-side 'tar' cannot",
            "read. Give the --identity-map the tree was provisioned",
            "under; the default is 'subordinate'. Takes no other",
            "option: it exports a rootfs rather than running a",
            "command in one",
        ],
        mode: Mode::Export,
        selects: true,
        take: Take::Refused(Arity::One),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--export-to",
        section: Section::Provisioning,
        placeholder: "FILE",
        help: &[
            "Where --export-rootfs writes. The default is standard",
            "output, so the archive pipes into a compressor without",
            "a temporary file; writing one to a terminal is refused",
        ],
        mode: Mode::Export,
        take: Take::Refused(Arity::One),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--clamp-mtime",
        section: Section::Provisioning,
        placeholder: "EPOCH",
        help: &[
            "Cap every modification time --export-rootfs records at",
            "EPOCH, a Unix timestamp in seconds. With it the archive",
            "is byte-reproducible given the tree",
        ],
        mode: Mode::Export,
        take: Take::Refused(Arity::One),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--profile",
        section: Section::Profiles,
        placeholder: "FILE",
        help: &[
            "Load a TOML sandbox profile; flags given alongside",
            "override its settings, binds and variables extend it,",
            "and any [hardening] table it carries takes effect. A",
            "profile is trusted like a script: it can bind any host",
            "path, issue raw mounts, share the host network, and",
            "share the host PID namespace. Load only a profile you",
            "trust, or use --restricted-profile",
        ],
        take: Take::One(|options, _flag, value| {
            let path = PathBuf::from(value);
            set_profile(options, path, false)?;
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--restricted-profile",
        section: Section::Profiles,
        placeholder: "FILE",
        help: &[
            "Load a TOML profile from an untrusted source: like",
            "--profile, but the operations that map host resources",
            "into the sandbox or share a host namespace (binds, raw",
            "mounts, host networking, the host PID namespace) are",
            "refused. The rootfs it names still grants access to that",
            "host subtree, so pass a rootfs you control",
        ],
        take: Take::One(|options, _flag, value| {
            let path = PathBuf::from(value);
            set_profile(options, path, true)?;
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--overlay-lower",
        section: Section::Profiles,
        placeholder: "DIR",
        help: &[
            "Root the sandbox on an overlay whose base is DIR",
            "(repeatable and ordered: the first is the base, each",
            "later one is laid over it). Alternative to --rootfs",
        ],
        take: Take::One(|options, _flag, value| {
            options.overlay_lowers.push(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--overlay-upper",
        section: Section::Profiles,
        placeholder: "DIR",
        help: &[
            "Where the overlay's writes land; DIR persists after",
            "the sandbox exits, so discarding it reverts the run.",
            "Required with --overlay-lower",
        ],
        take: Take::One(|options, _flag, value| {
            options.overlay_upper = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--overlay-work",
        section: Section::Profiles,
        placeholder: "DIR",
        help: &[
            "Override the overlay's work directory, which must sit",
            "on the same filesystem as the upper",
        ],
        take: Take::One(|options, _flag, value| {
            options.overlay_work = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--bind",
        section: Section::Profiles,
        placeholder: "SRC DEST",
        help: &["Bind-mount host path SRC read-write at DEST"],
        needs: "a source and a target",
        take: Take::Two(|options, _flag, value, second| {
            let source = value;
            let target = second;
            options.mounts.push(Mount::Bind(
                Bind::new(PathBuf::from(source), PathBuf::from(target)).read_only(false),
            ));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--ro-bind",
        section: Section::Profiles,
        placeholder: "SRC DEST",
        help: &["Bind-mount host path SRC read-only at DEST"],
        needs: "a source and a target",
        take: Take::Two(|options, _flag, value, second| {
            let source = value;
            let target = second;
            options.mounts.push(Mount::Bind(
                Bind::new(PathBuf::from(source), PathBuf::from(target)).read_only(true),
            ));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--raw-mount",
        section: Section::Profiles,
        placeholder: "SPEC",
        help: &[
            "A mount the typed options do not model, passed to the",
            "kernel as given. SPEC is space-separated key=value",
            "fields: 'target=/sys fstype=sysfs flags=0xE",
            "[source=...] [data=...]'. Only the target is validated",
            "and confined. Repeatable.",
            "Mounts apply in the order these flags appear, so a",
            "--raw-mount tmpfs followed by --bind flags into it",
            "builds a directory the sandbox owns outright",
        ],
        take: Take::One(|options, flag, value| {
            options
                .mounts
                .push(Mount::Raw(parse_raw_mount(&into_string(flag, value)?)?));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--identity-map",
        section: Section::Identity,
        placeholder: "M",
        help: &[
            "How the user namespace maps identities: 'single'",
            "(default: root inside is you outside, and no other id",
            "exists), 'subordinate' (root plus your whole",
            "subordinate allocation, through newuidmap/newgidmap),",
            "or explicit extents,",
            "'uid=IN:OUT:COUNT[,...] gid=IN:OUT:COUNT[,...]'",
        ],
        take: Take::One(|options, flag, value| {
            options.identity_map = Some(parse_identity_map(flag, &into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--run-as",
        section: Section::Identity,
        placeholder: "UID:GID[:G,...]",
        help: &[
            "Run the command as a non-root identity inside the",
            "sandbox, with optional supplementary groups. Every id",
            "must be contained in the identity map; groups need a",
            "range gid map",
        ],
        take: Take::One(|options, flag, value| {
            options.run_as = Some(parse_run_as(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--rlimit",
        section: Section::Identity,
        placeholder: "RES=SOFT[:HARD]",
        help: &[
            "Set a resource limit on the command, inherited by",
            "every process it starts. A value may be 'unlimited',",
            "and an omitted hard limit repeats the soft one.",
            "Repeatable (e.g. --rlimit processes=64 --rlimit",
            "address-space=536870912). RES is one of:",
        ],
        roster: true,
        take: Take::One(|options, flag, value| {
            options
                .rlimits
                .push(parse_rlimit(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--path-lookup",
        section: Section::Command,
        help: &[
            "Resolve a command with no slash against the sandbox's",
            "PATH, the way a shell does",
        ],
        take: Take::Bare(|options| {
            options.path_lookup = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--setenv",
        section: Section::Command,
        placeholder: "NAME VALUE",
        help: &["Set an environment variable for the command"],
        needs: "a name and a value",
        take: Take::Two(|options, flag, value, second| {
            // Validated here so a bad name is the usage error it is (exit 2),
            // rather than deferring to the library's build-time rejection
            // (exit 125). The rule matches the library's.
            if value.is_empty() || value.as_bytes().contains(&b'=') {
                return Err(format!(
                    "{flag}: {value:?} is not a valid environment variable name \
                     (it is empty or contains '=')"
                ));
            }
            options.setenv.push((value, second));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--hostname",
        section: Section::Command,
        placeholder: "NAME",
        help: &["Set the hostname inside the sandbox"],
        take: Take::One(|options, _flag, value| {
            options.hostname = Some(value);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--chdir",
        section: Section::Command,
        placeholder: "DIR",
        help: &["Working directory inside the sandbox (default /)"],
        take: Take::One(|options, _flag, value| {
            options.chdir = Some(PathBuf::from(value));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--stdin",
        section: Section::Command,
        placeholder: "MODE",
        help: &[
            "Standard input: inherit (default) or null. With null",
            "the command also runs in a session of its own, so the",
            "terminal fcage was started from is not its controlling",
            "terminal; an interrupt there stops fcage, which stops",
            "the sandbox. Standard output and standard error still",
            "reach that terminal unless redirected, which a shell",
            "already spells and a profile carries as stdout/stderr",
        ],
        take: Take::One(|options, _flag, value| {
            options.stdin = Some(parse_stdin(&value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--terminal",
        section: Section::Command,
        help: &[
            "Give the sandbox a pseudoterminal of its own and relay",
            "this terminal to it: interactive programs work, and the",
            "sandbox reaches nothing of the terminal fcage was",
            "started from. TERM passes through as ever, so set it",
            "with --setenv TERM to override. From a script, where",
            "fcage's own input is not a terminal, this degrades to a",
            "plain byte relay around a sandbox that still has a real",
            "terminal of its own, at 80x24",
        ],
        take: Take::Bare(|options| {
            options.terminal = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--timeout",
        section: Section::Command,
        placeholder: "SECS",
        help: &[
            "Terminate the command after SECS seconds, kill it",
            "--kill-after seconds later, and exit 124",
        ],
        take: Take::One(|options, flag, value| {
            options.timeout = Some(parse_seconds(flag, &value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--kill-after",
        section: Section::Command,
        placeholder: "SECS",
        help: &["Grace between terminate and kill (default 10)"],
        take: Take::One(|options, flag, value| {
            options.kill_after = parse_seconds(flag, &value)?;
            options.kill_after_given = true;
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--stop-with-caller",
        section: Section::Command,
        help: &[
            "Stop the sandbox when fcage itself exits (the default;",
            "--no-stop-with-caller leaves it running)",
        ],
        take: Take::Bare(|options| {
            options.stop_with_caller = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--share-net",
        section: Section::Networking,
        help: &["Share the host network (default: isolated loopback)"],
        take: Take::Bare(|options| {
            options.network = Some(Network::Host);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--deny-net",
        section: Section::Networking,
        help: &[
            "Isolated network with loopback left down (no",
            "connectivity at all, not even 127.0.0.1)",
        ],
        take: Take::Bare(|options| {
            options.network = Some(Network::None);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--netstack",
        section: Section::Networking,
        help: &[
            "Attach the native userspace network stack: outbound",
            "IPv4 and IPv6 for the isolated network, forwarded over",
            "host sockets with no external helper. Composes the",
            "sandbox's resolv.conf from the host's routable",
            "nameservers unless --no-resolv-conf or",
            "--no-managed-mounts is given; a host with only loopback",
            "nameservers composes nothing, leaving the rootfs's own",
            "resolv.conf in place",
        ],
        take: Take::Bare(|options| {
            options.netstack = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--netstack-cidr",
        section: Section::Networking,
        placeholder: "V4/LEN",
        help: &[
            "IPv4 network for --netstack (default 10.0.2.0/24; the",
            "gateway is host 2, the guest host 15)",
        ],
        take: Take::One(|options, flag, value| {
            options.netstack_cidr = Some(parse_cidr(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--netstack-cidr6",
        section: Section::Networking,
        placeholder: "V6/LEN",
        help: &[
            "IPv6 network for --netstack (default fd00::/64; the",
            "gateway is host 2, the guest host 15)",
        ],
        take: Take::One(|options, flag, value| {
            options.netstack_cidr6 = Some(parse_cidr6(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--netstack-no-ipv4",
        section: Section::Networking,
        help: &[
            "Run the stack without IPv4, for a workload or a host",
            "where it is unwanted. The guest is then given no IPv4",
            "address and the stack answers no IPv4 traffic",
        ],
        take: Take::Bare(|options| {
            options.netstack_no_ipv4 = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--netstack-no-ipv6",
        section: Section::Networking,
        help: &[
            "Run the stack without IPv6, for a host that offers no",
            "IPv6 connectivity. The guest is then given no IPv6",
            "address and the stack answers no IPv6 traffic",
        ],
        take: Take::Bare(|options| {
            options.netstack_no_ipv6 = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--netstack-interface",
        section: Section::Networking,
        placeholder: "NAME",
        help: &[
            "Name the stack's interface inside the sandbox (default",
            "tap0; 1 to 15 bytes, free of '/', ':', and whitespace)",
        ],
        take: Take::One(|options, flag, value| {
            options.netstack_interface = Some(into_string(flag, value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--netstack-mtu",
        section: Section::Networking,
        placeholder: "N",
        help: &[
            "Interface MTU for --netstack (default 1500; the minimum",
            "is 576, or 1280 while IPv6 is enabled)",
        ],
        take: Take::One(|options, flag, value| {
            options.netstack_mtu = Some(parse_mtu(&into_string(flag, value)?)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--netstack-host-loopback",
        section: Section::Networking,
        help: &[
            "Map connections to the gateway address onto the host's",
            "127.0.0.1, port preserved, to reach a service bound",
            "there (off by default; every other loopback destination",
            "stays blocked, including a resolver on another loopback",
            "address such as systemd-resolved's 127.0.0.53 stub)",
        ],
        take: Take::Bare(|options| {
            options.netstack_host_loopback = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--restrict",
        section: Section::Hardening,
        help: &[
            "Confine the command with Landlock and seccomp only:",
            "no namespaces, no root filesystem swap, and paths are",
            "host paths. The fallback for hosts without",
            "unprivileged user namespaces; requires at least one",
            "--landlock-* or --seccomp flag, and accepts only",
            "those plus --setenv, --no-base-env, --chdir,",
            "--stdin, --terminal, --timeout, --kill-after,",
            "--rlimit, and --stop-with-caller",
        ],
        take: Take::Bare(|options| {
            options.restrict = true;
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--landlock-ro",
        section: Section::Hardening,
        placeholder: "PATH",
        help: &[
            "Grant the command read and execute beneath PATH under",
            "a Landlock ruleset (repeatable; enrolling any grant",
            "denies all filesystem access not granted)",
        ],
        take: Take::One(|options, _flag, value| {
            let path = value;
            options.landlock.push((PathBuf::from(path), false));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--landlock-rw",
        section: Section::Hardening,
        placeholder: "PATH",
        help: &[
            "Grant read, write, and execute beneath PATH",
            "(repeatable)",
        ],
        take: Take::One(|options, _flag, value| {
            let path = value;
            options.landlock.push((PathBuf::from(path), true));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--landlock-bind",
        section: Section::Hardening,
        placeholder: "PORT",
        help: &[
            "Allow binding a TCP socket to PORT under a Landlock",
            "ruleset (repeatable; enrolling any network grant denies",
            "every bind and connect not granted; port 0 permits a",
            "kernel-assigned ephemeral port; needs Landlock ABI 4)",
        ],
        take: Take::One(|options, flag, value| {
            let value = into_string(flag, value)?;
            options
                .landlock_net
                .push((parse_port(flag, &value)?, NetAccess::BIND));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--landlock-connect",
        section: Section::Hardening,
        placeholder: "PORT",
        help: &["Allow connecting a TCP socket to PORT (repeatable)"],
        take: Take::One(|options, flag, value| {
            let value = into_string(flag, value)?;
            options
                .landlock_net
                .push((parse_port(flag, &value)?, NetAccess::CONNECT));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--seccomp",
        section: Section::Hardening,
        placeholder: "curated",
        help: &[
            "Apply the curated seccomp deny-list of dangerous",
            "syscalls to the command",
        ],
        take: Take::One(|options, flag, value| {
            parse_seccomp(&into_string(flag, value)?, &mut options.seccomp_curated)?;
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--seccomp-allow",
        section: Section::Hardening,
        placeholder: "LIST",
        help: &[
            "Allow only these syscalls, denying the rest with EPERM",
            "(comma-separated names, repeatable; must name every",
            "syscall the command needs)",
        ],
        take: Take::One(|options, flag, value| {
            let value = into_string(flag, value)?;
            parse_seccomp_names(flag, &value, &mut options.seccomp_allow)?;
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--seccomp-deny",
        section: Section::Hardening,
        placeholder: "LIST",
        help: &[
            "Deny these syscalls with EPERM, allowing the rest",
            "(comma-separated names, repeatable)",
        ],
        take: Take::One(|options, flag, value| {
            let value = into_string(flag, value)?;
            parse_seccomp_names(flag, &value, &mut options.seccomp_deny)?;
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--seccomp-allow-rule",
        section: Section::Hardening,
        placeholder: "RULE",
        help: &[
            "Allow a syscall only when its arguments match; RULE is",
            "a syscall name and comma-separated conditions, each of",
            "the form 'arg=N len=dword|qword op=OP value=V', with",
            "op one of eq, ne, ge, gt, le, lt, or masked-eq (which",
            "also takes mask=M). Repeatable; repeating a syscall",
            "accepts any of the rules. Example:",
            "'ioctl arg=1 len=dword op=eq value=0x5413'",
        ],
        take: Take::One(|options, flag, value| {
            let value = into_string(flag, value)?;
            options
                .seccomp_allow_rules
                .push(parse_seccomp_rule(flag, &value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--seccomp-deny-rule",
        section: Section::Hardening,
        placeholder: "RULE",
        help: &[
            "Deny a syscall only when its arguments match, in the",
            "same form as --seccomp-allow-rule",
        ],
        take: Take::One(|options, flag, value| {
            let value = into_string(flag, value)?;
            options
                .seccomp_deny_rules
                .push(parse_seccomp_rule(flag, &value)?);
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--drop-caps",
        section: Section::Hardening,
        help: &["Drop every capability from the command"],
        take: Take::Bare(|options| {
            options.caps = Some(CapsChoice::DropAll);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--keep-caps",
        section: Section::Hardening,
        placeholder: "LIST",
        help: &[
            "Drop every capability except LIST (comma-separated,",
            "e.g. net-bind-service,sys-chroot)",
        ],
        take: Take::One(|options, flag, value| {
            options.caps = Some(CapsChoice::Keep(parse_caps(&into_string(flag, value)?)?));
            Ok(())
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--share-pid",
        section: Section::Off,
        help: &["Share the host PID namespace (default: isolated)"],
        take: Take::Bare(|options| {
            options.pid_namespace = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--no-proc",
        section: Section::Off,
        help: &[
            "Do not mount /proc. A cage needs a procfs from",
            "somewhere -- the nested user namespace that locks its",
            "mount flags establishes its identity map through one --",
            "so a run that sets this supplies its own with --bind",
        ],
        take: Take::Bare(|options| {
            options.mount_proc = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--no-dev",
        section: Section::Off,
        help: &["Do not assemble the minimal /dev"],
        take: Take::Bare(|options| {
            options.mount_dev = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--no-tmp",
        section: Section::Off,
        help: &["Do not mount a tmpfs on /tmp"],
        take: Take::Bare(|options| {
            options.mount_tmp = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--no-resolv-conf",
        section: Section::Off,
        help: &[
            "Do not bind the host resolv.conf: neither the bind",
            "--share-net makes nor the one --netstack composes",
        ],
        take: Take::Bare(|options| {
            options.resolv_conf = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--no-managed-mounts",
        section: Section::Off,
        help: &[
            "Establish no mount of the library's own, so the sandbox",
            "carries exactly the --bind and --raw-mount flags given.",
            "Unlike the individual --no-* toggles this also excludes",
            "any managed mount a later release adds. One of the flags",
            "given must supply a procfs; see --no-proc",
        ],
        take: Take::Bare(|options| {
            options.managed_mounts = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--no-base-env",
        section: Section::Off,
        help: &[
            "Give the command exactly the --setenv variables, with",
            "no PATH or HOME supplied underneath them",
        ],
        take: Take::Bare(|options| {
            options.base_env = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--isolate-net",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.network = Some(Network::Isolated);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--pid-ns",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.pid_namespace = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--proc",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.mount_proc = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--dev",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.mount_dev = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--tmp",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.mount_tmp = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--resolv-conf",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.resolv_conf = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--managed-mounts",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.managed_mounts = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--base-env",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.base_env = Some(true);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--no-path-lookup",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.path_lookup = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--no-stop-with-caller",
        section: Section::Counterpart,
        take: Take::Bare(|options| {
            options.stop_with_caller = Some(false);
        }),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--help",
        section: Section::Help,
        short: Some("-h"),
        help: &["Print this help"],
        mode: Mode::Help,
        take: Take::Refused(Arity::Bare),
        ..Flag::DEFAULTS
    },
    Flag {
        long: "--version",
        section: Section::Help,
        short: Some("-V"),
        help: &["Print the version"],
        mode: Mode::Version,
        take: Take::Refused(Arity::Bare),
        ..Flag::DEFAULTS
    },
];

/// What `--help` prints above the option sections.
const SYNOPSIS: &str = "\
Run a command inside an unprivileged Linux sandbox.

Usage: fcage [--rootfs DIR | --overlay-lower DIR | --profile FILE | --restricted-profile FILE | --restrict] [OPTIONS] [--] [COMMAND [ARGS...]]
       fcage --remove-rootfs DIR [--identity-map M]
       fcage --export-rootfs DIR [--export-to FILE] [--identity-map M] [--clamp-mtime EPOCH]
";

/// What `--help` prints below them.
///
/// Prose rather than entries, so it stays written out: it names flags in
/// sentences, and the ten counterpart toggles are documented here rather
/// than listed above. A test holds every name it uses to [`FLAGS`], which is
/// what stops it drifting from the vocabulary it describes.
const CLOSING: &str = "\
Each toggle has a counterpart to override a profile in the other direction:
--isolate-net, --pid-ns, --proc, --dev, --tmp, --resolv-conf,
--managed-mounts, --base-env, --stop-with-caller, and --no-path-lookup.
A profile's [hardening] table composes with the hardening flags:
--landlock-ro, --landlock-rw, --landlock-bind, and --landlock-connect add
grants to it, while the seccomp flags, --drop-caps, and --keep-caps replace
its seccomp policy or capability posture. The seccomp flags are mutually
constrained: --seccomp curated stands alone, and an allow side
(--seccomp-allow, --seccomp-allow-rule) cannot be mixed with a deny side
(--seccomp-deny, --seccomp-deny-rule).

The command path is interpreted inside the sandbox (with --restrict, on the
host) and must be absolute; a command given on the command line replaces one
named by the profile. The command runs with inherited standard streams and a
clean environment: PATH and HOME, the host TERM when set, profile variables,
and the --setenv values. With --restrict the base is PATH alone, there being
no sandbox root for HOME to name. --no-base-env drops the base either way.

Exit status: the command's own exit code, or 128 plus the signal number
when it is terminated by a signal, or 124 when --timeout expires. fcage
itself exits 125 when the sandbox cannot be built or launched, 126 when
the command exists but cannot be executed, 127 when the command does not
exist, and 2 on usage errors.
";

/// A parsed command line.
enum Invocation {
    /// Launch a sandbox.
    Run(Box<Options>),
    /// Delete a provisioned rootfs, under the identity map it was written
    /// under.
    Remove {
        dest: PathBuf,
        map: IdentityMap,
    },
    /// Print the stage3 variants an architecture publishes.
    GentooVariants {
        architecture: String,
        /// The archive to read, or `None` for the library's default.
        ///
        /// Kept apart from the backstops, as a provisioning run keeps them, so
        /// that the two flags mean the same thing in both modes.
        mirror: Option<String>,
        fallbacks: Vec<String>,
        max_pointer_age: Option<Option<u64>>,
    },
    /// Print what the binhost publishes for an architecture.
    GentooPackages {
        architecture: String,
        /// The sub-architecture tree, which has no default: nothing signed
        /// enumerates them.
        binhost: Option<String>,
        mirror: Option<String>,
        fallbacks: Vec<String>,
    },
    /// Print what a Gentoo root already has installed, from its own database.
    GentooInstalled {
        root: PathBuf,
    },
    /// Print what each certificate of the vendored Gentoo keyring can still be
    /// trusted to do, and until when.
    GentooKeyring,
    /// Write a provisioned rootfs to a tar archive, under the identity map it
    /// was written under.
    Export {
        source: PathBuf,
        /// Where the archive goes; standard output when absent.
        dest: Option<PathBuf>,
        map: IdentityMap,
        /// The `SOURCE_DATE_EPOCH` ceiling that makes the archive
        /// byte-reproducible, when given.
        clamp_mtime: Option<i64>,
    },
    Help,
    Version,
}

/// Everything a `Run` invocation configures. Toggles are three-state:
/// `None` leaves the profile's (or library's) value in place.
struct Options {
    profile: Option<PathBuf>,
    /// Whether the profile is loaded under the restricted policy
    /// (`--restricted-profile`) rather than fully trusted (`--profile`).
    profile_restricted: bool,
    rootfs: Option<PathBuf>,
    provision_tar: Option<PathBuf>,
    provision_debian: Option<String>,
    debian_arch: Option<String>,
    debian_mirror: Option<String>,
    debian_components: Vec<String>,
    debian_include: Vec<String>,
    debian_exclude: Vec<String>,
    debian_plan: Option<PathBuf>,
    debian_pin: Option<PathBuf>,
    debian_extract_only: bool,
    debian_cache: Option<PathBuf>,
    debian_keyring: Option<PathBuf>,
    debian_mirror_fallback: Vec<String>,
    debian_base_priority: Option<Priority>,
    debian_trust_unsigned: bool,
    debian_allow_stale_release: bool,
    debian_pre_configure_overlay: Option<PathBuf>,
    debian_identity_map: Option<IdentityMap>,
    debian_repositories: Vec<Repository>,
    provision_alpine: Option<String>,
    alpine_arch: Option<String>,
    alpine_mirror: Option<String>,
    alpine_components: Vec<String>,
    alpine_include: Vec<String>,
    alpine_exclude: Vec<String>,
    alpine_plan: Option<PathBuf>,
    alpine_pin: Option<PathBuf>,
    alpine_extract_only: bool,
    alpine_cache: Option<PathBuf>,
    alpine_keys: Option<AlpineKeys>,
    alpine_mirror_fallback: Vec<String>,
    alpine_pre_configure_overlay: Option<PathBuf>,
    alpine_identity_map: Option<IdentityMap>,
    alpine_repositories: Vec<AlpineRepositorySpec>,
    provision_gentoo: Option<String>,
    gentoo_variant: Option<String>,
    gentoo_binhost: Option<String>,
    gentoo_install: Vec<String>,
    gentoo_prefer_use: Vec<String>,
    gentoo_plan: Option<PathBuf>,
    gentoo_build_id: Option<String>,
    gentoo_mirror: Option<String>,
    gentoo_mirror_fallback: Vec<String>,
    gentoo_cache: Option<PathBuf>,
    gentoo_max_pointer_age: Option<Option<u64>>,
    command_line: Vec<OsString>,
    path_lookup: Option<bool>,
    /// Binds and raw mounts in one sequence, so `--bind` and `--raw-mount`
    /// apply in the order they appear on the command line — the same
    /// declaration-order rule the library's `[[mount]]` array follows.
    mounts: Vec<Mount>,
    overlay_lowers: Vec<PathBuf>,
    overlay_upper: Option<PathBuf>,
    overlay_work: Option<PathBuf>,
    identity_map: Option<IdentityMap>,
    run_as: Option<Identity>,
    rlimits: Vec<(Resource, Limit, Limit)>,
    setenv: Vec<(OsString, OsString)>,
    hostname: Option<OsString>,
    chdir: Option<PathBuf>,
    stdin: Option<Stdio>,
    /// Whether to allocate a pseudoterminal for the sandbox and relay it.
    terminal: bool,
    timeout: Option<Duration>,
    kill_after: Duration,
    /// Whether `--kill-after` was given explicitly, to reject it without a
    /// `--timeout` to hang the grace period on.
    kill_after_given: bool,
    network: Option<Network>,
    pid_namespace: Option<bool>,
    mount_proc: Option<bool>,
    mount_dev: Option<bool>,
    mount_tmp: Option<bool>,
    resolv_conf: Option<bool>,
    managed_mounts: Option<bool>,
    base_env: Option<bool>,
    stop_with_caller: Option<bool>,
    landlock: Vec<(PathBuf, bool)>,
    landlock_net: Vec<(u16, NetAccess)>,
    seccomp: Option<SeccompPolicy>,
    /// The seccomp flags as they were given, reconciled into
    /// [`seccomp`](Self::seccomp) once the whole command line has been read.
    ///
    /// The curated posture and the allow and deny sides are mutually
    /// constrained, so they are gathered rather than applied: which of them is
    /// legal depends on what else was given, and the flag that decides can come
    /// last. They live here rather than beside the argument loop because a
    /// flag's own applier reaches exactly one value, and that value is this.
    seccomp_curated: bool,
    seccomp_allow: Vec<i64>,
    seccomp_deny: Vec<i64>,
    seccomp_allow_rules: Vec<(i64, Vec<SeccompArg>)>,
    seccomp_deny_rules: Vec<(i64, Vec<SeccompArg>)>,
    caps: Option<CapsChoice>,
    restrict: bool,
    netstack: bool,
    netstack_cidr: Option<(Ipv4Addr, u8)>,
    netstack_cidr6: Option<(Ipv6Addr, u8)>,
    netstack_no_ipv4: bool,
    netstack_no_ipv6: bool,
    netstack_interface: Option<String>,
    netstack_mtu: Option<u16>,
    netstack_host_loopback: bool,
}

/// The capability posture requested on the command line.
enum CapsChoice {
    /// Drop every capability.
    DropAll,
    /// Keep only these, dropping the rest.
    Keep(Vec<Capability>),
}

/// The help text, with its generated sections filled in.
///
/// The resource-limit names come from the library's own roster rather than a
/// second copy here, so a resource the library gains is offered by `--help` as
/// soon as `--rlimit` accepts it.
fn usage() -> String {
    /// The column an entry's description starts in, and the widest name that
    /// still shares a line with it.
    const DESCRIPTION: usize = 24;
    const NAME_ROOM: usize = DESCRIPTION - 2 - 1;

    let mut out = String::from(SYNOPSIS);
    for section in Section::ALL {
        let Some(heading) = section.heading() else {
            continue;
        };
        out.push('\n');
        out.push_str(heading);
        out.push_str(":\n");
        for flag in FLAGS.iter().filter(|flag| flag.section == *section) {
            let name = flag.spelled();
            let mut body = flag.help.iter();
            // A name too wide to leave room takes a line of its own, and the
            // description begins on the next.
            if name.len() <= NAME_ROOM
                && let Some(first) = body.next()
            {
                out.push_str(&format!(
                    "  {name:<width$}{first}\n",
                    width = DESCRIPTION - 2
                ));
            } else {
                out.push_str(&format!("  {name}\n"));
            }
            for line in body {
                out.push_str(&format!("{:DESCRIPTION$}{line}\n", ""));
            }
            if flag.roster {
                // The resource names come from the library's own roster rather
                // than a second copy here, so a resource the library gains is
                // offered by --help as soon as --rlimit accepts it.
                let names: Vec<&str> = Resource::ALL.iter().map(|r| r.spelling()).collect();
                out.push_str(&wrapped(&names));
                out.push('\n');
            }
        }
    }
    out.push('\n');
    out.push_str(CLOSING);
    out
}

/// The usage error for an option the launch parser does not know, offering the
/// nearest flag the help documents when one is close.
///
/// The message may span two lines: the report, then the suggestion, which
/// [`main`] prints above its own `Try 'fcage --help'`. Nothing is offered when
/// nothing is close, so a string that resembles no flag is reported plainly
/// rather than answered with an arbitrary one.
fn unrecognized_option(arg: &OsStr) -> String {
    let given = arg.to_string_lossy();
    // A `--flag=value` argument names its flag before the `=`; matching the
    // whole of it would weigh a value against a roster of flags and find
    // nothing near.
    let name = flag_name(&given);
    // A flag of another mode is not a misspelling. Suggesting it would offer
    // the spelling just refused; naming the mode that accepts it will not.
    if let Some(owner) = export_only_owner(name) {
        return format!(
            "unrecognized option {given}\n{name} is an option of {owner}, which is a mode of \
             its own.",
        );
    }
    // The candidates are the table itself. They used to be scraped out of the
    // rendered help, which is now rendered from the table -- so the roster and
    // the vocabulary are one list rather than two that have to agree.
    let candidates: Vec<&str> = FLAGS
        .iter()
        .map(|flag| flag.long)
        .filter(|flag| export_only_owner(flag).is_none())
        .collect();
    match nearest_flag(name, &candidates) {
        Some(flag) => format!("unrecognized option {given}\nTry 'fcage {flag}'."),
        None => format!("unrecognized option {given}"),
    }
}

/// The flag an argument names: everything before a `=`, so the joined and
/// separated spellings of one option compare alike.
fn flag_name(arg: &str) -> &str {
    arg.split_once('=').map_or(arg, |(name, _)| name)
}

/// The mode flag that owns `flag`, when `flag` belongs to a mode of its own
/// rather than to a launch.
///
/// A flag of another mode is not a misspelling, so the suggester never offers
/// one; naming the flag that selects the owning mode is the useful answer.
fn export_only_owner(flag: &str) -> Option<&'static str> {
    let entry = FLAGS.iter().find(|entry| entry.long == flag)?;
    // A flag that *selects* its mode is not an option of another mode: it is
    // the mode, and typing it is how a caller asks for one. Only a flag that
    // belongs to a mode without selecting it -- `--export-to` -- is the case
    // this answers.
    if entry.mode == Mode::Launch || entry.selects {
        return None;
    }
    FLAGS
        .iter()
        .find(|other| other.selects && other.mode == entry.mode)
        .map(|other| other.long)
}

/// The usage error for an argument a mode's parser does not accept.
///
/// A mode takes only its own options, so an unexpected one is usually a launch
/// flag given to the wrong invocation — reported as the conflict it is. A near
/// miss of one of the mode's own flags is a misspelling instead, and is answered
/// like any other: the launch parser's suggestion machinery, over this mode's
/// vocabulary.
fn mode_conflict(arg: &OsStr, mode: &str, vocabulary: &[&'static str]) -> String {
    let given = arg.to_string_lossy();
    match nearest_flag(flag_name(&given), vocabulary) {
        Some(flag) => format!("unrecognized option {given}\nTry 'fcage {flag}'."),
        None => format!("{given} cannot be used with {mode}"),
    }
}

/// The documented flag nearest `given`, or `None` when none is near enough to
/// be worth offering.
///
/// A candidate qualifies on a small edit distance or on a prefix relationship.
/// The prefix rule carries the cases the distance bound misses on a long name:
/// a flag typed short, and one typed with something appended. Ties break on the
/// flag's own spelling, so the suggestion for a given input never depends on
/// the order the help happens to list its options in.
fn nearest_flag<'a>(given: &str, flags: &[&'a str]) -> Option<&'a str> {
    /// Two edits is a transposition, a doubled letter, or a wrong one — the
    /// typos worth guessing at. Beyond it a suggestion is noise.
    const FURTHEST: usize = 2;

    // A run of dashes with nothing after it is every flag's prefix and names
    // none of them. The prefix rule below is about a flag typed short, and this
    // is not one typed at all: without this a mode parser meeting a bare `--`
    // answers it with whichever flag happens to sort first.
    if given.trim_start_matches('-').is_empty() {
        return None;
    }

    flags
        .iter()
        .filter_map(|flag| {
            let distance = edit_distance(given, flag);
            // An abbreviation of a flag outranks any small distance: `--net`
            // names `--netstack`, and answering it with the two-edit `--dev`
            // is worse than useless. A flag typed with something appended is
            // the weaker signal — `--seccomp-alow` extends `--seccomp` and
            // misspells `--seccomp-allow` — so it merely qualifies a
            // candidate, leaving the distance to choose.
            let abbreviates = flag.starts_with(given);
            let extends = given.starts_with(flag);
            (abbreviates || extends || distance <= FURTHEST).then_some((
                usize::from(!abbreviates),
                distance,
                *flag,
            ))
        })
        .min()
        .map(|(_, _, flag)| flag)
}

/// The Levenshtein distance between two strings: the fewest single-character
/// insertions, deletions, and substitutions that turn one into the other.
///
/// Two rows rather than the full matrix, since only the previous one is ever
/// read. Both inputs are short — a flag and something someone typed instead of
/// one — so this runs once, against a couple of hundred candidates, on a path
/// that is about to exit.
fn edit_distance(left: &str, right: &str) -> usize {
    let right: Vec<char> = right.chars().collect();
    // Row zero: turning an empty prefix of `left` into each prefix of `right`
    // costs one insertion per character.
    let mut previous: Vec<usize> = (0..=right.len()).collect();
    let mut current = vec![0; right.len() + 1];
    for (row, from) in left.chars().enumerate() {
        current[0] = row + 1;
        for (column, to) in right.iter().enumerate() {
            let substitute = previous[column] + usize::from(from != *to);
            let delete = previous[column + 1] + 1;
            let insert = current[column] + 1;
            current[column + 1] = substitute.min(delete).min(insert);
        }
        std::mem::swap(&mut previous, &mut current);
    }
    previous[right.len()]
}

/// Renders `items` as a comma-separated list, wrapped to the option-help
/// column and indented to it.
fn wrapped(items: &[&str]) -> String {
    /// The column option descriptions start in, and the width they wrap at.
    const INDENT: usize = 24;
    const WIDTH: usize = 78;

    let mut lines = vec![String::new()];
    for (position, item) in items.iter().enumerate() {
        let separator = if position + 1 == items.len() { "" } else { "," };
        let line = lines.last_mut().expect("the first line is always present");
        if !line.is_empty() && INDENT + line.len() + 1 + item.len() + separator.len() > WIDTH {
            lines.push(String::new());
        }
        let line = lines.last_mut().expect("a line was just ensured");
        if !line.is_empty() {
            line.push(' ');
        }
        line.push_str(item);
        line.push_str(separator);
    }
    lines
        .iter()
        .map(|line| format!("{:INDENT$}{line}", ""))
        .collect::<Vec<_>>()
        .join("\n")
}

/// The mode an invocation selects, and where the command begins.
///
/// A mode flag chooses the invocation, so it has to be found before the launch
/// vocabulary is parsed. What "before" means is the whole of this function: an
/// argument past the command belongs to the command, so a tool with an
/// `--export-rootfs` flag of its own must still be runnable inside a sandbox.
///
/// The command begins at `--`, or at the first argument that is neither an
/// option nor the value of one. Deciding the second half is why every flag is
/// in [`FLAGS`] whether a launch takes it or not: without each flag's arity
/// this walk would read `--export-to /tmp/out` as the command `/tmp/out` and
/// stop, or read a launch's command as a flag and go on.
fn selected_mode(args: &[OsString]) -> Option<Mode> {
    let mut selected = None;
    let mut rest = args.iter();
    while let Some(arg) = rest.next() {
        if arg == "--" {
            break;
        }
        let Some(flag) = named(arg) else {
            if arg.as_bytes().starts_with(b"-") && arg != "-" {
                // An option this does not know: not a mode, and the launch
                // parser is where it is reported.
                continue;
            }
            // The command.
            break;
        };
        if flag.selects && selected.is_none() {
            selected = Some(flag.mode);
        }
        // A separated value is the flag's, not the command.
        if flag.arity() != Arity::Bare && !joined(arg) {
            let count = if flag.arity() == Arity::Two { 2 } else { 1 };
            for _ in 0..count {
                if rest.next().is_none() {
                    break;
                }
            }
        }
    }
    selected
}

/// Whether `arg` is a flag written with its value joined on.
fn joined(arg: &OsStr) -> bool {
    arg.as_bytes().contains(&b'=')
}

/// The flag `arg` names, whether it is written joined or separated.
///
/// A joined value is only split off for a flag that takes one value: `--bind=A`
/// would leave the pair's second half on the wrong side of the `=`, and
/// `--no-proc=1` names a flag that takes nothing. Both stay unrecognized, which
/// is what they were.
fn named(arg: &OsStr) -> Option<&'static Flag> {
    let text = arg.to_str()?;
    if let Some(flag) = FLAGS.iter().find(|flag| flag.long == text) {
        return Some(flag);
    }
    let (name, _) = text.split_once('=')?;
    FLAGS
        .iter()
        .find(|flag| flag.long == name && flag.arity() == Arity::One)
}

/// Applies one flag to the options a launch is being built from.
///
/// `joined` is the value written after an `=`, where it was; the lookup only
/// splits one off for a flag that takes exactly one value.
fn apply_flag(
    flag: &Flag,
    options: &mut Options,
    joined: Option<OsString>,
    args: &mut dyn Iterator<Item = OsString>,
) -> Result<(), String> {
    match flag.take {
        Take::Bare(set) => {
            set(options);
            Ok(())
        }
        Take::One(set) => {
            let value = match joined {
                Some(value) => value,
                None => value_for(flag.long, flag.needs, args)?,
            };
            set(options, flag.long, value)
        }
        Take::Two(set) => {
            let first = value_for(flag.long, flag.needs, args)?;
            let second = value_for(flag.long, flag.needs, args)?;
            set(options, flag.long, first, second)
        }
        // A flag of another mode, written before the command of a launch. The
        // pre-scan routed nothing here, so it is one that belongs to a mode
        // without selecting it -- and the message names the mode rather than
        // suggesting the spelling that was just refused.
        Take::Refused(_) => Err(unrecognized_option(OsStr::new(flag.long))),
    }
}

fn main() -> ExitCode {
    match parse(std::env::args_os().skip(1)) {
        Ok(Invocation::Help) => {
            print!("{}", usage());
            ExitCode::SUCCESS
        }
        Ok(Invocation::Version) => {
            println!("fcage {}", env!("CARGO_PKG_VERSION"));
            ExitCode::SUCCESS
        }
        Ok(Invocation::Run(options)) => run(*options),
        Ok(Invocation::Remove { dest, map }) => remove_rootfs(&dest, map),
        Ok(Invocation::GentooVariants {
            architecture,
            mirror,
            fallbacks,
            max_pointer_age,
        }) => gentoo_variants(
            &architecture,
            mirror.as_deref(),
            &fallbacks,
            max_pointer_age,
        ),
        Ok(Invocation::GentooPackages {
            architecture,
            binhost,
            mirror,
            fallbacks,
        }) => gentoo_packages(
            &architecture,
            binhost.as_deref(),
            mirror.as_deref(),
            &fallbacks,
        ),
        Ok(Invocation::GentooInstalled { root }) => gentoo_installed(&root),
        Ok(Invocation::GentooKeyring) => gentoo_keyring_horizon(),
        Ok(Invocation::Export {
            source,
            dest,
            map,
            clamp_mtime,
        }) => export_rootfs(&source, dest.as_deref(), map, clamp_mtime),
        Err(message) => {
            eprintln!("fcage: {message}");
            eprintln!("Try 'fcage --help' for usage.");
            ExitCode::from(2)
        }
    }
}

/// Parses the command line, excluding the program name.
fn parse(args: impl Iterator<Item = OsString>) -> Result<Invocation, String> {
    let args: Vec<OsString> = args.collect();
    // A mode is a program of its own behind the same name, so it is recognized
    // before the launch vocabulary is parsed and its parser accepts only its
    // own flags. Splitting it this way is what keeps the two in step: a flag
    // added to a launch is refused alongside --remove-rootfs by the same `else`
    // that refuses every other one, rather than being silently accepted and
    // then ignored by a removal that never reads it.
    match selected_mode(&args) {
        Some(Mode::GentooVariants) => return parse_gentoo_variants(args),
        Some(Mode::GentooPackages) => return parse_gentoo_packages(args),
        Some(Mode::GentooInstalled) => return parse_gentoo_installed(args),
        Some(Mode::GentooKeyring) => return parse_gentoo_keyring(args),
        Some(Mode::Remove) => return parse_removal(args),
        Some(Mode::Export) => return parse_export(args),
        _ => {}
    }
    // Kept for the no-effect check at the end, which asks what was written
    // rather than what it parsed to.
    let raw = args.clone();
    let mut args = args.into_iter();

    let mut options = Options {
        profile: None,
        profile_restricted: false,
        rootfs: None,
        provision_tar: None,
        provision_debian: None,
        debian_arch: None,
        debian_mirror: None,
        debian_components: Vec::new(),
        debian_include: Vec::new(),
        debian_exclude: Vec::new(),
        debian_plan: None,
        debian_pin: None,
        debian_extract_only: false,
        debian_cache: None,
        debian_keyring: None,
        debian_mirror_fallback: Vec::new(),
        debian_base_priority: None,
        debian_trust_unsigned: false,
        debian_allow_stale_release: false,
        debian_pre_configure_overlay: None,
        debian_identity_map: None,
        debian_repositories: Vec::new(),
        provision_alpine: None,
        alpine_arch: None,
        alpine_mirror: None,
        alpine_components: Vec::new(),
        alpine_include: Vec::new(),
        alpine_exclude: Vec::new(),
        alpine_plan: None,
        alpine_pin: None,
        alpine_extract_only: false,
        alpine_cache: None,
        alpine_keys: None,
        alpine_mirror_fallback: Vec::new(),
        provision_gentoo: None,
        gentoo_variant: None,
        gentoo_binhost: None,
        gentoo_install: Vec::new(),
        gentoo_prefer_use: Vec::new(),
        gentoo_plan: None,
        gentoo_build_id: None,
        gentoo_mirror: None,
        gentoo_mirror_fallback: Vec::new(),
        gentoo_cache: None,
        gentoo_max_pointer_age: None,
        alpine_pre_configure_overlay: None,
        alpine_identity_map: None,
        alpine_repositories: Vec::new(),
        command_line: Vec::new(),
        path_lookup: None,
        mounts: Vec::new(),
        overlay_lowers: Vec::new(),
        overlay_upper: None,
        overlay_work: None,
        identity_map: None,
        run_as: None,
        rlimits: Vec::new(),
        setenv: Vec::new(),
        hostname: None,
        chdir: None,
        stdin: None,
        terminal: false,
        timeout: None,
        kill_after: Duration::from_secs(10),
        kill_after_given: false,
        network: None,
        pid_namespace: None,
        mount_proc: None,
        mount_dev: None,
        mount_tmp: None,
        resolv_conf: None,
        managed_mounts: None,
        base_env: None,
        // `None` like every other toggle, so a profile's setting survives. The
        // default is applied where the profile is known rather than here: see
        // `stop_with_caller_default`.
        stop_with_caller: None,
        landlock: Vec::new(),
        landlock_net: Vec::new(),
        seccomp: None,
        seccomp_curated: false,
        seccomp_allow: Vec::new(),
        seccomp_deny: Vec::new(),
        seccomp_allow_rules: Vec::new(),
        seccomp_deny_rules: Vec::new(),
        caps: None,
        restrict: false,
        netstack: false,
        netstack_cidr: None,
        netstack_cidr6: None,
        netstack_no_ipv4: false,
        netstack_no_ipv6: false,
        netstack_interface: None,
        netstack_mtu: None,
        netstack_host_loopback: false,
    };

    while let Some(arg) = args.next() {
        if arg == "-h" || arg == "--help" {
            return Ok(Invocation::Help);
        }
        if arg == "-V" || arg == "--version" {
            return Ok(Invocation::Version);
        }
        if arg == "--" {
            options.command_line.extend(args);
            break;
        }
        if let Some(flag) = named(&arg) {
            // The joined form's value, where the argument carries one. The
            // lookup only matches a joined argument against a flag that takes
            // exactly one value, so this is `Some` for those and nothing else.
            let joined = flag_value(&arg, format!("{}=", flag.long).as_bytes());
            apply_flag(flag, &mut options, joined, &mut args)?;
            continue;
        }
        if arg.as_bytes().starts_with(b"-") && arg != "-" {
            return Err(unrecognized_option(&arg));
        }
        // The first positional argument is the command; everything after it
        // belongs to the command, dashes included.
        options.command_line.push(arg);
        options.command_line.extend(args);
        break;
    }

    // Reconciled after the loop: the curated posture and the allow and deny
    // sides are mutually constrained, and the flag that decides can come last.
    options.seccomp = assemble_seccomp(
        options.seccomp_curated,
        std::mem::take(&mut options.seccomp_allow),
        std::mem::take(&mut options.seccomp_deny),
        std::mem::take(&mut options.seccomp_allow_rules),
        std::mem::take(&mut options.seccomp_deny_rules),
    )?;

    // --kill-after is the grace period before the SIGKILL that follows a
    // --timeout; without a timeout it has nothing to hang on and would be
    // silently ignored.
    if options.kill_after_given && options.timeout.is_none() {
        return Err("--kill-after requires --timeout".to_string());
    }

    // A terminal is all three of the command's standard streams, so a stated
    // disposition for any of them means two different things were asked for.
    // The library refuses the same combination at the launch; naming it here
    // makes it the usage error it is, and names both flags.
    if options.terminal && matches!(options.stdin, Some(Stdio::Null)) {
        return Err("--terminal cannot be used with --stdin null".to_string());
    }

    if options.restrict {
        // A restriction knows nothing of a rootfs or namespaces; every flag
        // that configures one is a contradiction, named explicitly.
        let conflicts = [
            (options.rootfs.is_some(), "--rootfs"),
            (
                options.profile.is_some(),
                "--profile or --restricted-profile",
            ),
            (options.provision_tar.is_some(), "--provision-tar"),
            (options.provision_debian.is_some(), "--provision-debian"),
            (has_debian_modifiers(&options), "the --debian-* options"),
            (options.provision_alpine.is_some(), "--provision-alpine"),
            (has_alpine_modifiers(&options), "the --alpine-* options"),
            (options.provision_gentoo.is_some(), "--provision-gentoo"),
            (has_gentoo_modifiers(&options), "the --gentoo-* options"),
            (
                options
                    .mounts
                    .iter()
                    .any(|mount| matches!(mount, Mount::Bind(_))),
                "--bind and --ro-bind",
            ),
            (options.hostname.is_some(), "--hostname"),
            (options.network.is_some(), "the network options"),
            (options.pid_namespace.is_some(), "the PID-namespace options"),
            (
                options.mount_proc.is_some()
                    || options.mount_dev.is_some()
                    || options.mount_tmp.is_some()
                    || options.managed_mounts.is_some(),
                "the mount toggles",
            ),
            (options.resolv_conf.is_some(), "the resolv.conf options"),
            (options.caps.is_some(), "the capability options"),
            (
                options
                    .mounts
                    .iter()
                    .any(|mount| matches!(mount, Mount::Raw(_))),
                "--raw-mount",
            ),
            (
                !options.overlay_lowers.is_empty()
                    || options.overlay_upper.is_some()
                    || options.overlay_work.is_some(),
                "the --overlay-* options",
            ),
            (options.identity_map.is_some(), "--identity-map"),
            (options.run_as.is_some(), "--run-as"),
            (options.path_lookup.is_some(), "the path-lookup options"),
            (options.netstack, "--netstack"),
            (has_netstack_modifiers(&options), "the --netstack-* options"),
        ];
        for (given, name) in conflicts {
            if given {
                return Err(format!("{name} cannot be used with --restrict"));
            }
        }
        if options.command_line.is_empty() {
            return Err("no command given".to_string());
        }
        // A restriction with nothing to enforce would run a plain host process
        // while appearing to sandbox it. The library rejects that too, but as a
        // launch error; catching it here makes it the usage error it is.
        if options.landlock.is_empty()
            && options.landlock_net.is_empty()
            && options.seccomp.is_none()
        {
            return Err(
                "--restrict requires at least one grant: a --landlock-* rule or a --seccomp filter"
                    .to_string(),
            );
        }
        return Ok(Invocation::Run(Box::new(options)));
    }

    // The native stack configures the isolated network; sharing the host
    // network is the opposite request, and the stack's sub-flags mean
    // nothing without it.
    if options.netstack && options.network == Some(Network::Host) {
        return Err("--netstack cannot be used with --share-net".to_string());
    }
    if !options.netstack && has_netstack_modifiers(&options) {
        return Err("the --netstack-* options require --netstack".to_string());
    }

    // An overlay root and a plain rootfs are alternatives; the last builder
    // call would silently win, so name the contradiction here instead.
    let overlay_given = !options.overlay_lowers.is_empty()
        || options.overlay_upper.is_some()
        || options.overlay_work.is_some();
    if overlay_given {
        if options.overlay_lowers.is_empty() {
            return Err("the --overlay-* options require at least one --overlay-lower".to_string());
        }
        if options.overlay_upper.is_none() {
            return Err("the --overlay-* options require --overlay-upper".to_string());
        }
        if options.rootfs.is_some() {
            return Err("--rootfs and the --overlay-* options are alternatives".to_string());
        }
    }
    if options.rootfs.is_none() && options.profile.is_none() && !overlay_given {
        return Err(
            "--rootfs, --overlay-lower, --profile, --restricted-profile, or --restrict is required"
                .to_string(),
        );
    }
    // One rootfs is provisioned one way, and by something that was told where
    // to put it. Both refusals name the flag rather than reporting "a
    // provisioner", so the two are enumerated once here.
    let provisioners: Vec<&str> = [
        (options.provision_tar.is_some(), "--provision-tar"),
        (options.provision_debian.is_some(), "--provision-debian"),
        (options.provision_alpine.is_some(), "--provision-alpine"),
        (options.provision_gentoo.is_some(), "--provision-gentoo"),
    ]
    .into_iter()
    .filter_map(|(given, flag)| given.then_some(flag))
    .collect();
    if let [first, second, ..] = provisioners[..] {
        return Err(format!("{first} and {second} are mutually exclusive"));
    }
    if let [only] = provisioners[..]
        && options.rootfs.is_none()
    {
        return Err(format!("{only} requires --rootfs to name the destination"));
    }
    if options.provision_debian.is_none() && has_debian_modifiers(&options) {
        return Err("the --debian-* options require --provision-debian".to_string());
    }
    if options.provision_alpine.is_none() && has_alpine_modifiers(&options) {
        return Err("the --alpine-* options require --provision-alpine".to_string());
    }
    if options.provision_gentoo.is_none() && has_gentoo_modifiers(&options) {
        return Err("the --gentoo-* options require --provision-gentoo".to_string());
    }
    // A variant is what a bootstrap installs, and the archive publishes dozens
    // per architecture with no default among them. Refusing here rather than
    // letting the library refuse after two fetches is what makes the message
    // "name one" instead of "the resolution failed".
    if options.provision_gentoo.is_some()
        && options.gentoo_variant.is_none()
        && options.rootfs.is_some()
    {
        return Err(
            "--provision-gentoo requires --gentoo-variant; --gentoo-variants lists what an \
             architecture offers"
                .to_string(),
        );
    }
    // A provisioning run without a command provisions and exits; otherwise a
    // command (or a profile that names one) is required.
    let provisioning = options.provision_tar.is_some()
        || options.provision_debian.is_some()
        || options.provision_alpine.is_some()
        || options.provision_gentoo.is_some();
    if options.command_line.is_empty() && options.profile.is_none() && !provisioning {
        return Err("no command given".to_string());
    }
    // Nothing is launched, so a flag that configures a launch has nothing to
    // configure. Every other no-effect combination is refused above, and
    // silently dropping this one leaves a caller believing a sandbox was shaped
    // the way the command line said.
    if options.command_line.is_empty()
        && options.profile.is_none()
        && let Some(flag) = first_launch_flag(&raw)
    {
        return Err(format!(
            "{flag} configures a launch, and a provisioning run without a command does not \
             launch one",
        ));
    }
    Ok(Invocation::Run(Box::new(options)))
}

/// The first argument of a provision-and-exit invocation that configures the
/// launch rather than the provisioning, if any.
///
/// A provision-and-exit run names no command, so nothing in the vector is a
/// positional and every `--` argument is one of fcage's own. The provisioning
/// vocabulary is short enough to name; everything else shapes a sandbox that is
/// never built.
///
/// The bare `--` separator is not a flag and is skipped: it introduces a command
/// line rather than configuring one, and a run that ends on it — `--rootfs /r
/// --provision-debian trixie --` — names no launch setting at all. Reading it as
/// a flag would refuse such a run for something it did not do.
fn first_launch_flag(args: &[OsString]) -> Option<String> {
    args.iter()
        .map(|arg| arg.to_string_lossy().into_owned())
        .find(|arg| arg != "--" && arg.starts_with("--") && !provisions(flag_name(arg)))
}

/// Whether `flag` configures the provisioning rather than the launch.
fn provisions(flag: &str) -> bool {
    matches!(
        flag,
        "--rootfs"
            | "--provision-tar"
            | "--provision-debian"
            | "--provision-alpine"
            | "--provision-gentoo"
    ) || flag.starts_with("--debian-")
        || flag.starts_with("--alpine-")
        || flag.starts_with("--gentoo-")
}

/// Records the profile to load, refusing a mix of the two trust models.
///
/// Repeating one flag takes the last value, as repeating any other value option
/// does. Naming both is refused instead: the two load a file under different
/// trust, and there is no sensible way to choose between them.
fn set_profile(options: &mut Options, path: PathBuf, restricted: bool) -> Result<(), String> {
    if options.profile.is_some() && options.profile_restricted != restricted {
        return Err("--profile and --restricted-profile are alternatives".to_string());
    }
    options.profile = Some(path);
    options.profile_restricted = restricted;
    Ok(())
}

/// The help or version request `args` carries, wherever it appears.
///
/// A mode takes no positional argument, so nothing in one can legitimately be
/// the word `--help`. Answering it up front is what stops the destination arm
/// from consuming it: `fcage --remove-rootfs --help` would otherwise take it as
/// the tree to delete.
fn help_or_version(args: &[OsString]) -> Option<Invocation> {
    if args.iter().any(|arg| arg == "-h" || arg == "--help") {
        return Some(Invocation::Help);
    }
    if args.iter().any(|arg| arg == "-V" || arg == "--version") {
        return Some(Invocation::Version);
    }
    None
}

/// Parses a `--remove-rootfs` command line, excluding the program name.
///
/// A removal takes the destination and the identity map the tree was written
/// under. Every other flag configures a launch that does not happen here, so
/// naming one is a usage error rather than a setting with no effect.
fn parse_removal(args: Vec<OsString>) -> Result<Invocation, String> {
    if let Some(answer) = help_or_version(&args) {
        return Ok(answer);
    }
    let mut dest: Option<PathBuf> = None;
    // The same default the library's own removal carries: a tree written by a
    // bundled-delegate sandbox is the case that needs the escalation at all.
    let mut map = IdentityMap::Subordinate;
    let mut args = args.into_iter();

    while let Some(arg) = args.next() {
        if arg == "--remove-rootfs" {
            dest = Some(PathBuf::from(value_for(
                "--remove-rootfs",
                "a value",
                &mut args,
            )?));
        } else if let Some(value) = flag_value(&arg, b"--remove-rootfs=") {
            dest = Some(PathBuf::from(value));
        } else if arg == "--identity-map" {
            map = parse_identity_map(
                "--identity-map",
                &string_value("--identity-map", &mut args)?,
            )?;
        } else if let Some(value) = flag_value(&arg, b"--identity-map=") {
            map = parse_identity_map("--identity-map", &into_string("--identity-map", value)?)?;
        } else {
            return Err(mode_conflict(
                &arg,
                "--remove-rootfs",
                &["--remove-rootfs", "--identity-map"],
            ));
        }
    }

    // The caller established that the flag is present, so this is a guard
    // rather than a live path: the only value-taking flag here would reject
    // `--remove-rootfs` as a map spelling before reaching it. It stays a usage
    // error rather than an `expect` because what upholds it is the shape of the
    // argument vector, not an invariant of this module.
    let dest = dest.ok_or_else(|| "--remove-rootfs requires a value".to_string())?;
    Ok(Invocation::Remove { dest, map })
}

/// Parses a `--gentoo-variants` command line, excluding the program name.
///
/// A listing reads the signed enumeration and prints it, so it takes the
/// architecture, where to read it from, and how old it may be. As with a removal
/// and an export, every other flag configures a launch that does not happen
/// here, and parsing the mode separately is what keeps that true of a flag added
/// to a launch later.
fn parse_gentoo_variants(args: Vec<OsString>) -> Result<Invocation, String> {
    if let Some(answer) = help_or_version(&args) {
        return Ok(answer);
    }
    let mut architecture: Option<String> = None;
    // The primary and its backstops are separate settings here exactly as they
    // are on a provisioning command line: repeating the primary takes the last
    // value, and a backstop given alone backs the default archive rather than
    // replacing it.
    let mut mirror: Option<String> = None;
    let mut fallbacks: Vec<String> = Vec::new();
    let mut max_pointer_age: Option<Option<u64>> = None;
    let mut args = args.into_iter();

    while let Some(arg) = args.next() {
        if arg == "--gentoo-variants" {
            architecture = Some(string_value("--gentoo-variants", &mut args)?);
        } else if let Some(value) = flag_value(&arg, b"--gentoo-variants=") {
            architecture = Some(into_string("--gentoo-variants", value)?);
        } else if arg == "--gentoo-mirror" {
            mirror = Some(string_value("--gentoo-mirror", &mut args)?);
        } else if let Some(value) = flag_value(&arg, b"--gentoo-mirror=") {
            mirror = Some(into_string("--gentoo-mirror", value)?);
        } else if arg == "--gentoo-mirror-fallback" {
            fallbacks.push(string_value("--gentoo-mirror-fallback", &mut args)?);
        } else if let Some(value) = flag_value(&arg, b"--gentoo-mirror-fallback=") {
            fallbacks.push(into_string("--gentoo-mirror-fallback", value)?);
        } else if arg == "--gentoo-max-pointer-age" {
            max_pointer_age = Some(parse_pointer_age(&string_value(
                "--gentoo-max-pointer-age",
                &mut args,
            )?)?);
        } else if let Some(value) = flag_value(&arg, b"--gentoo-max-pointer-age=") {
            max_pointer_age = Some(parse_pointer_age(&into_string(
                "--gentoo-max-pointer-age",
                value,
            )?)?);
        } else {
            return Err(mode_conflict(
                &arg,
                "--gentoo-variants",
                &[
                    "--gentoo-variants",
                    "--gentoo-mirror",
                    "--gentoo-mirror-fallback",
                    "--gentoo-max-pointer-age",
                ],
            ));
        }
    }

    // As for a removal, the caller established that the flag is present, so
    // this is a guard rather than a live path.
    let architecture =
        architecture.ok_or_else(|| "--gentoo-variants requires a value".to_string())?;
    Ok(Invocation::GentooVariants {
        architecture,
        mirror,
        fallbacks,
        max_pointer_age,
    })
}

/// Parses a `--gentoo-keyring-horizon` command line, excluding the program name.
///
/// It reads the keyring the crate vendors and nothing else, so it takes no
/// settings at all: there is no mirror to name and no network to reach.
fn parse_gentoo_keyring(args: Vec<OsString>) -> Result<Invocation, String> {
    if let Some(answer) = help_or_version(&args) {
        return Ok(answer);
    }
    for arg in args {
        if arg != "--gentoo-keyring-horizon" {
            return Err(mode_conflict(
                &arg,
                "--gentoo-keyring-horizon",
                &["--gentoo-keyring-horizon"],
            ));
        }
    }
    Ok(Invocation::GentooKeyring)
}

/// Parses a `--gentoo-packages` command line, excluding the program name.
///
/// A listing reads the binhost index and prints it, so it takes the
/// architecture, the sub-architecture tree, and where to read them from. As
/// with the other listing modes, every other flag configures a launch that does
/// not happen here.
fn parse_gentoo_packages(args: Vec<OsString>) -> Result<Invocation, String> {
    if let Some(answer) = help_or_version(&args) {
        return Ok(answer);
    }
    let mut architecture: Option<String> = None;
    let mut binhost: Option<String> = None;
    let mut mirror: Option<String> = None;
    let mut fallbacks: Vec<String> = Vec::new();
    let mut args = args.into_iter();

    while let Some(arg) = args.next() {
        if arg == "--gentoo-packages" {
            architecture = Some(string_value("--gentoo-packages", &mut args)?);
        } else if let Some(value) = flag_value(&arg, b"--gentoo-packages=") {
            architecture = Some(into_string("--gentoo-packages", value)?);
        } else if arg == "--gentoo-binhost" {
            binhost = Some(string_value("--gentoo-binhost", &mut args)?);
        } else if let Some(value) = flag_value(&arg, b"--gentoo-binhost=") {
            binhost = Some(into_string("--gentoo-binhost", value)?);
        } else if arg == "--gentoo-mirror" {
            mirror = Some(string_value("--gentoo-mirror", &mut args)?);
        } else if let Some(value) = flag_value(&arg, b"--gentoo-mirror=") {
            mirror = Some(into_string("--gentoo-mirror", value)?);
        } else if arg == "--gentoo-mirror-fallback" {
            fallbacks.push(string_value("--gentoo-mirror-fallback", &mut args)?);
        } else if let Some(value) = flag_value(&arg, b"--gentoo-mirror-fallback=") {
            fallbacks.push(into_string("--gentoo-mirror-fallback", value)?);
        } else {
            return Err(mode_conflict(
                &arg,
                "--gentoo-packages",
                &[
                    "--gentoo-packages",
                    "--gentoo-binhost",
                    "--gentoo-mirror",
                    "--gentoo-mirror-fallback",
                ],
            ));
        }
    }
    match architecture {
        Some(architecture) => Ok(Invocation::GentooPackages {
            architecture,
            binhost,
            mirror,
            fallbacks,
        }),
        None => Err("--gentoo-packages requires a value".to_string()),
    }
}

/// Parses a `--gentoo-installed` command line, excluding the program name.
///
/// It reads a root's own package database and reaches nothing else, so it takes
/// a path and no other flag.
fn parse_gentoo_installed(args: Vec<OsString>) -> Result<Invocation, String> {
    if let Some(answer) = help_or_version(&args) {
        return Ok(answer);
    }
    let mut root: Option<PathBuf> = None;
    let mut args = args.into_iter();
    while let Some(arg) = args.next() {
        if arg == "--gentoo-installed" {
            root = Some(PathBuf::from(value_for(
                "--gentoo-installed",
                "a value",
                &mut args,
            )?));
        } else if let Some(value) = flag_value(&arg, b"--gentoo-installed=") {
            root = Some(PathBuf::from(value));
        } else {
            return Err(mode_conflict(
                &arg,
                "--gentoo-installed",
                &["--gentoo-installed"],
            ));
        }
    }
    match root {
        Some(root) => Ok(Invocation::GentooInstalled { root }),
        None => Err("--gentoo-installed requires a value".to_string()),
    }
}

/// Parses an `--export-rootfs` command line, excluding the program name.
///
/// An export takes the tree to read, where to write it, the identity map the
/// tree was written under, and the modification-time ceiling. As with a
/// removal, every other flag configures a launch that does not happen here, so
/// naming one is a usage error rather than a setting with no effect — and
/// parsing the mode separately is what keeps that true of a flag added to a
/// launch later, since the vocabulary is closed by exhaustion rather than by a
/// list kept in step by hand.
fn parse_export(args: Vec<OsString>) -> Result<Invocation, String> {
    if let Some(answer) = help_or_version(&args) {
        return Ok(answer);
    }
    let mut source: Option<PathBuf> = None;
    let mut dest: Option<PathBuf> = None;
    // The map a bundled-delegate sandbox writes under, as removal defaults to.
    let mut map = IdentityMap::Subordinate;
    let mut clamp_mtime: Option<i64> = None;
    let mut args = args.into_iter();

    while let Some(arg) = args.next() {
        if arg == "--export-rootfs" {
            let value = args
                .next()
                .ok_or_else(|| "--export-rootfs requires a value".to_string())?;
            source = Some(PathBuf::from(value));
        } else if let Some(value) = flag_value(&arg, b"--export-rootfs=") {
            source = Some(PathBuf::from(value));
        } else if arg == "--export-to" {
            let value = args
                .next()
                .ok_or_else(|| "--export-to requires a value".to_string())?;
            dest = Some(PathBuf::from(value));
        } else if let Some(value) = flag_value(&arg, b"--export-to=") {
            dest = Some(PathBuf::from(value));
        } else if arg == "--identity-map" {
            map = parse_identity_map(
                "--identity-map",
                &string_value("--identity-map", &mut args)?,
            )?;
        } else if let Some(value) = flag_value(&arg, b"--identity-map=") {
            map = parse_identity_map("--identity-map", &into_string("--identity-map", value)?)?;
        } else if arg == "--clamp-mtime" {
            clamp_mtime = Some(parse_epoch(&string_value("--clamp-mtime", &mut args)?)?);
        } else if let Some(value) = flag_value(&arg, b"--clamp-mtime=") {
            clamp_mtime = Some(parse_epoch(&into_string("--clamp-mtime", value)?)?);
        } else {
            return Err(mode_conflict(
                &arg,
                "--export-rootfs",
                &[
                    "--export-rootfs",
                    "--export-to",
                    "--identity-map",
                    "--clamp-mtime",
                ],
            ));
        }
    }

    // As for a removal, the caller established that the flag is present, so
    // this is a guard rather than a live path.
    let source = source.ok_or_else(|| "--export-rootfs requires a value".to_string())?;
    Ok(Invocation::Export {
        source,
        dest,
        map,
        clamp_mtime,
    })
}

/// Parses the `--clamp-mtime` ceiling: a Unix timestamp in seconds.
///
/// Signed, because the ceiling is a plain timestamp rather than a duration and
/// a tree may legitimately be pinned to an instant before the epoch.
fn parse_epoch(value: &str) -> Result<i64, String> {
    value
        .parse::<i64>()
        .map_err(|_| format!("--clamp-mtime: {value:?} is not a Unix timestamp in whole seconds"))
}

/// Whether any `--debian-*` modifier flag was given.
fn has_debian_modifiers(options: &Options) -> bool {
    options.debian_arch.is_some()
        || options.debian_mirror.is_some()
        || !options.debian_components.is_empty()
        || !options.debian_include.is_empty()
        || !options.debian_exclude.is_empty()
        || options.debian_plan.is_some()
        || options.debian_pin.is_some()
        || options.debian_extract_only
        || options.debian_cache.is_some()
        || options.debian_keyring.is_some()
        || !options.debian_mirror_fallback.is_empty()
        || options.debian_base_priority.is_some()
        || options.debian_trust_unsigned
        || options.debian_allow_stale_release
        || options.debian_pre_configure_overlay.is_some()
        || options.debian_identity_map.is_some()
        || !options.debian_repositories.is_empty()
}

/// Whether any `--alpine-*` modifier flag was given.
fn has_alpine_modifiers(options: &Options) -> bool {
    options.alpine_arch.is_some()
        || options.alpine_mirror.is_some()
        || !options.alpine_components.is_empty()
        || !options.alpine_include.is_empty()
        || !options.alpine_exclude.is_empty()
        || options.alpine_plan.is_some()
        || options.alpine_pin.is_some()
        || options.alpine_extract_only
        || options.alpine_cache.is_some()
        || options.alpine_keys.is_some()
        || !options.alpine_mirror_fallback.is_empty()
        || options.alpine_pre_configure_overlay.is_some()
        || options.alpine_identity_map.is_some()
        || !options.alpine_repositories.is_empty()
}

/// Whether any `--gentoo-*` modifier flag was given.
fn has_gentoo_modifiers(options: &Options) -> bool {
    options.gentoo_variant.is_some()
        || options.gentoo_binhost.is_some()
        || !options.gentoo_install.is_empty()
        || !options.gentoo_prefer_use.is_empty()
        || options.gentoo_plan.is_some()
        || options.gentoo_build_id.is_some()
        || options.gentoo_mirror.is_some()
        || !options.gentoo_mirror_fallback.is_empty()
        || options.gentoo_cache.is_some()
        || options.gentoo_max_pointer_age.is_some()
}

/// Parses `--gentoo-max-pointer-age`: a count of days, or `none` for no bound.
fn parse_pointer_age(value: &str) -> Result<Option<u64>, String> {
    if value == "none" {
        return Ok(None);
    }
    let days: u64 = value.parse().map_err(|_| {
        format!("--gentoo-max-pointer-age expects a number of days or 'none', not {value:?}")
    })?;
    Ok(Some(days))
}

/// Whether any `--netstack-*` modifier flag was given.
fn has_netstack_modifiers(options: &Options) -> bool {
    options.netstack_cidr.is_some()
        || options.netstack_cidr6.is_some()
        || options.netstack_no_ipv4
        || options.netstack_no_ipv6
        || options.netstack_interface.is_some()
        || options.netstack_mtu.is_some()
        || options.netstack_host_loopback
}

/// Parses an IPv4 `address/prefix` for `--netstack-cidr`.
fn parse_cidr(value: &str) -> Result<(Ipv4Addr, u8), String> {
    let (address, len) = value
        .split_once('/')
        .ok_or_else(|| format!("--netstack-cidr expects ADDRESS/LEN, not {value:?}"))?;
    let address = address
        .parse::<Ipv4Addr>()
        .map_err(|_| format!("--netstack-cidr: {address:?} is not an IPv4 address"))?;
    let len = len
        .parse::<u8>()
        .map_err(|_| format!("--netstack-cidr: {len:?} is not a prefix length"))?;
    if len > 32 {
        return Err(format!(
            "--netstack-cidr: {len} is not an IPv4 prefix length (0-32)"
        ));
    }
    Ok((address, len))
}

/// Parses an IPv6 `address/prefix` for `--netstack-cidr6`.
///
/// A second answer to the question above, because the two address families are
/// two types with two parsers and two prefix ceilings, and a shared one would
/// take the family as a parameter only to branch on it throughout. The library
/// splits [`ipv4_cidr`] from [`ipv6_cidr`] the same way.
///
/// [`ipv4_cidr`]: ferroday_cage::NetStackBuilder::ipv4_cidr
/// [`ipv6_cidr`]: ferroday_cage::NetStackBuilder::ipv6_cidr
fn parse_cidr6(value: &str) -> Result<(Ipv6Addr, u8), String> {
    let (address, len) = value
        .split_once('/')
        .ok_or_else(|| format!("--netstack-cidr6 expects ADDRESS/LEN, not {value:?}"))?;
    let address = address
        .parse::<Ipv6Addr>()
        .map_err(|_| format!("--netstack-cidr6: {address:?} is not an IPv6 address"))?;
    let len = len
        .parse::<u8>()
        .map_err(|_| format!("--netstack-cidr6: {len:?} is not a prefix length"))?;
    if len > 128 {
        return Err(format!(
            "--netstack-cidr6: {len} is not an IPv6 prefix length (0-128)"
        ));
    }
    Ok((address, len))
}

/// Parses an interface MTU for `--netstack-mtu`.
fn parse_mtu(value: &str) -> Result<u16, String> {
    value
        .parse::<u16>()
        .map_err(|_| format!("--netstack-mtu: {value:?} is not a valid MTU"))
}

/// Splits a space-separated `key=value` specification into its pairs.
///
/// The shape `--seccomp-allow-rule` already uses, shared by `--raw-mount`,
/// `--debian-repository`, and the range form of `--identity-map`. A bare word
/// with no `=` is a flag, reported with an empty value.
fn spec_pairs<'a>(flag: &str, spec: &'a str) -> Result<Vec<(&'a str, &'a str)>, String> {
    let mut pairs = Vec::new();
    for field in spec.split_whitespace() {
        match field.split_once('=') {
            Some((key, value)) if !key.is_empty() => pairs.push((key, value)),
            Some(_) => return Err(format!("{flag}: {field:?} has an empty key")),
            None => pairs.push((field, "")),
        }
    }
    if pairs.is_empty() {
        return Err(format!("{flag} requires at least one key=value field"));
    }
    Ok(pairs)
}

/// Reads a field whose presence is the whole of its meaning, refusing one
/// written with a value.
///
/// A value cannot be honoured by a field that has no off state, and reading
/// `trust-unsigned=false` as the field being present turns archive signature
/// verification off — the opposite of what it says. Refused rather than
/// interpreted: `trust-unsigned` and `allow-stale-release` are spelled bare,
/// and a caller who wants the setting off leaves the field out.
fn bare_field(flag: &str, key: &str, value: &str) -> Result<bool, String> {
    if value.is_empty() {
        Ok(true)
    } else {
        Err(format!(
            "{flag}: {key} takes no value, and {key}={value} does not turn it off; write {key} on \
             its own, or leave it out"
        ))
    }
}

/// Parses a `--raw-mount` specification:
/// `target=/sys fstype=sysfs flags=0xE [source=...] [data=...]`.
fn parse_raw_mount(spec: &str) -> Result<RawMount, String> {
    let mut target = None;
    let mut source = None;
    let mut fstype = None;
    let mut data = None;
    let mut flags = 0u64;
    for (key, value) in spec_pairs("--raw-mount", spec)? {
        match key {
            "target" => target = Some(PathBuf::from(value)),
            "source" => source = Some(PathBuf::from(value)),
            "fstype" => fstype = Some(value.to_string()),
            "data" => data = Some(value.to_string()),
            "flags" => flags = parse_u64_literal("--raw-mount", "flags", value)?,
            other => {
                return Err(format!(
                    "--raw-mount: unknown field {other:?}; expected target, source, fstype, \
                     flags, or data"
                ));
            }
        }
    }
    let target = target.ok_or("--raw-mount requires a target= field".to_string())?;
    let mut mount = RawMount::new(target).flags(flags);
    if let Some(source) = source {
        mount = mount.source(source);
    }
    if let Some(fstype) = fstype {
        mount = mount.fstype(fstype);
    }
    if let Some(data) = data {
        mount = mount.data(data);
    }
    Ok(mount)
}

/// Parses an identity-map selector: `single`, `subordinate`, or the explicit
/// range form `uid=IN:OUT:COUNT[,...] gid=IN:OUT:COUNT[,...]`.
fn parse_identity_map(flag: &str, spec: &str) -> Result<IdentityMap, String> {
    match spec.trim() {
        "single" => return Ok(IdentityMap::Single),
        "subordinate" => return Ok(IdentityMap::Subordinate),
        _ => {}
    }
    let mut uid = Vec::new();
    let mut gid = Vec::new();
    for (key, value) in spec_pairs(flag, spec)? {
        let target = match key {
            "uid" => &mut uid,
            "gid" => &mut gid,
            other => {
                return Err(format!(
                    "{flag}: expected 'single', 'subordinate', or uid=/gid= extents, not {other:?}"
                ));
            }
        };
        for extent in value.split(',').filter(|extent| !extent.is_empty()) {
            target.push(parse_id_range(flag, extent)?);
        }
    }
    if uid.is_empty() || gid.is_empty() {
        return Err(format!(
            "{flag}: an explicit range map needs both uid= and gid= extents"
        ));
    }
    Ok(IdentityMap::ranges(uid, gid))
}

/// Parses one `INSIDE:OUTSIDE:COUNT` extent of an explicit range map.
fn parse_id_range(flag: &str, extent: &str) -> Result<IdRange, String> {
    let parts: Vec<&str> = extent.split(':').collect();
    let [inside, outside, count] = parts.as_slice() else {
        return Err(format!(
            "{flag}: {extent:?} is not an INSIDE:OUTSIDE:COUNT extent"
        ));
    };
    let field = |name: &str, text: &str| {
        text.parse::<u32>()
            .map_err(|_| format!("{flag}: {text:?} is not a valid {name}"))
    };
    Ok(IdRange {
        inside: field("inside id", inside)?,
        outside: field("outside id", outside)?,
        count: field("count", count)?,
    })
}

/// Parses a `--run-as` identity: `UID:GID[:GROUP[,GROUP...]]`.
fn parse_run_as(spec: &str) -> Result<Identity, String> {
    let mut fields = spec.splitn(3, ':');
    let id = |name: &str, text: Option<&str>| match text {
        Some(text) => text
            .parse::<u32>()
            .map_err(|_| format!("--run-as: {text:?} is not a valid {name}")),
        None => Err(format!("--run-as requires UID:GID, not {spec:?}")),
    };
    let uid = id("uid", fields.next().filter(|field| !field.is_empty()))?;
    let gid = id("gid", fields.next())?;
    let identity = Identity::new(uid, gid);
    match fields.next().filter(|groups| !groups.is_empty()) {
        None => Ok(identity),
        Some(groups) => {
            let groups = groups
                .split(',')
                .filter(|group| !group.is_empty())
                .map(|group| {
                    group
                        .parse::<u32>()
                        .map_err(|_| format!("--run-as: {group:?} is not a valid group id"))
                })
                .collect::<Result<Vec<_>, _>>()?;
            Ok(identity.groups(groups))
        }
    }
}

/// Parses a `--rlimit` setting: `RESOURCE=SOFT[:HARD]`, where a value of
/// `unlimited` is the kernel's `RLIM_INFINITY` and an omitted hard limit
/// repeats the soft one.
fn parse_rlimit(spec: &str) -> Result<(Resource, Limit, Limit), String> {
    let (name, values) = spec
        .split_once('=')
        .ok_or_else(|| format!("--rlimit expects RESOURCE=SOFT[:HARD], not {spec:?}"))?;
    // Resolved through the library's own `Deserialize`, which is the same name
    // table a profile's `[rlimit]` keys use. A resource added to the library is
    // then spelled identically here without a change, and its rejection message
    // lists the accepted names.
    let resource = Resource::deserialize(serde::de::value::StrDeserializer::<
        serde::de::value::Error,
    >::new(name.trim()))
    .map_err(|error| format!("--rlimit: {error}"))?;
    let limit = |text: &str| -> Result<Limit, String> {
        if text == "unlimited" {
            return Ok(Limit::UNLIMITED);
        }
        text.parse::<u64>()
            .map(Limit::of)
            .map_err(|_| format!("--rlimit: {text:?} is not a limit value or 'unlimited'"))
    };
    let (soft, hard) = match values.split_once(':') {
        Some((soft, hard)) => (limit(soft)?, limit(hard)?),
        None => {
            let both = limit(values)?;
            (both, both)
        }
    };
    Ok((resource, soft, hard))
}

/// Parses a Debian priority floor for `--debian-base-priority`.
///
/// The library owns the name table — it is the same one that reads a
/// `Priority:` field out of an index — so this only prefixes the flag onto the
/// refusal.
fn parse_priority(value: &str) -> Result<Priority, String> {
    value
        .parse()
        .map_err(|err| format!("--debian-base-priority: {err}"))
}

/// The mirrors a repository specification names: its primary, and its backstops
/// in the order they were given.
///
/// The two fields are held apart rather than as one list, because neither a
/// repeated `mirror=` nor a lone `mirror-fallback=` is a spelling of something
/// the caller could have meant. One list read positionally makes both of them
/// mean something: a lone backstop becomes the primary, and a second `mirror=`
/// demotes the first to a backstop ahead of the declared ones. The first is the
/// one that matters — a repository's primary mirror is written into the finished
/// root, as `/etc/apk/repositories` or `sources.list`, so a typo-dropped
/// `mirror=` would leave that root permanently fetching from what the caller
/// meant as a fetch-time backstop.
#[derive(Debug, Default)]
struct MirrorSpec {
    primary: Option<String>,
    fallbacks: Vec<String>,
}

impl MirrorSpec {
    /// Records a `mirror=` field, refusing a second one.
    fn primary(&mut self, flag: &str, url: &str) -> Result<(), String> {
        if let Some(first) = &self.primary {
            return Err(format!(
                "{flag}: mirror= is given twice, as {first:?} and {url:?}; a repository has one \
                 primary mirror, and the rest are mirror-fallback="
            ));
        }
        self.primary = Some(url.to_string());
        Ok(())
    }

    /// Records a `mirror-fallback=` field.
    fn fallback(&mut self, url: &str) {
        self.fallbacks.push(url.to_string());
    }

    /// The primary and its backstops, refusing a spec that names only backstops.
    fn finish(self, flag: &str) -> Result<(Option<String>, Vec<String>), String> {
        if self.primary.is_none() && !self.fallbacks.is_empty() {
            return Err(format!(
                "{flag}: mirror-fallback= names a backstop for a mirror= that was not given; a \
                 repository is fetched from its primary mirror first"
            ));
        }
        Ok((self.primary, self.fallbacks))
    }
}

/// Parses a `--debian-repository` specification:
/// `suite=S mirror=URL [mirror-fallback=URL] [components=a,b] [keyring=PATH]
/// [name=NAME] [trust-unsigned] [allow-stale-release]`.
fn parse_repository(spec: &str) -> Result<Repository, String> {
    let mut suite = None;
    let mut mirrors = MirrorSpec::default();
    let mut components: Vec<String> = Vec::new();
    let mut keyring = None;
    let mut name = None;
    let mut trust_unsigned = false;
    let mut allow_stale = false;
    for (key, value) in spec_pairs("--debian-repository", spec)? {
        match key {
            "suite" => suite = Some(value.to_string()),
            "mirror" => mirrors.primary("--debian-repository", value)?,
            "mirror-fallback" => mirrors.fallback(value),
            "components" => extend_comma(&mut components, value),
            "keyring" => keyring = Some(PathBuf::from(value)),
            "name" => name = Some(value.to_string()),
            "trust-unsigned" => trust_unsigned = bare_field("--debian-repository", key, value)?,
            "allow-stale-release" => allow_stale = bare_field("--debian-repository", key, value)?,
            other => {
                return Err(format!(
                    "--debian-repository: unknown field {other:?}; expected suite, mirror, \
                     mirror-fallback, components, keyring, name, trust-unsigned, or \
                     allow-stale-release"
                ));
            }
        }
    }
    let suite = suite.ok_or("--debian-repository requires a suite= field".to_string())?;
    let (primary, fallbacks) = mirrors.finish("--debian-repository")?;
    let mut builder = Repository::builder(suite)
        .trust_unsigned(trust_unsigned)
        .allow_stale_release(allow_stale);
    if let Some(primary) = primary {
        builder = builder.mirror(primary);
    }
    for fallback in fallbacks {
        builder = builder.mirror_fallback(fallback);
    }
    if !components.is_empty() {
        builder = builder.components(components);
    }
    if let Some(keyring) = keyring {
        builder = builder.keyring(keyring);
    }
    if let Some(name) = name {
        builder = builder.name(name);
    }
    builder
        .build()
        .map_err(|error| format!("--debian-repository: {error}"))
}

/// Where an apk repository's trusted keys come from.
///
/// Resolved after the whole command line is read rather than as the flag is
/// parsed, because the bundled Alpine set is per architecture and
/// `--alpine-arch` may come later. The spelling is checked here; only the
/// lookup waits.
#[derive(Debug, Clone, PartialEq, Eq)]
enum AlpineKeys {
    /// The bundled Alpine set for the bootstrap's architecture.
    Alpine,
    /// The bundled postmarketOS key, which serves every architecture it
    /// publishes.
    PostmarketOs,
    /// A directory of PEM public keys, each held under its file name.
    Dir(PathBuf),
}

/// A `--alpine-repository` specification, read but not yet built.
///
/// Held in this shape for the same reason [`AlpineKeys`] is: a repository is
/// built once the architecture its keys are chosen by is known.
#[derive(Debug, Clone)]
struct AlpineRepositorySpec {
    release: String,
    /// The primary mirror, absent where the spec named none — which the library
    /// refuses, and is left to it so the refusal reads the same however the
    /// repository was configured.
    mirror: Option<String>,
    /// The backstops, in the order they were given.
    fallbacks: Vec<String>,
    components: Vec<String>,
    keys: AlpineKeys,
}

/// Reads a key-set selector: `alpine`, `postmarketos`, or a directory path.
///
/// A path is accepted without being examined, since whether a directory holds
/// usable keys is [`alpine_key_set`]'s question and its answer names the file.
/// An empty selector is not a path, though: read as one it names the working
/// directory, and the run ends at an io failure about a directory the caller
/// never typed rather than at the usage error it is.
fn parse_alpine_keys(flag: &str, value: &str) -> Result<AlpineKeys, String> {
    Ok(match value {
        "alpine" => AlpineKeys::Alpine,
        "postmarketos" => AlpineKeys::PostmarketOs,
        "" => {
            return Err(format!(
                "{flag}: keys= names no key set; write 'alpine', 'postmarketos', or a directory \
                 of PEM public keys"
            ));
        }
        path => AlpineKeys::Dir(PathBuf::from(path)),
    })
}

/// Builds the key set `keys` names, for a bootstrap targeting `architecture`.
///
/// A directory is read as `/etc/apk/keys` is: every regular file in it is a PEM
/// public key held under its own file name, which is the name a signature spells
/// its key by. The directory is read in name order so that two runs over one
/// directory report the same first failure.
fn alpine_key_set(
    flag: &str,
    keys: &AlpineKeys,
    architecture: &str,
) -> Result<AlpineKeySet, String> {
    let directory = match keys {
        AlpineKeys::Alpine => {
            return AlpineKeySet::alpine(architecture).map_err(|err| format!("{flag}: {err}"));
        }
        AlpineKeys::PostmarketOs => return Ok(AlpineKeySet::postmarketos()),
        AlpineKeys::Dir(directory) => directory,
    };

    let mut entries: Vec<PathBuf> = std::fs::read_dir(directory)
        .map_err(|err| format!("{flag}: reading {}: {err}", directory.display()))?
        .map(|entry| {
            entry
                .map(|entry| entry.path())
                .map_err(|err| format!("{flag}: reading {}: {err}", directory.display()))
        })
        .collect::<Result<_, _>>()?;
    entries.sort();

    let mut set = AlpineKeySet::new();
    for path in entries {
        if !path.is_file() {
            continue;
        }
        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
            return Err(format!(
                "{flag}: {} is not a usable key name; a signature names its key by exactly the \
                 file name the repository publishes it under",
                path.display(),
            ));
        };
        let pem = std::fs::read_to_string(&path)
            .map_err(|err| format!("{flag}: reading {}: {err}", path.display()))?;
        set.insert(name, &pem)
            .map_err(|err| format!("{flag}: {err}"))?;
    }
    if set.is_empty() {
        return Err(format!(
            "{flag}: {} holds no keys, so nothing the repository serves could be verified",
            directory.display(),
        ));
    }
    Ok(set)
}

/// Parses an `--alpine-repository` specification:
/// `release=R mirror=URL keys=SOURCE [mirror-fallback=URL] [components=a,b]`.
fn parse_alpine_repository(spec: &str) -> Result<AlpineRepositorySpec, String> {
    let mut release = None;
    let mut mirrors = MirrorSpec::default();
    let mut components: Vec<String> = Vec::new();
    let mut keys = None;
    for (key, value) in spec_pairs("--alpine-repository", spec)? {
        match key {
            "release" => release = Some(value.to_string()),
            "mirror" => mirrors.primary("--alpine-repository", value)?,
            "mirror-fallback" => mirrors.fallback(value),
            "components" => extend_comma(&mut components, value),
            "keys" => keys = Some(parse_alpine_keys("--alpine-repository", value)?),
            other => {
                return Err(format!(
                    "--alpine-repository: unknown field {other:?}; expected release, mirror, \
                     mirror-fallback, components, or keys"
                ));
            }
        }
    }
    let (primary, fallbacks) = mirrors.finish("--alpine-repository")?;
    Ok(AlpineRepositorySpec {
        release: release.ok_or("--alpine-repository requires a release= field".to_string())?,
        mirror: primary,
        fallbacks,
        components,
        // Unlike the primary, an additional repository has no default: its
        // signing key is its own, and the library refuses one without keys.
        keys: keys.ok_or(
            "--alpine-repository requires a keys= field, one of 'alpine', 'postmarketos', or a \
             directory of PEM public keys"
                .to_string(),
        )?,
    })
}

/// Consumes the next argument as the value a flag needs, or reports which flag
/// needed one.
///
/// A free function rather than a closure inside the main parser, because the
/// sub-parsers are functions of their own and a closure there is out of scope:
/// three flags spelled this message by hand before it moved here.
///
/// A value that names another flag is refused rather than consumed. `fcage
/// --remove-rootfs --identity-map=subordinate` would otherwise take the map's
/// spelling as the tree to delete, and report success having removed a path of
/// that name in the working directory instead. Every flag taking a separated
/// value has that shape, which is why the refusal is here and not at the one it
/// was found on.
///
/// Only a name [`FLAGS`] holds is refused, so a value that merely begins with a
/// dash is still the caller's: `--gentoo-prefer-use -systemd` states a
/// preference against a flag and means what it looks like. A value that
/// genuinely is a flag's spelling is written joined, as `--export-to=--odd`.
fn value_for(
    name: &str,
    needs: &str,
    args: &mut dyn Iterator<Item = OsString>,
) -> Result<OsString, String> {
    let value = args
        .next()
        .ok_or_else(|| format!("{name} requires {needs}"))?;
    if named(&value).is_some() {
        return Err(format!(
            "{name} requires {needs}, and {} names a flag; write it joined as \
             {name}=VALUE where it is the value",
            value.to_string_lossy(),
        ));
    }
    Ok(value)
}

/// Consumes the next argument as a required UTF-8 string value.
///
/// The library's examples carry helpers answering the same three questions —
/// this, [`into_string`], and [`flag_value`] — and keep them because a crate's
/// examples cannot reach another crate's code, so sharing four
/// argument-parsing functions would mean publishing a crate for them. Each side
/// owns the wording of its own diagnostics.
fn string_value(name: &str, args: &mut dyn Iterator<Item = OsString>) -> Result<String, String> {
    into_string(name, value_for(name, "a value", args)?)
}

/// Converts a flag value to a `String`, requiring UTF-8.
fn into_string(name: &str, value: OsString) -> Result<String, String> {
    value
        .into_string()
        .map_err(|_| format!("{name} requires a valid UTF-8 value"))
}

/// Appends comma-separated items to `target`, trimming and dropping empties.
fn extend_comma(target: &mut Vec<String>, value: &str) {
    target.extend(
        value
            .split(',')
            .map(str::trim)
            .filter(|item| !item.is_empty())
            .map(str::to_string),
    );
}

/// Splits `--flag=value` syntax, preserving non-UTF-8 values.
fn flag_value(arg: &OsStr, prefix: &[u8]) -> Option<OsString> {
    arg.as_bytes()
        .strip_prefix(prefix)
        .map(|value| OsString::from_vec(value.to_vec()))
}

/// Parses a `--stdin` mode.
fn parse_stdin(value: &OsStr) -> Result<Stdio, String> {
    if value == "inherit" {
        Ok(Stdio::Inherit)
    } else if value == "null" {
        Ok(Stdio::Null)
    } else {
        Err(format!(
            "--stdin accepts 'inherit' or 'null', not {}",
            value.to_string_lossy()
        ))
    }
}

/// Parses a `--seccomp` value, which selects the curated posture.
fn parse_seccomp(value: &str, curated: &mut bool) -> Result<(), String> {
    match value {
        "curated" => {
            *curated = true;
            Ok(())
        }
        other => Err(format!(
            "--seccomp accepts 'curated', not {other:?}; name syscalls with \
             --seccomp-allow/--seccomp-deny or condition them with \
             --seccomp-allow-rule/--seccomp-deny-rule"
        )),
    }
}

/// Appends the comma-separated syscall names in `value` to `target`, resolved
/// to their numbers for the host architecture.
fn parse_seccomp_names(flag: &str, value: &str, target: &mut Vec<i64>) -> Result<(), String> {
    for name in value
        .split(',')
        .map(str::trim)
        .filter(|name| !name.is_empty())
    {
        target.push(resolve_syscall_name(flag, name)?);
    }
    Ok(())
}

/// Parses one `--seccomp-*-rule` value into a syscall number and its argument
/// conditions.
///
/// The value is a syscall name followed by comma-separated conditions, each a
/// space-separated set of `key=value` pairs mirroring a profile's `arg` entry:
/// `arg` (0 through 5), `len` (`dword` or `qword`), `op` (`eq`, `ne`, `ge`,
/// `gt`, `le`, `lt`, or `masked-eq`), `value`, and `mask` (required only for
/// `masked-eq`). Values are decimal or `0x`-prefixed hexadecimal. A rule
/// without conditions lists the syscall unconditionally.
fn parse_seccomp_rule(flag: &str, value: &str) -> Result<(i64, Vec<SeccompArg>), String> {
    let value = value.trim();
    let (name, rest) = match value.split_once(char::is_whitespace) {
        Some((name, rest)) => (name, rest.trim()),
        None => (value, ""),
    };
    if name.is_empty() {
        return Err(format!("{flag} requires a syscall name"));
    }
    let syscall = resolve_syscall_name(flag, name)?;
    let conditions = rest
        .split(',')
        .map(str::trim)
        .filter(|clause| !clause.is_empty())
        .map(|clause| parse_seccomp_condition(flag, clause))
        .collect::<Result<Vec<_>, _>>()?;
    Ok((syscall, conditions))
}

/// Parses one `key=value` condition clause into a [`SeccompArg`].
fn parse_seccomp_condition(flag: &str, clause: &str) -> Result<SeccompArg, String> {
    let mut index: Option<u8> = None;
    let mut len: Option<SeccompArgLen> = None;
    let mut op: Option<String> = None;
    let mut value: Option<u64> = None;
    let mut mask: Option<u64> = None;

    for field in clause.split_whitespace() {
        let (key, raw) = field
            .split_once('=')
            .ok_or_else(|| format!("{flag}: expected key=value, not {field:?}"))?;
        match key {
            "arg" => {
                // A syscall has six argument registers; the library rejects a
                // larger index at build, but a parse-time check reports it
                // where the other usage errors are reported.
                let parsed = raw
                    .parse::<u8>()
                    .ok()
                    .filter(|index| *index <= 5)
                    .ok_or_else(|| format!("{flag}: arg must be 0 through 5, not {raw:?}"))?;
                index = Some(parsed);
            }
            "len" => {
                len = Some(match raw {
                    "dword" => SeccompArgLen::Dword,
                    "qword" => SeccompArgLen::Qword,
                    other => {
                        return Err(format!("{flag}: len must be dword or qword, not {other:?}"));
                    }
                });
            }
            "op" => op = Some(raw.to_string()),
            "value" => value = Some(parse_u64_literal(flag, "value", raw)?),
            "mask" => mask = Some(parse_u64_literal(flag, "mask", raw)?),
            other => return Err(format!("{flag}: unknown condition key {other:?}")),
        }
    }

    let index = index.ok_or_else(|| format!("{flag}: a condition needs arg="))?;
    let len = len.ok_or_else(|| format!("{flag}: a condition needs len= (dword or qword)"))?;
    let op = op.ok_or_else(|| format!("{flag}: a condition needs op="))?;
    let value = value.ok_or_else(|| format!("{flag}: a condition needs value="))?;

    // The mask belongs to masked-eq alone: required there, rejected elsewhere,
    // the same rule the profile applies.
    let compare = match op.as_str() {
        "masked-eq" => SeccompCompare::MaskedEq(
            mask.ok_or_else(|| format!("{flag}: op=masked-eq needs mask="))?,
        ),
        simple => {
            if mask.is_some() {
                return Err(format!("{flag}: mask= is only valid with op=masked-eq"));
            }
            match simple {
                "eq" => SeccompCompare::Eq,
                "ne" => SeccompCompare::Ne,
                "ge" => SeccompCompare::Ge,
                "gt" => SeccompCompare::Gt,
                "le" => SeccompCompare::Le,
                "lt" => SeccompCompare::Lt,
                other => {
                    return Err(format!(
                        "{flag}: op must be eq, ne, ge, gt, le, lt, or masked-eq, not {other:?}"
                    ));
                }
            }
        }
    };

    Ok(SeccompArg::new(index, len, compare, value))
}

/// Parses a decimal or `0x`-prefixed hexadecimal `u64` for a condition field.
fn parse_u64_literal(flag: &str, field: &str, raw: &str) -> Result<u64, String> {
    let parsed = match raw.strip_prefix("0x").or_else(|| raw.strip_prefix("0X")) {
        Some(hex) => u64::from_str_radix(hex, 16),
        None => raw.parse::<u64>(),
    };
    parsed.map_err(|_| format!("{flag}: {field} must be a number (decimal or 0x hex), not {raw:?}"))
}

/// Resolves a syscall name to its number for the host architecture, through
/// the `syscalls` crate, the same table the library uses.
fn resolve_syscall_name(flag: &str, name: &str) -> Result<i64, String> {
    name.parse::<syscalls::Sysno>()
        .map(|sysno| i64::from(sysno.id()))
        .map_err(|_| format!("{flag}: unknown syscall {name:?}"))
}

/// Reconciles the seccomp flags into a single policy, or `None` when none were
/// given.
///
/// The curated posture is a whole policy on its own, so it cannot be combined
/// with named rules. An allow-list and a deny-list are opposite postures and
/// cannot be combined either, the same constraint a profile enforces.
fn assemble_seccomp(
    curated: bool,
    allow: Vec<i64>,
    deny: Vec<i64>,
    allow_rules: Vec<(i64, Vec<SeccompArg>)>,
    deny_rules: Vec<(i64, Vec<SeccompArg>)>,
) -> Result<Option<SeccompPolicy>, String> {
    let allow_side = !allow.is_empty() || !allow_rules.is_empty();
    let deny_side = !deny.is_empty() || !deny_rules.is_empty();

    if curated && (allow_side || deny_side) {
        return Err(
            "--seccomp curated cannot be combined with --seccomp-allow/--seccomp-deny rules"
                .to_string(),
        );
    }
    if curated {
        return Ok(Some(SeccompPolicy::Curated));
    }
    if allow_side && deny_side {
        return Err(
            "--seccomp-allow/--seccomp-allow-rule cannot be combined with \
             --seccomp-deny/--seccomp-deny-rule"
                .to_string(),
        );
    }

    let (bare, rules) = if allow_side {
        (SeccompRules::allowing(allow), allow_rules)
    } else if deny_side {
        (SeccompRules::denying(deny), deny_rules)
    } else {
        return Ok(None);
    };
    let policy = rules
        .into_iter()
        .fold(bare, |rules, (syscall, conditions)| {
            rules.rule(syscall, conditions)
        });
    Ok(Some(SeccompPolicy::Rules(policy)))
}

/// Parses a TCP port for a `--landlock-bind` or `--landlock-connect` grant.
///
/// The value is a decimal port in `0..=65535`; port 0 with `--landlock-bind`
/// permits binding to a kernel-assigned ephemeral port.
fn parse_port(flag: &str, value: &str) -> Result<u16, String> {
    value
        .parse::<u16>()
        .map_err(|_| format!("{flag} requires a TCP port in 0..=65535, not {value:?}"))
}

/// Parses a comma-separated `--keep-caps` list into capabilities.
///
/// Each name is parsed by the library's [`Capability`] `FromStr`, which
/// accepts the kebab or snake form with or without a `cap-`/`cap_` prefix
/// (`net-bind-service`, `CAP_SYS_ADMIN`).
fn parse_caps(value: &str) -> Result<Vec<Capability>, String> {
    value
        .split(',')
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(|name| name.parse::<Capability>().map_err(|err| err.to_string()))
        .collect()
}

/// Parses a positive decimal duration in seconds.
fn parse_seconds(name: &str, value: &OsStr) -> Result<Duration, String> {
    let seconds: f64 = value
        .to_str()
        .and_then(|value| value.parse().ok())
        .ok_or(format!("{name} requires a number of seconds"))?;
    if !seconds.is_finite() || seconds <= 0.0 {
        return Err(format!("{name} requires a positive number of seconds"));
    }
    Duration::try_from_secs_f64(seconds).map_err(|_| format!("{name} is too large"))
}

/// What the CLI needs to know about a loaded profile beyond the builder itself.
struct ProfileMeta {
    /// The profile sets a `TERM` variable, so the host `TERM` is not applied as
    /// a fallback beneath it.
    sets_term: bool,
    /// The profile requests host networking, which `--netstack` cannot attach
    /// a stack to.
    network_host: bool,
    /// The profile states `stop-with-caller`, so `fcage`'s own default for it
    /// is not applied over the answer the profile gave.
    sets_stop_with_caller: bool,
}

/// Whether to set the caller tie, and to what: the flag where one was given,
/// `fcage`'s own default where neither the command line nor a profile said.
///
/// The tie is on by default here, unlike in the library: `fcage` waits for the
/// command and exits with it, so a sandbox that outlived the process is never
/// what a shell or a supervisor meant. Without it a SIGTERM to `fcage` —
/// `timeout(1)` is the everyday source — kills the waiter and orphans the
/// sandbox.
///
/// A default is not a setting, though, so it is applied only where nothing else
/// answers. Seeding the option with it instead made every run state the tie, and
/// a profile's `stop-with-caller = false` was overridden by a value its author
/// never wrote — leaving a documented profile key unreachable through `fcage`.
fn stop_with_caller_default(flag: Option<bool>, profile_states_it: bool) -> Option<bool> {
    flag.or((!profile_states_it).then_some(true))
}

/// Loads a profile into a builder, alongside the metadata the CLI reconciles
/// against its own flags.
///
/// With `override_command`, the profile's command and arguments are dropped
/// before it is deserialized: when the command line names a command of its own,
/// it overrides the profile's as a unit, never mixed with the profile's
/// arguments.
///
/// With `restricted`, the profile is deserialized under the library's
/// [`RestrictedProfile`] policy, which refuses the operations that map host
/// resources into the sandbox or share a host namespace; otherwise it is
/// trusted as code-equivalent configuration.
fn load_profile(
    path: &Path,
    override_command: bool,
    restricted: bool,
) -> Result<(CageBuilder, ProfileMeta), String> {
    let text = std::fs::read_to_string(path)
        .map_err(|err| format!("cannot read profile {}: {err}", path.display()))?;
    let mut table: toml::Table = text
        .parse()
        .map_err(|err| format!("cannot parse profile {}: {err}", path.display()))?;
    if override_command {
        table.remove("command");
        table.remove("args");
    }
    let meta = ProfileMeta {
        sets_term: table
            .get("env")
            .and_then(|env| env.as_table())
            .is_some_and(|env| env.contains_key("TERM")),
        network_host: table.get("network").and_then(|value| value.as_str()) == Some("host"),
        sets_stop_with_caller: table.contains_key("stop-with-caller"),
    };
    let builder = if restricted {
        let profile: RestrictedProfile = table
            .try_into()
            .map_err(|err| format!("cannot load profile {}: {err}", path.display()))?;
        profile.into_builder()
    } else {
        table
            .try_into()
            .map_err(|err| format!("cannot load profile {}: {err}", path.display()))?
    };
    Ok((builder, meta))
}

/// Deletes the provisioned rootfs at `dest`, under the identity map it was
/// written under.
///
/// A tree a range-mapped sandbox wrote carries subordinate ownership that a
/// plain `rm -rf` cannot delete; the library re-enters the same map to remove
/// it. A failure exits 125, the code every other setup failure uses: nothing
/// ran, so there is no command status to report.
fn remove_rootfs(dest: &Path, map: IdentityMap) -> ExitCode {
    match ferroday_cage::provision::Remove::new(dest).map(map).run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("fcage: {error}");
            ExitCode::from(125)
        }
    }
}

/// Writes a provisioned rootfs to a tar archive, to a file or to standard
/// output.
///
/// A named destination appears complete or not at all: the library stages the
/// archive beside it and renames, so a run that fails part-way leaves whatever
/// archive was already there. Standard output has no such staging, and a
/// pipeline that consumes a partial stream is the caller's to arrange.
///
/// The terminal refusal is here rather than in the parser, so that parsing a
/// command line stays a function of the command line: whether standard output
/// is a terminal is a property of how `fcage` was invoked, not of what was
/// typed, and a parser that consulted it would answer differently under a test
/// harness than at a prompt. It is still the usage error it looks like, exit
/// code and all.
fn export_rootfs(
    source: &Path,
    dest: Option<&Path>,
    map: IdentityMap,
    clamp_mtime: Option<i64>,
) -> ExitCode {
    use std::io::IsTerminal as _;

    if dest.is_none() && std::io::stdout().is_terminal() {
        eprintln!("fcage: refusing to write an archive to the terminal");
        eprintln!("Try '--export-to FILE', or pipe the output into a compressor.");
        return ExitCode::from(2);
    }

    let mut export = ferroday_cage::provision::Export::new(source).map(map);
    if let Some(epoch) = clamp_mtime {
        export = export.clamp_mtime(epoch);
    }

    // To a file the library stages and renames, so a failed export leaves an
    // existing archive at the destination exactly as it found it; to standard
    // output there is nothing to stage onto, and the library buffers the writer
    // itself, so neither arm wraps it again.
    let written = match dest {
        Some(path) => export.write_to_path(path),
        None => export.write_to(std::io::stdout().lock()),
    };

    match written {
        Ok(()) => ExitCode::SUCCESS,
        // A reader that stopped early — `fcage --export-rootfs X | head -c 512`
        // — is not a failure of the export. The conventional ending is a quiet
        // one, so it is reported as the signal a writer to a closed pipe would
        // ordinarily die of rather than as noise on stderr.
        Err(ferroday_cage::provision::ProvisionError::Io { source, .. })
            if dest.is_none() && source.kind() == std::io::ErrorKind::BrokenPipe =>
        {
            ExitCode::from(141)
        }
        Err(error) => {
            eprintln!("fcage: {error}");
            ExitCode::from(125)
        }
    }
}

/// Builds and runs the sandbox, mapping the outcome onto the exit status.
fn run(options: Options) -> ExitCode {
    if options.restrict {
        return run_restricted(options);
    }
    if let Some(tarball) = &options.provision_tar {
        // The parser guarantees a rootfs accompanies --provision-tar. An
        // already-provisioned rootfs is reused as it stands.
        let rootfs = options.rootfs.as_deref().expect("checked at parse time");
        let mut provisioner = ferroday_cage::provision::Tarball::new(tarball);
        if let Err(error) = ferroday_cage::provision::ensure(rootfs, &mut provisioner) {
            eprintln!("fcage: {error}");
            return ExitCode::from(125);
        }
    }
    if let Some(suite) = &options.provision_debian {
        let rootfs = options.rootfs.as_deref().expect("checked at parse time");
        if let Err(code) = provision_debian(suite, &options, rootfs) {
            return code;
        }
    }
    if let Some(release) = &options.provision_alpine {
        let rootfs = options.rootfs.as_deref().expect("checked at parse time");
        if let Err(code) = provision_alpine(release, &options, rootfs) {
            return code;
        }
    }

    if let Some(architecture) = &options.provision_gentoo {
        let rootfs = options.rootfs.as_deref().expect("checked at parse time");
        if let Err(code) = provision_gentoo(architecture, &options, rootfs) {
            return code;
        }
    }

    // A provisioning run with no command and no profile provisions and exits.
    if options.command_line.is_empty() && options.profile.is_none() {
        return ExitCode::SUCCESS;
    }

    // Assembled here for two reasons: `options` is consumed field by field as
    // the builder is composed below, and a configuration the stack refuses is
    // better reported before a sandbox has been built for it.
    let stack = if options.netstack {
        match netstack_from(&options) {
            Ok(stack) => Some(stack),
            Err(error) => {
                eprintln!("fcage: {error}");
                return ExitCode::from(125);
            }
        }
    } else {
        None
    };

    let mut profile_sets_term = false;
    let mut profile_network_host = false;
    let mut profile_sets_stop_with_caller = false;
    let mut builder = match &options.profile {
        Some(path) => match load_profile(
            path,
            !options.command_line.is_empty(),
            options.profile_restricted,
        ) {
            Ok((builder, meta)) => {
                profile_sets_term = meta.sets_term;
                profile_network_host = meta.network_host;
                profile_sets_stop_with_caller = meta.sets_stop_with_caller;
                builder
            }
            Err(message) => {
                eprintln!("fcage: {message}");
                return ExitCode::from(125);
            }
        },
        None => Cage::builder(),
    };

    // The parse-time guard rejects --netstack with --share-net, but a profile
    // can request host networking without any CLI network flag, leaving that
    // check blind. Reconcile against the loaded profile: attaching a stack to a
    // host-network sandbox cannot work, and the usage error belongs here.
    if options.netstack && options.network.is_none() && profile_network_host {
        eprintln!("fcage: --netstack cannot be used with a profile that sets network = \"host\"");
        eprintln!("Try 'fcage --help' for usage.");
        return ExitCode::from(2);
    }

    if let Some(rootfs) = options.rootfs {
        builder = builder.rootfs(rootfs);
    }
    // An overlay root, when the run named one. Parse-time validation has
    // already established that a lower and an upper are both present and that
    // no --rootfs competes with them.
    if !options.overlay_lowers.is_empty() {
        let mut overlay = Overlay::new();
        for lower in options.overlay_lowers {
            overlay = overlay.lower(lower);
        }
        if let Some(upper) = options.overlay_upper {
            overlay = overlay.upper(upper);
        }
        if let Some(work) = options.overlay_work {
            overlay = overlay.work(work);
        }
        builder = builder.overlay(overlay);
    }
    let mut command_line = options.command_line.into_iter();
    if let Some(command) = command_line.next() {
        builder = builder.command(PathBuf::from(command)).args(command_line);
    }
    // The host TERM passes through so interactive commands work at a prompt,
    // but only as a fallback: a profile or --setenv TERM overrides it. Since
    // `envs` appends (last-wins), adding the host TERM unconditionally would
    // override the profile, so it is added only when neither the profile nor
    // --setenv sets TERM.
    let mut env = options.setenv;
    let setenv_sets_term = env.iter().any(|(key, _)| key.to_str() == Some("TERM"));
    if !profile_sets_term
        && !setenv_sets_term
        && let Some(term) = std::env::var_os("TERM")
    {
        env.push((OsString::from("TERM"), term));
    }
    builder = builder.envs(env);
    // One pass, so a `--raw-mount` written between two `--bind` flags is
    // applied between them.
    for mount in options.mounts {
        builder = match mount {
            Mount::Bind(bind) => {
                if bind.is_read_only() {
                    builder.bind_ro(bind.get_source(), bind.get_target())
                } else {
                    builder.bind(bind.get_source(), bind.get_target())
                }
            }
            Mount::Raw(raw) => builder.raw_mount(raw),
            // `Mount` is non-exhaustive. A kind this build cannot apply must
            // not be dropped in silence: a sandbox missing a mount it was
            // asked for is not the sandbox that was asked for.
            other => {
                eprintln!("fcage: unsupported mount kind: {other:?}");
                return ExitCode::from(125);
            }
        };
    }
    for (resource, soft, hard) in options.rlimits {
        builder = builder.rlimit(resource, soft, hard);
    }
    if let Some(map) = options.identity_map {
        builder = builder.identity_map(map);
    }
    if let Some(identity) = options.run_as {
        builder = builder.run_as(identity);
    }
    if let Some(enabled) = options.path_lookup {
        builder = builder.path_lookup(enabled);
    }
    if let Some(hostname) = options.hostname {
        builder = builder.hostname(hostname);
    }
    if let Some(chdir) = options.chdir {
        builder = builder.current_dir(chdir);
    }
    if let Some(stdin) = options.stdin {
        builder = builder.stdin(stdin);
    }
    if let Some(network) = options.network {
        builder = builder.network(network);
    }
    if let Some(isolate) = options.pid_namespace {
        builder = builder.pid_namespace(isolate);
    }
    if let Some(mount) = options.mount_proc {
        builder = builder.mount_proc(mount);
    }
    if let Some(mount) = options.mount_dev {
        builder = builder.mount_dev(mount);
    }
    if let Some(mount) = options.mount_tmp {
        builder = builder.mount_tmp(mount);
    }
    if let Some(bind) = options.resolv_conf {
        builder = builder.resolv_conf(bind);
    }
    if let Some(managed) = options.managed_mounts {
        builder = builder.managed_mounts(managed);
    }
    if let Some(base) = options.base_env {
        builder = builder.base_env(base);
    }
    if let Some(tie) =
        stop_with_caller_default(options.stop_with_caller, profile_sets_stop_with_caller)
    {
        builder = builder.stop_with_caller(tie);
    }
    for (path, writable) in options.landlock {
        builder = builder.landlock_fs(landlock_access(writable), path);
    }
    for (port, access) in options.landlock_net {
        builder = builder.landlock_net(access, port);
    }
    if let Some(policy) = options.seccomp {
        builder = builder.seccomp(policy);
    }
    match options.caps {
        Some(CapsChoice::DropAll) => builder = builder.drop_all_capabilities(),
        Some(CapsChoice::Keep(caps)) => builder = builder.keep_capabilities(caps),
        None => {}
    }

    if options.netstack {
        // The native stack composes the sandbox's DNS from the host's routable
        // nameservers, unless the run opts out. --no-managed-mounts opts out
        // as surely as --no-resolv-conf does: its promise is that the sandbox
        // carries exactly the binds the command line names, and this would be
        // one it does not.
        //
        // The builder is asked rather than the flags, so that a profile
        // setting either toggle governs this composition exactly as the
        // matching flag does. Both have already been applied above.
        if builder.get_resolv_conf() {
            builder = compose_netstack_resolv_conf(builder);
        }
        return run_with_netstack(
            builder,
            stack.expect("assembled above for exactly this branch"),
            options.terminal,
            options.timeout,
            options.kill_after,
        );
    }

    if options.terminal {
        return run_on_a_terminal(builder, options.timeout, options.kill_after);
    }

    let outcome = builder
        .build()
        .and_then(|cage| cage.spawn())
        .and_then(|running| wait_with_deadline(running, options.timeout, options.kill_after));
    conclude(outcome)
}

/// Runs a sandbox on a pseudoterminal of its own and relays the caller's
/// terminal to it.
///
/// The signals the relay reads are blocked first, before anything else the run
/// may start, so no thread of this process is left able to take one; raw mode is
/// entered last, inside the relay, so every failure up to that point leaves the
/// caller's terminal untouched.
fn run_on_a_terminal(
    builder: CageBuilder,
    timeout: Option<Duration>,
    kill_after: Duration,
) -> ExitCode {
    let signals = match Signals::install() {
        Ok(signals) => signals,
        Err(error) => return conclude_relay(Err(error)),
    };
    let launched = builder
        .build()
        .and_then(|cage| cage.spawn_terminal(&terminal::terminal_for_caller()));
    let (running, pty) = match launched {
        Ok(launched) => launched,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(error.shell_code());
        }
    };
    conclude_relay(terminal::relay(running, pty, signals, timeout, kill_after))
}

/// Maps a relay's outcome onto the process exit status.
///
/// The library's own failures go through [`conclude`], so a launch that fails
/// the same way with and without a terminal exits the same way. The relay's own
/// plumbing failing is a `fcage` failure, which is 125.
fn conclude_relay(outcome: Result<Option<ExitStatus>, RelayError>) -> ExitCode {
    match outcome {
        Ok(outcome) => conclude(Ok(outcome)),
        Err(RelayError::Cage(error)) => conclude(Err(error)),
        Err(error) => {
            eprintln!("fcage: {error}");
            ExitCode::from(125)
        }
    }
}

/// Assembles the native network stack the `--netstack-*` flags describe.
///
/// Built before the sandbox is, so a configuration the stack refuses -- a
/// prefix outside its range, an MTU below the floor IPv6 raises, an interface
/// name the kernel would not take, both protocols turned off -- is reported
/// without a sandbox having been created and torn down for it. Building the
/// stack starts nothing: the pump thread is `attach`'s, and the relay's signal
/// mask has to be in place before it exists.
fn netstack_from(options: &Options) -> Result<NetStack, ferroday_cage::NetStackError> {
    let mut stack = NetStack::builder()
        .ipv4(!options.netstack_no_ipv4)
        .ipv6(!options.netstack_no_ipv6)
        .host_loopback(options.netstack_host_loopback);
    if let Some((network, prefix_len)) = options.netstack_cidr {
        stack = stack.ipv4_cidr(network, prefix_len);
    }
    if let Some((network, prefix_len)) = options.netstack_cidr6 {
        stack = stack.ipv6_cidr(network, prefix_len);
    }
    if let Some(name) = &options.netstack_interface {
        stack = stack.interface(name);
    }
    if let Some(mtu) = options.netstack_mtu {
        stack = stack.mtu(mtu);
    }
    stack.build()
}

/// Builds and runs a sandbox with the native network stack attached at the
/// pending seam: build, hold the command, attach the stack, then release it
/// so the network is up before the command's first instruction.
fn run_with_netstack(
    builder: CageBuilder,
    stack: NetStack,
    terminal: bool,
    timeout: Option<Duration>,
    kill_after: Duration,
) -> ExitCode {
    // Blocked before the stack's own thread exists, so that thread inherits the
    // mask and no process-directed signal can be delivered behind the relay's
    // back. Nothing is allocated for a run without a terminal.
    let signals = if terminal {
        match Signals::install() {
            Ok(signals) => Some(signals),
            Err(error) => return conclude_relay(Err(error)),
        }
    } else {
        None
    };
    let cage = match builder.build() {
        Ok(cage) => cage,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(error.shell_code());
        }
    };

    // Hold the command at the gate, attach the stack to the sandbox's
    // namespace, then release the command. A failed attach drops the
    // pending launch, which tears the sandbox down.
    //
    // With a terminal, the primary comes back here rather than out of
    // `proceed`: the pseudoterminal is allocated before the fork and the gate
    // sits after its controlling terminal is established, so the stack is
    // attached with the primary already in hand.
    let held = if terminal {
        cage.spawn_pending_terminal(&terminal::terminal_for_caller())
            .map(|(pending, pty)| (pending, Some(pty)))
    } else {
        cage.spawn_pending().map(|pending| (pending, None))
    };
    let (pending, pty) = match held {
        Ok(held) => held,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(error.shell_code());
        }
    };
    let handle = match stack.attach(&pending) {
        Ok(handle) => handle,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(125);
        }
    };
    let running = match pending.proceed() {
        Ok(running) => running,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(error.shell_code());
        }
    };

    // The relay when a terminal was allocated, the plain wait otherwise. Both
    // return the same outcome; only the driving differs.
    let outcome = match (pty, signals) {
        (Some(pty), Some(signals)) => terminal::relay(running, pty, signals, timeout, kill_after),
        _ => wait_with_deadline(running, timeout, kill_after).map_err(Into::into),
    };
    // The stack is torn down after the command; a failure here loses no
    // data, so it is a warning, not the run's outcome. Printed after the relay
    // has restored the caller's terminal, so it is not stair-stepped.
    if let Err(error) = handle.stop() {
        eprintln!("fcage: the network stack did not stop cleanly: {error}");
    }
    conclude_relay(outcome)
}

/// Whether one of the caller's own mounts targets the sandbox's
/// `/etc/resolv.conf`.
///
/// The same question the library asks of a host-network sandbox's managed bind,
/// asked again here because the bind a `--netstack` run composes is `fcage`'s
/// own and the library never sees it. Both answers must move together: a target
/// the library yields to and this one overrides would have the sandbox's DNS
/// depend on which of the two composed the bind.
///
/// Every kind of mount counts, not only a bind. A `--raw-mount` carries a source
/// and the kernel's own flags, so a bind is expressible through it, and a caller
/// who reaches for it has claimed the target as deliberately as `--bind` does.
///
/// `Path` compares by components, so `/etc//resolv.conf` and
/// `/etc/./resolv.conf` are the same target here as they are there.
fn mounts_resolv_conf(builder: &CageBuilder) -> bool {
    builder
        .get_mounts()
        .iter()
        .any(|mount| mount.get_target() == Path::new("/etc/resolv.conf"))
}

/// Composes the sandbox's `resolv.conf` for a native-stack run: binds the
/// host's `resolv.conf` read-only when it names a routable nameserver, and
/// otherwise composes nothing and says so.
///
/// A loopback nameserver — systemd-resolved's `127.0.0.53` stub is the
/// common one — is unreachable through the stack, which refuses loopback
/// destinations, so binding it would only produce silent DNS failures.
///
/// Composing nothing leaves whatever `resolv.conf` the rootfs ships, which
/// may name a routable resolver and resolve perfectly well. The warning
/// therefore reports what was not composed; it does not predict that the
/// sandbox has no DNS, which is not this function's to know.
fn compose_netstack_resolv_conf(builder: CageBuilder) -> CageBuilder {
    // A caller who mounted the target themselves named it deliberately, and
    // this bind is composed after every mount the command line and the profile
    // carry -- so it would land on top of theirs and decide the sandbox's DNS
    // in silence. Their mount replaces this one, as it does the library's own
    // managed bind for a host-network sandbox.
    if mounts_resolv_conf(&builder) {
        return builder;
    }
    let Ok(contents) = std::fs::read_to_string("/etc/resolv.conf") else {
        // No host resolv.conf to compose from; leave the sandbox's as-is.
        return builder;
    };
    if resolv_conf_has_routable_nameserver(&contents) {
        return builder.bind_ro("/etc/resolv.conf", "/etc/resolv.conf");
    }
    eprintln!(
        "fcage: the host's nameservers are all on loopback, which the network stack \
         refuses, so no resolv.conf was composed; the sandbox resolves through whatever \
         its rootfs ships (point it at a routable nameserver, or give it the gateway \
         address and pass --netstack-host-loopback, which reaches a host resolver only \
         when that resolver listens on 127.0.0.1 — not systemd-resolved's 127.0.0.53 \
         stub)"
    );
    builder
}

/// Whether a `resolv.conf` names at least one nameserver that is not a
/// loopback address, and so reachable through the network stack.
fn resolv_conf_has_routable_nameserver(contents: &str) -> bool {
    contents.lines().any(|line| {
        let line = line.trim();
        let Some(address) = line.strip_prefix("nameserver") else {
            return false;
        };
        // The keyword and its value are separated by whitespace, and glibc
        // ignores a line that runs them together. Reading `nameserver8.8.8.8`
        // as a nameserver would count a line the resolver does not as the
        // reason this host is considered routable.
        if !address.starts_with([' ', '\t']) {
            return false;
        }
        match address.trim().parse::<std::net::IpAddr>() {
            Ok(address) => !address.is_loopback(),
            Err(_) => false,
        }
    })
}

/// Builds and runs a restriction — the --restrict mode — mapping the outcome
/// onto the exit status exactly as the sandbox path does.
fn run_restricted(options: Options) -> ExitCode {
    let mut builder = Restriction::builder();
    let mut command_line = options.command_line.into_iter();
    if let Some(command) = command_line.next() {
        builder = builder.command(PathBuf::from(command)).args(command_line);
    }
    // The host TERM passes through so interactive commands work at a
    // prompt; it is set first, so a --setenv TERM overrides it.
    let mut env = options.setenv;
    if let Some(term) = std::env::var_os("TERM") {
        env.insert(0, (OsString::from("TERM"), term));
    }
    builder = builder.envs(env);
    if let Some(base) = options.base_env {
        builder = builder.base_env(base);
    }
    if let Some(chdir) = options.chdir {
        builder = builder.current_dir(chdir);
    }
    if let Some(stdin) = options.stdin {
        builder = builder.stdin(stdin);
    }
    for (resource, soft, hard) in options.rlimits {
        builder = builder.rlimit(resource, soft, hard);
    }
    if let Some(tie) = stop_with_caller_default(options.stop_with_caller, false) {
        builder = builder.stop_with_caller(tie);
    }
    for (path, writable) in options.landlock {
        builder = builder.landlock_fs(landlock_access(writable), path);
    }
    for (port, access) in options.landlock_net {
        builder = builder.landlock_net(access, port);
    }
    if let Some(policy) = options.seccomp {
        builder = builder.seccomp(policy);
    }

    if options.terminal {
        // A host-allocated pseudoterminal needs no devpts instance, so the
        // fallback gets the same interactive story a cage does.
        let signals = match Signals::install() {
            Ok(signals) => signals,
            Err(error) => return conclude_relay(Err(error)),
        };
        let launched = builder
            .build()
            .and_then(|restriction| restriction.spawn_terminal(&terminal::terminal_for_caller()));
        let (running, pty) = match launched {
            Ok(launched) => launched,
            Err(error) => {
                eprintln!("fcage: {error}");
                return ExitCode::from(error.shell_code());
            }
        };
        return conclude_relay(terminal::relay(
            running,
            pty,
            signals,
            options.timeout,
            options.kill_after,
        ));
    }

    let outcome = builder
        .build()
        .and_then(|restriction| restriction.spawn())
        .and_then(|running| wait_with_deadline(running, options.timeout, options.kill_after));
    conclude(outcome)
}

/// The Landlock access set a --landlock-ro or --landlock-rw grant confers.
fn landlock_access(writable: bool) -> FsAccess {
    if writable {
        FsAccess::READ | FsAccess::WRITE | FsAccess::EXECUTE
    } else {
        FsAccess::READ | FsAccess::EXECUTE
    }
}

/// Waits a launch out under the optional deadline, escalating as
/// [`Escalation`] says. `Ok(None)` means the deadline fired.
///
/// The blocking half of the two waits `fcage` has; the terminal relay drives
/// the same escalation from its poll loop.
fn wait_with_deadline(
    mut running: Running<'_>,
    timeout: Option<Duration>,
    kill_after: Duration,
) -> Result<Option<ExitStatus>, Error> {
    let mut escalation = Escalation::new(timeout, kill_after);
    let status = loop {
        // No deadline left: either none was asked for, or the escalation has
        // run its course and only the outcome is outstanding.
        let Some(deadline) = escalation.deadline() else {
            break running.wait()?;
        };
        match running.wait_deadline(deadline)? {
            Some(status) => break status,
            None => escalation.expire(&mut running)?,
        }
    };
    Ok(escalation.outcome(status))
}

/// Maps a launch outcome onto the process exit status.
fn conclude(outcome: Result<Option<ExitStatus>, Error>) -> ExitCode {
    match outcome {
        // The timeout(1) convention: 124 announces an expired timeout,
        // whatever became of the command afterwards.
        Ok(None) => ExitCode::from(124),
        Ok(Some(status)) => ExitCode::from(status.shell_code()),
        Err(error) => {
            eprintln!("fcage: {error}");
            ExitCode::from(error.shell_code())
        }
    }
}

/// Reads the plan document a `--*-plan` or `--*-pin` flag names and parses it
/// with `parse`.
///
/// The parse is each userland's own -- three formats, three `Plan` types, three
/// `parse_document` functions -- but reading the file and saying what stopped it
/// is one question, and its answer names the path the caller typed rather than
/// the layer that could not read it. Both failures are environment failures, so
/// both are 125.
fn plan_from<P, E: std::fmt::Display>(
    path: &Path,
    parse: impl FnOnce(&str) -> Result<P, E>,
) -> Result<P, ExitCode> {
    let document = std::fs::read_to_string(path).map_err(|error| {
        eprintln!("fcage: reading {}: {error}", path.display());
        ExitCode::from(125)
    })?;
    parse(&document).map_err(|error| {
        eprintln!("fcage: {}: {error}", path.display());
        ExitCode::from(125)
    })
}

/// Bootstraps a Debian rootfs from the archive, printing progress to stderr.
///
/// Returns `Err` with the process exit code on failure.
fn provision_debian(suite: &str, options: &Options, rootfs: &Path) -> Result<(), ExitCode> {
    use ferroday_cage::provision::debian::{Debian, Plan};

    let mut builder = Debian::builder(suite).extract_only(options.debian_extract_only);
    if let Some(arch) = &options.debian_arch {
        builder = builder.architecture(arch.as_str());
    }
    if let Some(mirror) = &options.debian_mirror {
        builder = builder.mirror(mirror.as_str());
    }
    if !options.debian_components.is_empty() {
        builder = builder.components(options.debian_components.clone());
    }
    if !options.debian_include.is_empty() {
        builder = builder.include(options.debian_include.clone());
    }
    if !options.debian_exclude.is_empty() {
        builder = builder.exclude(options.debian_exclude.clone());
    }
    if let Some(path) = &options.debian_plan {
        builder = builder.plan(plan_from(path, Plan::parse_document)?);
    }
    if let Some(path) = &options.debian_pin {
        builder = builder.pin(plan_from(path, Plan::parse_document)?);
    }
    if let Some(cache) = &options.debian_cache {
        builder = builder.cache_dir(cache);
    }
    if let Some(keyring) = &options.debian_keyring {
        builder = builder.keyring(keyring);
    }
    for fallback in &options.debian_mirror_fallback {
        builder = builder.mirror_fallback(fallback.as_str());
    }
    if let Some(priority) = options.debian_base_priority {
        builder = builder.base_priority(priority);
    }
    if options.debian_trust_unsigned {
        builder = builder.trust_unsigned(true);
    }
    if options.debian_allow_stale_release {
        builder = builder.allow_stale_release(true);
    }
    if let Some(overlay) = &options.debian_pre_configure_overlay {
        builder = builder.pre_configure_overlay(overlay);
    }
    if let Some(map) = &options.debian_identity_map {
        builder = builder.identity_map(map.clone());
    }
    for repository in &options.debian_repositories {
        builder = builder.repository(repository.clone());
    }

    let mut debian = builder.build().map_err(|error| {
        eprintln!("fcage: {error}");
        ExitCode::from(125)
    })?;
    let mut progress = print_debian_event;
    ferroday_cage::provision::ensure(rootfs, &mut debian.observe(&mut progress)).map_err(
        |error| {
            eprintln!("fcage: {error}");
            ExitCode::from(125)
        },
    )?;
    Ok(())
}

/// Prints a Debian bootstrap progress event to stderr.
fn print_debian_event(event: ferroday_cage::provision::debian::DebianEvent<'_>) {
    use ferroday_cage::provision::debian::DebianEvent;
    use std::io::Write;
    match event {
        DebianEvent::Fetching { url, .. } => eprintln!("fcage: fetching {url}"),
        DebianEvent::Resolving => eprintln!("fcage: resolving the package set"),
        DebianEvent::Unsatisfiable {
            requirement,
            required_by,
            reason,
            ..
        } => eprintln!("fcage: {required_by} requires {requirement}, and {reason}"),
        DebianEvent::Downloading {
            package,
            index,
            total,
            ..
        } => eprintln!("fcage: downloading {package} ({index}/{total})"),
        DebianEvent::Extracting { package, .. } => eprintln!("fcage: extracting {package}"),
        // dpkg's own output flows straight to stderr.
        DebianEvent::CommandOutput { bytes, .. } => {
            let _ = std::io::stderr().write_all(bytes);
        }
        _ => {}
    }
}

/// Bootstraps an Alpine rootfs from the archive, printing progress to stderr.
///
/// Mirrors [`provision_debian`] flag for flag where the two layers agree. Where
/// they do not, the difference is the archive's: apk publishes no priority band,
/// so there is no base-set floor and the install set is exactly what
/// `--alpine-include` names closed over its dependencies; and it has no unsigned
/// mode and no freshness window, so there is nothing for a `--debian-*`
/// counterpart of `trust-unsigned` or `allow-stale-release` to relax.
fn provision_alpine(release: &str, options: &Options, rootfs: &Path) -> Result<(), ExitCode> {
    use ferroday_cage::provision::alpine::{Alpine, Plan, Repository};

    let usage = |message: String| {
        eprintln!("fcage: {message}");
        ExitCode::from(2)
    };
    // Reading a key set is not spelling: the selector was checked when the
    // command line was parsed, so what is left is whether this machine can
    // supply the keys — an unreadable directory, a file that is not a PEM key,
    // a bundle holding none for the architecture. Those are what 125 means, and
    // what the library reports for the same failures when it resolves the keys
    // itself. A script telling "fix my command line" from "fix my machine" reads
    // the two codes.
    let environment = |message: String| {
        eprintln!("fcage: {message}");
        ExitCode::from(125)
    };

    // The architecture the key sets are chosen by: the one named, or the host's,
    // which is what the builder would default to.
    let architecture = options
        .alpine_arch
        .clone()
        .unwrap_or_else(ferroday_cage::provision::alpine::host_architecture);

    let mut builder = Alpine::builder(release)
        .architecture(&architecture)
        .extract_only(options.alpine_extract_only);
    if let Some(mirror) = &options.alpine_mirror {
        builder = builder.mirror(mirror);
    }
    for fallback in &options.alpine_mirror_fallback {
        builder = builder.mirror_fallback(fallback);
    }
    if !options.alpine_components.is_empty() {
        builder = builder.components(options.alpine_components.clone());
    }
    if !options.alpine_include.is_empty() {
        builder = builder.include(options.alpine_include.clone());
    }
    if !options.alpine_exclude.is_empty() {
        builder = builder.exclude(options.alpine_exclude.clone());
    }
    if let Some(path) = &options.alpine_plan {
        builder = builder.plan(plan_from(path, Plan::parse_document)?);
    }
    if let Some(path) = &options.alpine_pin {
        builder = builder.pin(plan_from(path, Plan::parse_document)?);
    }
    if let Some(cache) = &options.alpine_cache {
        builder = builder.cache_dir(cache);
    }
    if let Some(keys) = &options.alpine_keys {
        builder = builder
            .keys(alpine_key_set("--alpine-keys", keys, &architecture).map_err(environment)?);
    }
    if let Some(overlay) = &options.alpine_pre_configure_overlay {
        builder = builder.pre_configure_overlay(overlay);
    }
    if let Some(map) = &options.alpine_identity_map {
        builder = builder.identity_map(map.clone());
    }
    for spec in &options.alpine_repositories {
        let mut repository = Repository::builder(&spec.release).keys(
            alpine_key_set("--alpine-repository", &spec.keys, &architecture)
                .map_err(environment)?,
        );
        if let Some(primary) = &spec.mirror {
            repository = repository.mirror(primary);
        }
        for fallback in &spec.fallbacks {
            repository = repository.mirror_fallback(fallback);
        }
        if !spec.components.is_empty() {
            repository = repository.components(spec.components.clone());
        }
        builder = builder.repository(
            repository
                .build()
                .map_err(|error| usage(format!("--alpine-repository: {error}")))?,
        );
    }

    let mut alpine = builder.build().map_err(|error| {
        eprintln!("fcage: {error}");
        ExitCode::from(125)
    })?;
    let mut progress = print_alpine_event;
    ferroday_cage::provision::ensure(rootfs, &mut alpine.observe(&mut progress)).map_err(
        |error| {
            eprintln!("fcage: {error}");
            ExitCode::from(125)
        },
    )?;
    Ok(())
}

/// Bootstraps a Gentoo rootfs from a signed stage3, printing progress to
/// stderr.
///
/// A run is two waves where the other two layers have one of a different shape:
/// the stage3 is extracted, and then the binary packages `--gentoo-install`
/// names are resolved against the root that produced and merged into it. A
/// command line that names no package does exactly the first, which is what a
/// stage3 bootstrap has always been.
fn provision_gentoo(architecture: &str, options: &Options, rootfs: &Path) -> Result<(), ExitCode> {
    use ferroday_cage::provision::ProvisionEvent;
    use ferroday_cage::provision::gentoo::{Gentoo, Plan};

    let mut builder = Gentoo::builder(architecture);
    if let Some(variant) = &options.gentoo_variant {
        builder = builder.variant(variant);
    }
    if let Some(binhost) = &options.gentoo_binhost {
        builder = builder.binhost(binhost);
    }
    if !options.gentoo_install.is_empty() {
        builder = builder.install(&options.gentoo_install);
    }
    if !options.gentoo_prefer_use.is_empty() {
        builder = builder.prefer_use(&options.gentoo_prefer_use);
    }
    if let Some(path) = &options.gentoo_plan {
        builder = builder.plan(plan_from(path, Plan::parse_document)?);
    }
    if let Some(build_id) = &options.gentoo_build_id {
        builder = builder.build_id(build_id);
    }
    if let Some(mirror) = &options.gentoo_mirror {
        builder = builder.mirror(mirror);
    }
    for fallback in &options.gentoo_mirror_fallback {
        builder = builder.mirror_fallback(fallback);
    }
    if let Some(cache) = &options.gentoo_cache {
        builder = builder.cache_dir(cache);
    }
    if let Some(age) = options.gentoo_max_pointer_age {
        builder = builder.max_pointer_age(age.map(days));
    }

    let mut gentoo = builder.build().map_err(|error| {
        eprintln!("fcage: {error}");
        ExitCode::from(125)
    })?;
    let mut progress = |event: ProvisionEvent<'_>| {
        if let ProvisionEvent::Gentoo(event) = event {
            print_gentoo_event(event);
        }
    };
    ferroday_cage::provision::Provision::new(rootfs)
        .observe(&mut progress)
        .run(&mut gentoo)
        .map_err(|error| {
            eprintln!("fcage: {error}");
            ExitCode::from(125)
        })?;
    Ok(())
}

/// A count of days as a duration.
fn days(count: u64) -> std::time::Duration {
    std::time::Duration::from_secs(count.saturating_mul(24 * 60 * 60))
}

/// Prints one Gentoo provisioning step to stderr, as the other layers do.
fn print_gentoo_event(event: &ferroday_cage::provision::gentoo::GentooEvent<'_>) {
    use ferroday_cage::provision::gentoo::GentooEvent;
    match event {
        GentooEvent::Fetching { url, .. } => eprintln!("fcage: fetching {url}"),
        GentooEvent::Resolved { stage3, .. } => eprintln!(
            "fcage: resolved {} to build {} ({} bytes), vouched for by {}",
            stage3.variant(),
            stage3.build_id(),
            stage3.size(),
            stage3.certificate(),
        ),
        GentooEvent::Verifying { path, .. } => {
            eprintln!("fcage: verifying {}", path.display());
        }
        GentooEvent::Extracting { path, .. } => {
            eprintln!("fcage: extracting {}", path.display());
        }
        GentooEvent::Index {
            builds,
            skipped,
            generated,
            ..
        } => eprintln!(
            "fcage: the binhost index names {builds} builds{}{}",
            match skipped {
                0 => String::new(),
                skipped => format!(", {skipped} of which this layer cannot act on"),
            },
            generated.map_or_else(String::new, |at| format!(", generated at {at}")),
        ),
        GentooEvent::Planned {
            packages, bytes, ..
        } => eprintln!("fcage: installing {packages} packages ({bytes} bytes)"),
        GentooEvent::Merging {
            package, version, ..
        } => eprintln!("fcage: merging {package}-{version}"),
        GentooEvent::DependencyCycle { packages, .. } => eprintln!(
            "fcage: a runtime dependency cycle among {} was broken to order the merge",
            packages.join(", "),
        ),
        // Reported before the run fails, so a caller fixing an install list
        // sees every atom the binhost cannot answer rather than the first.
        GentooEvent::Unsatisfiable {
            atom,
            wanted_by,
            reason,
            ..
        } => eprintln!("fcage: {wanted_by} requires {atom}, and no build {reason}"),
        GentooEvent::Conflict {
            atom,
            stated_by,
            blocks,
            installed,
            ..
        } => eprintln!(
            "fcage: {stated_by} blocks {blocks} with {atom}, which {}",
            if *installed {
                "the root already has"
            } else {
                "this same resolution would install"
            },
        ),
        _ => {}
    }
}

/// Prints the stage3 variants an architecture publishes, from the signed
/// enumeration.
fn gentoo_variants(
    architecture: &str,
    mirror: Option<&str>,
    fallbacks: &[String],
    max_pointer_age: Option<Option<u64>>,
) -> ExitCode {
    use ferroday_cage::provision::gentoo::Gentoo;

    // Configured exactly as a provisioning run configures the same layer, so a
    // command line that lists an architecture's variants and one that installs
    // one of them read the same archive.
    let mut builder = Gentoo::builder(architecture);
    if let Some(mirror) = mirror {
        builder = builder.mirror(mirror);
    }
    for fallback in fallbacks {
        builder = builder.mirror_fallback(fallback);
    }
    if let Some(age) = max_pointer_age {
        builder = builder.max_pointer_age(age.map(days));
    }
    let mut gentoo = match builder.build() {
        Ok(gentoo) => gentoo,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(125);
        }
    };
    let available = match gentoo.available() {
        Ok(available) => available,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(125);
        }
    };
    // The build id belongs beside the variant rather than in a heading: a
    // sub-architecture is built on its own cadence, so one document routinely
    // points different variants at different builds.
    print_listing("the variant listing", |out| {
        for variant in available.variants() {
            let build = available.build_id(variant).unwrap_or("");
            let size = available.size(variant).unwrap_or(0);
            writeln!(out, "{variant}\t{build}\t{size}")?;
        }
        Ok(())
    })
}

/// Writes a listing to standard output, reporting a reader that stopped early as
/// the quiet ending it is.
///
/// A listing is a stream a reader is expected to walk away from —
/// `fcage --gentoo-packages amd64 | head` is the everyday case — and `println!`
/// answers that by panicking: Rust ignores `SIGPIPE`, so the write returns
/// `EPIPE` rather than the process dying of the signal, and the macro has
/// nowhere to report an error to. The command then exits 101 with a panic
/// message on stderr where a shell expected 141 and silence.
///
/// [`export_rootfs`] answers the same question in its own terms, because its
/// write goes through the library and fails as a `ProvisionError` naming what it
/// was doing — a diagnostic this could only report as a bare `io::Error`.
fn print_listing(
    subject: &str,
    records: impl FnOnce(&mut dyn std::io::Write) -> std::io::Result<()>,
) -> ExitCode {
    use std::io::Write as _;
    // Buffered, so a listing of thousands of lines is a handful of writes: the
    // records below are small and there is no reader waiting on each one.
    let mut out = std::io::BufWriter::new(std::io::stdout().lock());
    let written = records(&mut out).and_then(|()| out.flush());
    ExitCode::from(listing_status(subject, written))
}

/// What a listing exits with, given how its writes ended.
///
/// Separate from [`print_listing`] because that one owns the process's own
/// standard output, and what is worth pinning is the reading of the outcome.
fn listing_status(subject: &str, written: std::io::Result<()>) -> u8 {
    match written {
        Ok(()) => 0,
        Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => 141,
        Err(error) => {
            eprintln!("fcage: cannot write {subject}: {error}");
            125
        }
    }
}

/// Prints what the binhost publishes: every package name and its versions.
fn gentoo_packages(
    architecture: &str,
    binhost: Option<&str>,
    mirror: Option<&str>,
    fallbacks: &[String],
) -> ExitCode {
    use ferroday_cage::provision::gentoo::Gentoo;

    // Configured exactly as a provisioning run configures the same layer, so a
    // command line that lists what a binhost offers and one that installs from
    // it read the same archive.
    let mut builder = Gentoo::builder(architecture);
    if let Some(binhost) = binhost {
        builder = builder.binhost(binhost);
    }
    if let Some(mirror) = mirror {
        builder = builder.mirror(mirror);
    }
    for fallback in fallbacks {
        builder = builder.mirror_fallback(fallback);
    }
    let mut gentoo = match builder.build() {
        Ok(gentoo) => gentoo,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(125);
        }
    };
    let catalogue = match gentoo.packages() {
        Ok(catalogue) => catalogue,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(125);
        }
    };
    // One line per package, its versions after it: a name is what a caller
    // writes in an atom, and the versions are what tells them whether the one
    // they meant is on offer.
    print_listing("the package listing", |out| {
        for name in catalogue.names() {
            let versions: Vec<&str> = catalogue.versions(name).collect();
            writeln!(out, "{name}\t{}", versions.join(" "))?;
        }
        Ok(())
    })
}

/// Prints what the Gentoo root at `root` already has installed.
fn gentoo_installed(root: &Path) -> ExitCode {
    let installed = match ferroday_cage::provision::gentoo::installed(root) {
        Ok(installed) => installed,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(125);
        }
    };
    print_listing("the installed listing", |out| {
        for package in installed.packages() {
            writeln!(
                out,
                "{}-{}\t{}\t{}",
                package.name(),
                package.version(),
                package.slot(),
                package.use_flags().collect::<Vec<_>>().join(" "),
            )?;
        }
        Ok(())
    })
}

/// Prints what each certificate of the vendored Gentoo keyring can still be
/// trusted to do, and until when.
fn gentoo_keyring_horizon() -> ExitCode {
    use ferroday_cage::provision::gentoo::Gentoo;

    // The architecture is a coordinate the keyring knows nothing about, and a
    // listing reads no archive, so any well-formed one names the same keyring.
    let gentoo = match Gentoo::builder("amd64").build() {
        Ok(gentoo) => gentoo,
        Err(error) => {
            eprintln!("fcage: {error}");
            return ExitCode::from(125);
        }
    };
    let horizon = gentoo.keyring_horizon();
    print_listing("the keyring horizon", |out| {
        for held in &horizon {
            writeln!(
                out,
                "{}\t{}\t{}\t{}",
                held.fingerprint,
                if held.signs { "signs" } else { "cannot-sign" },
                held.expires
                    .map_or_else(|| "never".to_string(), |at| at.to_string()),
                held.user_id.as_deref().unwrap_or(""),
            )?;
        }
        // The number a caller acts on, and the reason the list is reported per
        // certificate: a keyring holds certificates that can vouch for nothing,
        // and their dates say nothing about how long it stays usable.
        match horizon
            .iter()
            .filter(|held| held.signs)
            .filter_map(|held| held.expires)
            .min()
        {
            Some(earliest) => writeln!(
                out,
                "earliest expiry among the certificates that can sign\t{earliest}"
            ),
            None => writeln!(out, "no certificate in the keyring can sign"),
        }
    })
}

/// Prints an Alpine bootstrap progress event to stderr.
///
/// The same shape as [`print_debian_event`], which is the point of
/// [`AlpineEvent`](ferroday_cage::provision::alpine::AlpineEvent) carrying the
/// same progress: a consumer reports one layer by changing the type it matches
/// on.
fn print_alpine_event(event: ferroday_cage::provision::alpine::AlpineEvent<'_>) {
    use ferroday_cage::provision::alpine::AlpineEvent;
    use std::io::Write;
    match event {
        AlpineEvent::Fetching { url, .. } => eprintln!("fcage: fetching {url}"),
        AlpineEvent::Resolving => eprintln!("fcage: resolving the package set"),
        AlpineEvent::Downloading {
            package,
            index,
            total,
            ..
        } => eprintln!("fcage: downloading {package} ({index}/{total})"),
        AlpineEvent::Extracting { package, .. } => eprintln!("fcage: extracting {package}"),
        AlpineEvent::Script {
            package, script, ..
        } => eprintln!("fcage: {package}: {script}"),
        // An install script's own output flows straight to stderr.
        AlpineEvent::CommandOutput { bytes, .. } => {
            let _ = std::io::stderr().write_all(bytes);
        }
        _ => {}
    }
}

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

    /// Parses an argument list given as string slices.
    fn parse_args(args: &[&str]) -> Result<Invocation, String> {
        parse(args.iter().map(OsString::from))
    }

    /// The usage error `args` produces, panicking if it is accepted instead.
    fn parse_error(args: &[&str]) -> String {
        match parse_args(args) {
            Err(message) => message,
            Ok(_) => panic!("{args:?} should be refused"),
        }
    }

    #[test]
    fn every_kind_of_caller_mount_claims_the_resolv_conf_target() {
        // Asserted against the predicate rather than through
        // `compose_netstack_resolv_conf`, which reads the host's own
        // `resolv.conf` and composes nothing when its nameservers are all on
        // loopback -- so a test driven through it would pass on a
        // systemd-resolved host whatever the predicate answered.
        for claimed in [
            Cage::builder().bind_ro("/etc/hosts", "/etc/resolv.conf"),
            // Written the way `Path`'s component comparison normalizes.
            Cage::builder().bind_ro("/etc/hosts", "/etc/./resolv.conf"),
            // A bind spelled through the raw escape hatch: a source and the
            // kernel's own `MS_BIND`.
            Cage::builder().raw_mount(
                RawMount::new("/etc/resolv.conf")
                    .source("/etc/hosts")
                    .flags(0x1000),
            ),
            // A raw mount of any other kind still claims the target.
            Cage::builder().raw_mount(RawMount::new("/etc/resolv.conf").fstype("tmpfs")),
        ] {
            assert!(
                mounts_resolv_conf(&claimed),
                "a caller's own mount at the target must be left in force",
            );
        }

        // A mount elsewhere leaves the composed bind to be made.
        assert!(!mounts_resolv_conf(
            &Cage::builder().bind_ro("/etc/hosts", "/etc/hosts")
        ));
        assert!(!mounts_resolv_conf(&Cage::builder()));
    }

    #[test]
    fn a_misspelled_flag_suggests_the_one_it_was_meant_to_be() {
        // With this many flags, several sharing long prefixes, a report that
        // says only that an option is unrecognized leaves the reader to find
        // the difference by eye.
        for (typed, meant) in [
            ("--rootsf", "--rootfs"),
            ("--seccomp-alow", "--seccomp-allow"),
            ("--no-prc", "--no-proc"),
            ("--bnid", "--bind"),
            ("--debian-includ", "--debian-include"),
            // A flag typed short: too far in edit distance on a long name,
            // caught by the prefix rule instead.
            ("--netstack-host-loop", "--netstack-host-loopback"),
            // A counterpart named only in the closing prose is still offered,
            // because the candidates come from the whole help text.
            ("--managed-mount", "--managed-mounts"),
        ] {
            let error = parse_error(&[typed]);
            assert!(
                error.contains(&format!("Try 'fcage {meant}'.")),
                "{typed} should have suggested {meant}, got {error:?}",
            );
            assert!(error.contains(typed), "the report drops what was typed");
        }
    }

    #[test]
    fn a_joined_value_does_not_hide_the_flag_it_misspells() {
        // `--flag=value` names its flag before the `=`. Weighing the whole
        // argument against the roster compares a value against flag names and
        // finds nothing near, so the one form of an option draws a suggestion
        // and the other does not.
        let error = parse_error(&["--rootsf=/srv/alpine"]);
        assert!(
            error.contains("Try 'fcage --rootfs'."),
            "the joined form drew no suggestion: {error:?}",
        );
    }

    #[test]
    fn an_option_of_another_mode_names_that_mode() {
        // The candidates come from the whole help, which documents every mode,
        // so a launch would otherwise answer `--export-to` with `--export-to`.
        for typed in ["--export-to", "--export-to=out.tar", "--clamp-mtime"] {
            let error = parse_error(&["--rootfs", "/srv/alpine", typed, "/bin/sh"]);
            assert!(
                error.contains("is an option of --export-rootfs"),
                "{typed} was not attributed to its mode: {error:?}",
            );
            assert!(
                !error.contains("Try 'fcage --export-to'."),
                "{typed} was answered with the spelling just refused: {error:?}",
            );
        }
    }

    #[test]
    fn a_mode_suggests_a_misspelling_of_its_own_vocabulary() {
        // A mode's parser refuses everything but its own options, so without
        // this a misspelling of one of them reads as a launch flag given to the
        // wrong invocation.
        let error = parse_error(&["--export-rootfs", "/roots/a", "--clamp-mtme", "5"]);
        assert!(
            error.contains("Try 'fcage --clamp-mtime'."),
            "the export mode did not answer its own misspelling: {error:?}",
        );
        let error = parse_error(&["--remove-rootfs", "/roots/a", "--identity-mp", "single"]);
        assert!(
            error.contains("Try 'fcage --identity-map'."),
            "the removal mode did not answer its own misspelling: {error:?}",
        );
        // A launch flag is still the conflict it is, not a near miss.
        let error = parse_error(&["--remove-rootfs", "/roots/a", "--hostname", "box"]);
        assert!(
            error.contains("cannot be used with --remove-rootfs"),
            "a launch flag stopped reading as a conflict: {error:?}",
        );
    }

    #[test]
    fn a_commands_own_flags_do_not_choose_the_mode() {
        // Past `--` every argument belongs to the command, including one spelled
        // like a mode of fcage's. Scanning the whole vector for a mode flag
        // makes a tool with an --export-rootfs option of its own unrunnable.
        let invocation = parse_args(&[
            "--rootfs",
            "/srv/alpine",
            "--",
            "/bin/mytool",
            "--export-rootfs",
            "/tmp/out",
        ])
        .expect("the launch parses");
        let Invocation::Run(options) = invocation else {
            panic!("the invocation is a launch, not a mode");
        };
        assert_eq!(
            options.command_line,
            ["/bin/mytool", "--export-rootfs", "/tmp/out"],
        );
    }

    #[test]
    fn a_commands_own_flags_do_not_choose_the_mode_without_a_separator() {
        // `--` is optional, and the synopsis says so: the command is the first
        // argument that is neither an option nor the value of one, and
        // everything after it is the command's. A pre-scan that stopped only at
        // `--` read a mode flag out of the command's own arguments, ran the
        // mode's parser, and reported the launch flag it then met as the
        // problem -- blaming --rootfs for an export nobody asked for.
        let invocation = parse_args(&[
            "--rootfs",
            "/srv/alpine",
            "/bin/mytool",
            "--export-rootfs",
            "/tmp/out",
        ])
        .expect("the launch parses");
        let Invocation::Run(options) = invocation else {
            panic!("the invocation is a launch, not a mode");
        };
        assert_eq!(
            options.command_line,
            ["/bin/mytool", "--export-rootfs", "/tmp/out"],
        );
    }

    #[test]
    fn a_mode_flag_after_another_flags_value_still_chooses_the_mode() {
        // The other half of the same rule: a flag's value is not the command,
        // so the walk goes past it. Reading `/tmp/out` as the command would
        // stop the scan before it reached the flag that selects the mode.
        let invocation = parse_args(&["--export-to", "/tmp/out", "--export-rootfs", "/roots/a"])
            .expect("the export parses");
        assert!(
            matches!(invocation, Invocation::Export { .. }),
            "the invocation is an export",
        );
    }

    #[test]
    fn a_two_value_flag_does_not_hide_the_command() {
        // A pair counts as two, so the argument after them is the command
        // rather than the second half of the pair.
        let invocation = parse_args(&["--rootfs", "/srv/a", "--setenv", "K", "V", "/bin/sh"])
            .expect("the launch parses");
        let Invocation::Run(options) = invocation else {
            panic!("the invocation is a launch, not a mode");
        };
        assert_eq!(options.command_line, ["/bin/sh"]);
        assert_eq!(options.setenv.len(), 1);
    }

    #[test]
    fn the_export_only_roster_holds_only_export_options() {
        // The roster is the table's `mode`, so this is what keeps that honest:
        // every flag it calls an export's must be one a launch refuses and an
        // export accepts, or the suggester attributes a flag to the wrong mode.
        let export_only: Vec<&str> = FLAGS
            .iter()
            .filter(|flag| flag.mode == Mode::Export && !flag.selects)
            .map(|flag| flag.long)
            .collect();
        assert!(!export_only.is_empty(), "the roster is not empty");
        for flag in export_only {
            let launch = parse_error(&["--rootfs", "/srv/alpine", flag, "/bin/sh"]);
            assert!(
                launch.contains("unrecognized option"),
                "a launch accepts {flag}, which the roster calls an export's: {launch:?}",
            );
            let export = parse_args(&["--export-rootfs", "/roots/a", flag, "1700000000"]);
            assert!(
                export.is_ok(),
                "an export refuses {flag}, which the roster calls its own: {:?}",
                export.err(),
            );
        }
    }

    #[test]
    fn a_provision_and_exit_run_refuses_a_launch_flag() {
        // Nothing is launched, so a launch flag has nothing to configure. The
        // parser refuses every other no-effect combination; dropping this one
        // would leave a caller believing a sandbox was shaped as written.
        let error = parse_error(&[
            "--rootfs",
            "/roots/trixie",
            "--provision-debian",
            "trixie",
            "--hostname",
            "box",
        ]);
        assert!(
            error.contains("--hostname configures a launch"),
            "the dropped flag went unreported: {error:?}",
        );
        // The provisioning vocabulary itself is accepted, and so is anything at
        // all once a command is given.
        assert!(
            parse_args(&[
                "--rootfs",
                "/roots/trixie",
                "--provision-debian",
                "trixie",
                "--debian-arch",
                "amd64",
            ])
            .is_ok()
        );
        assert!(
            parse_args(&[
                "--rootfs",
                "/roots/trixie",
                "--provision-debian",
                "trixie",
                "--hostname",
                "box",
                "/bin/sh",
            ])
            .is_ok()
        );
        // A trailing separator with nothing after it names no launch setting:
        // it introduces a command line rather than configuring one, and the run
        // it ends is the provisioning run it was already.
        assert!(
            parse_args(&[
                "--rootfs",
                "/roots/trixie",
                "--provision-debian",
                "trixie",
                "--"
            ])
            .is_ok()
        );
    }

    /// The options of a parsed invocation, or a panic naming what went wrong.
    fn run_options(args: &[&str]) -> Box<Options> {
        match parse_args(args) {
            Ok(Invocation::Run(options)) => options,
            Ok(_) => panic!("{args:?} should parse as a run"),
            Err(error) => panic!("{args:?} should parse: {error}"),
        }
    }

    #[test]
    fn the_alpine_options_reach_the_builder_they_mirror() {
        let options = run_options(&[
            "--rootfs",
            "/roots/alpine",
            "--provision-alpine",
            "v3.23",
            "--alpine-arch",
            "aarch64",
            "--alpine-include",
            "build-base,git",
            "--alpine-include",
            "curl",
            "--alpine-exclude",
            "docs",
            "--alpine-components",
            "main,community",
            "--alpine-cache",
            "/var/cache/apk",
            "--alpine-extract-only",
        ]);
        assert_eq!(options.provision_alpine.as_deref(), Some("v3.23"));
        assert_eq!(options.alpine_arch.as_deref(), Some("aarch64"));
        // Repeatable and comma-separated, as the Debian list flags are.
        assert_eq!(options.alpine_include, ["build-base", "git", "curl"]);
        assert_eq!(options.alpine_exclude, ["docs"]);
        assert_eq!(options.alpine_components, ["main", "community"]);
        assert!(options.alpine_extract_only);
    }

    #[test]
    fn every_userland_takes_a_plan_document_the_same_way() {
        // A plan replaces a resolution and a pin constrains one, and both are
        // documents a previous resolution wrote. Gentoo has taken a plan since
        // it gained one; Debian and Alpine take both, so a reproducible install
        // is expressible at a prompt for each of the three formats and not only
        // from a program.
        let options = run_options(&[
            "--rootfs",
            "/roots/trixie",
            "--provision-debian",
            "trixie",
            "--debian-plan",
            "/plans/trixie.plan",
            "--debian-pin",
            "/plans/trixie.pin",
        ]);
        assert_eq!(
            options.debian_plan.as_deref(),
            Some(Path::new("/plans/trixie.plan"))
        );
        assert_eq!(
            options.debian_pin.as_deref(),
            Some(Path::new("/plans/trixie.pin"))
        );

        let options = run_options(&[
            "--rootfs",
            "/roots/alpine",
            "--provision-alpine",
            "v3.23",
            "--alpine-plan",
            "/plans/alpine.plan",
            "--alpine-pin",
            "/plans/alpine.pin",
        ]);
        assert_eq!(
            options.alpine_plan.as_deref(),
            Some(Path::new("/plans/alpine.plan"))
        );
        assert_eq!(
            options.alpine_pin.as_deref(),
            Some(Path::new("/plans/alpine.pin"))
        );

        // And each belongs to its own provisioner, as the rest of its family
        // does.
        for flag in ["--debian-plan", "--debian-pin"] {
            let error = parse_error(&["--rootfs", "/roots/r", flag, "/plans/p"]);
            assert!(
                error.contains("require --provision-debian"),
                "{flag}: {error:?}",
            );
        }
        for flag in ["--alpine-plan", "--alpine-pin"] {
            let error = parse_error(&["--rootfs", "/roots/r", flag, "/plans/p"]);
            assert!(
                error.contains("require --provision-alpine"),
                "{flag}: {error:?}",
            );
        }
    }

    #[test]
    fn an_overlay_repository_is_spelled_by_naming_no_components() {
        // postmarketOS's layout, which is the whole of what the flag has to
        // express that the Debian one does not.
        let options = run_options(&[
            "--rootfs",
            "/roots/alpine",
            "--provision-alpine",
            "v3.23",
            "--alpine-repository",
            "release=v26.06 mirror=http://mirror.invalid/pmos keys=postmarketos",
        ]);
        let [overlay] = &options.alpine_repositories[..] else {
            panic!(
                "one repository was given: {:?}",
                options.alpine_repositories
            );
        };
        assert_eq!(overlay.release, "v26.06");
        assert_eq!(
            overlay.mirror.as_deref(),
            Some("http://mirror.invalid/pmos")
        );
        assert!(overlay.fallbacks.is_empty());
        assert!(overlay.components.is_empty(), "the shallower layout");
        assert_eq!(overlay.keys, AlpineKeys::PostmarketOs);
    }

    #[test]
    fn a_repository_spec_states_one_primary_mirror_and_names_it_mirror() {
        // A repository's primary mirror is written into the finished root, so a
        // spec that promoted a backstop would leave that root permanently
        // fetching from what the caller meant as a fetch-time backstop, and one
        // that demoted a repeated mirror= would quietly reorder the walk.
        for (flag, spec) in [
            (
                "--alpine-repository",
                "release=v26.06 keys=postmarketos mirror-fallback=http://backstop.invalid",
            ),
            (
                "--debian-repository",
                "suite=trixie mirror-fallback=http://backstop.invalid",
            ),
        ] {
            let error = parse_error(&[
                "--rootfs",
                "/roots/r",
                "--provision-alpine",
                "v3.23",
                flag,
                spec,
            ]);
            assert!(error.contains("mirror-fallback="), "{flag}: {error}");
            assert!(error.contains("was not given"), "{flag}: {error}");
        }

        for (flag, spec) in [
            (
                "--alpine-repository",
                "release=v26.06 keys=postmarketos mirror=http://one.invalid \
                 mirror=http://two.invalid",
            ),
            (
                "--debian-repository",
                "suite=trixie mirror=http://one.invalid mirror=http://two.invalid",
            ),
        ] {
            let error = parse_error(&[
                "--rootfs",
                "/roots/r",
                "--provision-alpine",
                "v3.23",
                flag,
                spec,
            ]);
            assert!(error.contains("given twice"), "{flag}: {error}");
        }
    }

    #[test]
    fn a_repository_without_keys_is_refused_where_it_is_written() {
        // An additional repository has no default trust anchor, so the refusal
        // belongs at the flag rather than at the first signature it cannot
        // check.
        let error = parse_error(&[
            "--rootfs",
            "/roots/alpine",
            "--provision-alpine",
            "v3.23",
            "--alpine-repository",
            "release=v26.06 mirror=http://mirror.invalid/pmos",
        ]);
        assert!(error.contains("keys="), "{error}");

        let error = parse_error(&[
            "--rootfs",
            "/roots/alpine",
            "--provision-alpine",
            "v3.23",
            "--alpine-repository",
            "release=v26.06 mirror=http://mirror.invalid/pmos keys=alpine suite=trixie",
        ]);
        assert!(
            error.contains("suite"),
            "an unknown field is named: {error}"
        );
    }

    #[test]
    fn the_gentoo_binhost_options_reach_the_builder_they_mirror() {
        let options = run_options(&[
            "--rootfs",
            "/roots/gentoo",
            "--provision-gentoo",
            "amd64",
            "--gentoo-variant",
            "amd64-openrc",
            "--gentoo-binhost",
            "x86-64",
            "--gentoo-install",
            "dev-vcs/git[keyring]",
            "--gentoo-install=app-editors/vim",
            // Space-separated, because a caller states a taste as a list
            // rather than one flag at a time.
            "--gentoo-prefer-use",
            "-X gtk",
            "--gentoo-prefer-use=keyring",
            "--gentoo-plan",
            "/plans/binhost.plan",
        ]);
        assert_eq!(options.gentoo_binhost.as_deref(), Some("x86-64"));
        assert_eq!(
            options.gentoo_install,
            ["dev-vcs/git[keyring]", "app-editors/vim"],
        );
        assert_eq!(options.gentoo_prefer_use, ["-X", "gtk", "keyring"]);
        assert_eq!(
            options.gentoo_plan.as_deref(),
            Some(Path::new("/plans/binhost.plan")),
        );
    }

    #[test]
    fn the_gentoo_binhost_listings_are_modes_of_their_own() {
        // Each reads and exits, so each parses on its own and refuses a flag
        // that configures a launch it will not perform.
        match parse_args(&["--gentoo-packages", "amd64", "--gentoo-binhost", "x86-64"])
            .expect("the listing parses")
        {
            Invocation::GentooPackages {
                architecture,
                binhost,
                ..
            } => {
                assert_eq!(architecture, "amd64");
                assert_eq!(binhost.as_deref(), Some("x86-64"));
            }
            _ => panic!("expected a binhost listing"),
        }
        match parse_args(&["--gentoo-installed=/roots/gentoo"]).expect("the listing parses") {
            Invocation::GentooInstalled { root } => assert_eq!(root, Path::new("/roots/gentoo")),
            _ => panic!("expected an installed listing"),
        }
        // A flag belonging to a launch is a conflict rather than something the
        // listing quietly ignores.
        let error = parse_error(&["--gentoo-packages", "amd64", "--rootfs", "/roots/x"]);
        assert!(error.contains("--gentoo-packages"), "{error}");
        let error = parse_error(&["--gentoo-installed", "/roots/x", "--gentoo-mirror", "u"]);
        assert!(error.contains("--gentoo-installed"), "{error}");
        // And each requires its value.
        assert!(parse_error(&["--gentoo-installed"]).contains("requires a value"));
    }

    #[test]
    fn the_gentoo_options_reach_the_builder_they_mirror() {
        let options = run_options(&[
            "--rootfs",
            "/roots/gentoo",
            "--provision-gentoo",
            "amd64",
            "--gentoo-variant",
            "amd64-hardened-openrc",
            "--gentoo-build-id",
            "20260810T204554Z",
            "--gentoo-mirror",
            "http://mirror.invalid/gentoo",
            "--gentoo-mirror-fallback",
            "http://backup.invalid/gentoo",
            "--gentoo-cache",
            "/var/cache/stage3",
            "--gentoo-max-pointer-age",
            "7",
        ]);
        // The architecture is the coordinate here rather than a release, since
        // Gentoo publishes one autobuilds tree per architecture and no suite.
        assert_eq!(options.provision_gentoo.as_deref(), Some("amd64"));
        assert_eq!(
            options.gentoo_variant.as_deref(),
            Some("amd64-hardened-openrc"),
        );
        assert_eq!(options.gentoo_build_id.as_deref(), Some("20260810T204554Z"));
        assert_eq!(
            options.gentoo_mirror.as_deref(),
            Some("http://mirror.invalid/gentoo"),
        );
        assert_eq!(
            options.gentoo_mirror_fallback,
            ["http://backup.invalid/gentoo"],
        );
        assert_eq!(options.gentoo_max_pointer_age, Some(Some(7)));

        // The bound is cleared by a word rather than by a number, since no
        // number means "no bound" and a very large one is not the same request.
        let cleared = run_options(&[
            "--rootfs",
            "/roots/gentoo",
            "--provision-gentoo",
            "amd64",
            "--gentoo-variant=amd64-openrc",
            "--gentoo-max-pointer-age=none",
        ]);
        assert_eq!(cleared.gentoo_max_pointer_age, Some(None));
        assert_eq!(cleared.gentoo_variant.as_deref(), Some("amd64-openrc"));

        let error = parse_error(&[
            "--rootfs",
            "/roots/gentoo",
            "--provision-gentoo",
            "amd64",
            "--gentoo-variant",
            "amd64-openrc",
            "--gentoo-max-pointer-age",
            "a-while",
        ]);
        assert!(error.contains("number of days or 'none'"), "{error}");
    }

    #[test]
    fn a_gentoo_bootstrap_names_the_variant_it_installs() {
        // The archive publishes twenty-one stage3s for amd64 alone with no
        // default among them, so the refusal belongs at the command line rather
        // than after two archive fetches.
        let error = parse_error(&["--rootfs", "/roots/gentoo", "--provision-gentoo", "amd64"]);
        assert!(error.contains("--gentoo-variant"), "{error}");
        assert!(error.contains("--gentoo-variants"), "{error}");
    }

    #[test]
    fn the_gentoo_listings_are_modes_of_their_own() {
        // Each reads and prints rather than launching anything, so each takes
        // its own vocabulary and refuses every launch flag -- the shape a
        // removal and an export already have.
        match parse_args(&[
            "--gentoo-variants",
            "arm64",
            "--gentoo-mirror",
            "http://mirror.invalid/gentoo",
            "--gentoo-mirror-fallback=http://backup.invalid/gentoo",
            "--gentoo-max-pointer-age=none",
        ])
        .expect("the listing parses")
        {
            Invocation::GentooVariants {
                architecture,
                mirror,
                fallbacks,
                max_pointer_age,
            } => {
                assert_eq!(architecture, "arm64");
                assert_eq!(mirror.as_deref(), Some("http://mirror.invalid/gentoo"));
                assert_eq!(fallbacks, ["http://backup.invalid/gentoo"]);
                assert_eq!(max_pointer_age, Some(None));
            }
            _ => panic!("expected a variant listing"),
        }

        // The two flags mean here what they mean on a provisioning command
        // line, which is what keeps one command line from reading an archive
        // the other would not. A backstop given alone backs the default archive
        // rather than replacing it, so nothing names the primary here.
        let listing = |args: &[&str]| match parse_args(args).expect("the listing parses") {
            Invocation::GentooVariants {
                mirror, fallbacks, ..
            } => (mirror, fallbacks),
            _ => panic!("expected a variant listing"),
        };
        assert_eq!(
            listing(&[
                "--gentoo-variants",
                "amd64",
                "--gentoo-mirror-fallback",
                "http://backup.invalid/gentoo",
            ]),
            (None, vec!["http://backup.invalid/gentoo".to_string()]),
        );
        // Repeating one flag takes the last value, as it does everywhere else
        // in the tool.
        assert_eq!(
            listing(&[
                "--gentoo-variants",
                "amd64",
                "--gentoo-mirror",
                "http://a.invalid",
                "--gentoo-mirror",
                "http://b.invalid",
            ]),
            (Some("http://b.invalid".to_string()), Vec::new()),
        );

        assert!(matches!(
            parse_args(&["--gentoo-keyring-horizon"]).expect("the horizon parses"),
            Invocation::GentooKeyring,
        ));

        // A launch flag alongside either is a usage error rather than a setting
        // with no effect.
        let error = parse_error(&["--gentoo-variants", "amd64", "--rootfs", "/roots/gentoo"]);
        assert!(error.contains("--rootfs"), "{error}");
        let error = parse_error(&["--gentoo-keyring-horizon", "--gentoo-mirror", "http://x"]);
        assert!(error.contains("--gentoo-mirror"), "{error}");
    }

    #[test]
    fn the_provisioners_are_mutually_exclusive_and_need_a_destination() {
        // One rootfs is provisioned one way. Every flag the refusal enumerates
        // is exercised, so a provisioner added to the list without being added
        // to the check fails here rather than in a caller's hands.
        let error = parse_error(&[
            "--rootfs",
            "/roots/mixed",
            "--provision-debian",
            "trixie",
            "--provision-alpine",
            "v3.23",
        ]);
        assert!(
            error.contains("--provision-debian and --provision-alpine"),
            "{error}",
        );
        let error = parse_error(&[
            "--rootfs",
            "/roots/mixed",
            "--provision-tar",
            "rootfs.tar",
            "--provision-gentoo",
            "amd64",
        ]);
        assert!(
            error.contains("--provision-tar and --provision-gentoo"),
            "{error}",
        );

        // And each of them names the destination it writes to. Alone, that is
        // the general refusal every command line without somewhere to run
        // meets; alongside a profile, which does say where the launch runs, it
        // is the provisioner's own -- and for the Gentoo one that refusal is
        // what makes the variant refusal reachable only where a destination was
        // named.
        for provisioner in [
            ["--provision-tar", "rootfs.tar"],
            ["--provision-debian", "trixie"],
            ["--provision-alpine", "v3.23"],
            ["--provision-gentoo", "amd64"],
        ] {
            let error = parse_error(&provisioner);
            assert!(error.contains("--rootfs"), "{provisioner:?}: {error}");

            let error = parse_error(&[
                "--profile",
                "/etc/fcage/profile.toml",
                provisioner[0],
                provisioner[1],
            ]);
            assert_eq!(
                error,
                format!(
                    "{} requires --rootfs to name the destination",
                    provisioner[0]
                ),
            );
        }
    }

    #[test]
    fn the_alpine_options_require_the_provisioner_they_configure() {
        let error = parse_error(&[
            "--rootfs",
            "/roots/alpine",
            "--alpine-include",
            "build-base",
            "/bin/sh",
        ]);
        assert!(
            error.contains("the --alpine-* options require --provision-alpine"),
            "{error}",
        );
    }

    #[test]
    fn the_gentoo_options_require_the_provisioner_they_configure() {
        let error = parse_error(&[
            "--rootfs",
            "/roots/gentoo",
            "--gentoo-variant",
            "amd64-openrc",
            "/bin/sh",
        ]);
        assert!(
            error.contains("the --gentoo-* options require --provision-gentoo"),
            "{error}",
        );
    }

    #[test]
    fn a_mode_answers_help_rather_than_taking_it_as_a_path() {
        // `--remove-rootfs` takes the next argument, so without an answer up
        // front `fcage --remove-rootfs --help` deletes a directory named
        // `--help` — or, finding none, exits 0 having printed nothing.
        for args in [
            ["--remove-rootfs", "--help"].as_slice(),
            ["--export-rootfs", "--help"].as_slice(),
            ["--remove-rootfs", "/roots/a", "--help"].as_slice(),
        ] {
            assert!(
                matches!(parse_args(args), Ok(Invocation::Help)),
                "{args:?} did not ask for help",
            );
        }
        assert!(matches!(
            parse_args(&["--export-rootfs", "--version"]),
            Ok(Invocation::Version)
        ));
    }

    #[test]
    fn the_sandbox_is_tied_to_fcage_unless_the_run_says_otherwise() {
        // fcage waits for the command and exits with it, so a sandbox that
        // outlived the process is never what was meant: a SIGTERM to fcage —
        // `timeout(1)` is the everyday source — would otherwise orphan it.
        //
        // The parse records only what the command line said, so that a profile
        // can be the thing that answers; the default is applied where the
        // profile is known.
        let options = parse_run(&["--rootfs", "/srv/alpine", "/bin/true"]).expect("it parses");
        assert_eq!(options.stop_with_caller, None);
        assert_eq!(
            stop_with_caller_default(options.stop_with_caller, false),
            Some(true)
        );
        let options = parse_run(&[
            "--rootfs",
            "/srv/alpine",
            "--no-stop-with-caller",
            "/bin/true",
        ])
        .expect("it parses");
        assert_eq!(options.stop_with_caller, Some(false));
        assert_eq!(
            stop_with_caller_default(options.stop_with_caller, false),
            Some(false),
        );
    }

    #[test]
    fn a_listing_whose_reader_stops_early_ends_quietly() {
        // Rust ignores SIGPIPE, so a write to a closed pipe returns EPIPE
        // rather than killing the process -- and `println!` panicked on it,
        // ending a listing at exit 101 with a panic message where a shell
        // expected 141 and silence. `fcage --gentoo-packages amd64 | head` is
        // the everyday case.
        assert_eq!(
            listing_status("a listing", Err(std::io::ErrorKind::BrokenPipe.into())),
            141,
        );
        // Any other write failure is a real one and says so.
        assert_eq!(
            listing_status("a listing", Err(std::io::ErrorKind::StorageFull.into())),
            125,
        );
        assert_eq!(listing_status("a listing", Ok(())), 0);
    }

    #[test]
    fn a_profiles_caller_tie_is_reachable_through_fcage() {
        // A default is not a setting. Seeding the option with fcage's own made
        // every run state the tie, so a profile's `stop-with-caller = false`
        // was overridden by a value its author never wrote and the documented
        // key could not be reached through fcage at all.
        assert_eq!(stop_with_caller_default(None, true), None);
        // A flag still wins over the profile, in both directions.
        assert_eq!(stop_with_caller_default(Some(false), true), Some(false));
        assert_eq!(stop_with_caller_default(Some(true), true), Some(true));

        // And the profile is read for the key, which is what tells "the
        // profile said so" from "nothing said".
        let dir = ferroday_cage_testkit::scratch::scratch_dir("fcage-profile-tie");
        let stated = dir.join("stated.toml");
        std::fs::write(
            &stated,
            "rootfs = \"/tmp\"\ncommand = \"/bin/true\"\nstop-with-caller = false\n",
        )
        .expect("the profile is written");
        let (_, meta) = load_profile(&stated, false, false).expect("the profile loads");
        assert!(meta.sets_stop_with_caller);

        let silent = dir.join("silent.toml");
        std::fs::write(&silent, "rootfs = \"/tmp\"\ncommand = \"/bin/true\"\n")
            .expect("the profile is written");
        let (_, meta) = load_profile(&silent, false, false).expect("the profile loads");
        assert!(!meta.sets_stop_with_caller);
    }

    #[test]
    fn a_string_resembling_no_flag_is_reported_without_a_guess() {
        // A suggestion is worth having only where it is likely to be right.
        for typed in ["--qqqzzz", "--", "-x", "--wildly-unlike-anything"] {
            let error = parse_error(&[typed]);
            assert!(
                !error.contains("Try 'fcage --"),
                "{typed} drew a suggestion out of nothing: {error:?}",
            );
        }
        // The mode parsers ask the same question of their own vocabularies, and
        // a run of dashes is every flag's prefix: the abbreviation rule would
        // otherwise answer a bare `--` with whichever flag sorts first.
        for typed in ["--", "-", "---"] {
            assert_eq!(
                nearest_flag(typed, &["--identity-map", "--remove-rootfs"]),
                None
            );
            let error = parse_error(&["--remove-rootfs=/roots/a", typed]);
            assert!(
                !error.contains("Try 'fcage --"),
                "{typed} drew a suggestion out of nothing: {error:?}",
            );
        }
        // And a flag genuinely typed short still draws one.
        assert_eq!(
            nearest_flag("--remove", &["--identity-map", "--remove-rootfs"]),
            Some("--remove-rootfs"),
        );
    }

    #[test]
    fn an_alpine_key_set_that_names_nothing_is_a_usage_error() {
        // Read as a path, an empty selector names the working directory: the
        // run then ends at an io failure about a directory the caller never
        // typed, exit 125, rather than at the usage error it is.
        let error = parse_error(&[
            "--rootfs",
            "/r",
            "--alpine-repository",
            "release=v3.23 mirror=https://dl-cdn.alpinelinux.org/alpine keys=",
            "/bin/true",
        ]);
        assert!(error.contains("names no key set"), "{error}");
        // The three forms it does take still parse.
        assert_eq!(
            parse_alpine_keys("--flag", "alpine"),
            Ok(AlpineKeys::Alpine)
        );
        assert_eq!(
            parse_alpine_keys("--flag", "postmarketos"),
            Ok(AlpineKeys::PostmarketOs)
        );
        assert_eq!(
            parse_alpine_keys("--flag", "keys"),
            Ok(AlpineKeys::Dir(PathBuf::from("keys")))
        );
    }

    #[test]
    fn every_flag_the_parser_accepts_is_in_the_help() {
        // The parser's vocabulary and the help's contents are one list, so
        // most of what this used to check is now unwritable. What is left is
        // the flags the help documents in prose rather than as an entry: the
        // counterpart toggles, each named in the closing paragraphs. A flag
        // filed there and then forgotten in the prose is documented nowhere,
        // and the suggester could never offer it.
        let usage = usage();
        for flag in FLAGS {
            if flag.section != Section::Counterpart {
                // Rendered from the table, so its presence is not a question.
                assert!(
                    usage.contains(&format!("  {}", flag.spelled())),
                    "the help does not list {}, which is not a prose entry",
                    flag.long,
                );
                continue;
            }
            assert!(
                usage.contains(flag.long),
                "the parser accepts {}, which --help never names",
                flag.long,
            );
        }
    }

    #[test]
    fn every_flag_the_help_names_in_prose_is_one_the_parser_accepts() {
        // The other direction over the same prose, and what keeps the closing
        // paragraphs from naming a flag that no longer exists. The entries
        // themselves come from the table and cannot.
        let usage = usage();
        let prose = usage
            .split_once("Each toggle")
            .expect("the closing prose")
            .1;
        for token in prose.split_whitespace() {
            let name = token.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-');
            if !name.starts_with("--") || name.len() <= 2 || name.ends_with('-') {
                continue;
            }
            assert!(
                FLAGS.iter().any(|flag| flag.long == name),
                "the closing prose names {name}, which no flag is",
            );
        }
    }

    #[test]
    fn every_flag_the_help_names_is_one_the_parser_accepts() {
        // A flag is offered to each mode's vocabulary in turn, since some
        // belong to one mode only -- `--clamp-mtime` is an export's -- and
        // trying all of them is what covers the whole table.
        for flag in FLAGS {
            if matches!(flag.mode, Mode::Help | Mode::Version) {
                continue;
            }
            let long = flag.long;
            let vocabularies: [Vec<&str>; 3] = [
                vec![long],
                vec!["--remove-rootfs", "/roots/a", long],
                vec!["--export-rootfs", "/roots/a", long],
            ];
            let recognized = vocabularies.iter().any(|args| match parse_args(args) {
                // A flag needing a value reports that, which is recognition.
                // Only being unknown, or belonging to another mode, is not.
                Err(error) => {
                    !error.contains("unrecognized option") && !error.contains("cannot be used with")
                }
                Ok(_) => true,
            });
            assert!(
                recognized,
                "the table holds {long}, which no mode's parser accepts",
            );
        }
    }

    #[test]
    fn the_help_files_every_option_under_a_section() {
        // The options are already ordered by subject; the sections name the
        // groups that ordering makes. An entry above the first header, or
        // after a header that no longer exists, is one a reader has to find by
        // scanning the whole list.
        let usage = usage();
        let mut section: Option<&str> = None;
        for line in usage.lines() {
            if line.ends_with(':') && !line.starts_with(' ') && !line.starts_with("Usage") {
                section = Some(line);
            } else if line.starts_with("  -") {
                assert!(
                    section.is_some(),
                    "the option {line:?} sits above the first section header",
                );
            }
        }
        // The groups themselves, so a section lost in an edit is caught rather
        // than silently folding its options into the one before it.
        for header in [
            "Provisioning the root filesystem:",
            "Profiles, overlays, and mounts:",
            "Identity and limits:",
            "The command and its process:",
            "Networking:",
            "Hardening:",
            "Turning off what is on by default:",
            "Help and version:",
        ] {
            assert!(
                usage.contains(header),
                "the help lost the section {header:?}"
            );
        }
    }

    #[test]
    fn edit_distance_counts_single_character_edits() {
        assert_eq!(edit_distance("", ""), 0);
        assert_eq!(edit_distance("--rootfs", "--rootfs"), 0);
        // One substitution, one deletion, one insertion.
        assert_eq!(edit_distance("--rootfs", "--roatfs"), 1);
        assert_eq!(edit_distance("--rootfs", "--rootf"), 1);
        assert_eq!(edit_distance("--rootfs", "--rootfss"), 1);
        // A transposition costs two: the distance does not model a swap, which
        // is why two is the bound worth offering a suggestion at.
        assert_eq!(edit_distance("--rootfs", "--rootsf"), 2);
        // Against an empty string the distance is the length, from either
        // side, so the two rows are indexed the same way round.
        assert_eq!(edit_distance("--bind", ""), 6);
        assert_eq!(edit_distance("", "--bind"), 6);
    }

    #[test]
    fn remove_rootfs_takes_a_destination_in_either_form() {
        for args in [
            ["--remove-rootfs", "/var/lib/roots/trixie"].as_slice(),
            ["--remove-rootfs=/var/lib/roots/trixie"].as_slice(),
        ] {
            match parse_args(args).expect("the removal should parse") {
                Invocation::Remove { dest, map } => {
                    assert_eq!(dest, PathBuf::from("/var/lib/roots/trixie"));
                    assert_eq!(
                        map,
                        IdentityMap::Subordinate,
                        "the default is the map a bundled-delegate sandbox writes under"
                    );
                }
                _ => panic!("expected a removal for {args:?}"),
            }
        }
    }

    #[test]
    fn remove_rootfs_takes_the_identity_map_the_tree_was_written_under() {
        // A tree provisioned under the single-identity map is removed under it
        // too, whichever side of the destination the flag appears on.
        for args in [
            ["--identity-map", "single", "--remove-rootfs", "/roots/a"].as_slice(),
            ["--remove-rootfs", "/roots/a", "--identity-map=single"].as_slice(),
        ] {
            match parse_args(args).expect("the removal should parse") {
                Invocation::Remove { map, .. } => assert_eq!(map, IdentityMap::Single),
                _ => panic!("expected a removal for {args:?}"),
            }
        }
    }

    #[test]
    fn a_separated_value_is_never_another_flag() {
        // A flag written where a value belongs is a usage error, not the value.
        // `--remove-rootfs --identity-map=subordinate` took the map's spelling
        // as the tree to delete and removed a path of that name in the working
        // directory, reporting success. Every flag taking a separated value has
        // the shape, so the refusal is checked across the modes.
        for args in [
            ["--remove-rootfs", "--identity-map=subordinate"].as_slice(),
            ["--remove-rootfs", "/roots/a", "--identity-map", "--rootfs"].as_slice(),
            ["--rootfs", "--share-net", "/bin/true"].as_slice(),
            ["--bind", "--rootfs", "/target", "/r", "/bin/true"].as_slice(),
            ["--gentoo-variants", "--gentoo-mirror"].as_slice(),
        ] {
            let error = parse_error(args);
            assert!(
                error.contains("names a flag"),
                "expected a refusal for {args:?}, got {error:?}"
            );
        }
    }

    #[test]
    fn a_value_that_merely_begins_with_a_dash_is_the_callers() {
        // A USE preference against a flag is written `-flag`, so the refusal
        // above keys on the names the flag table holds rather than on a leading
        // dash.
        let options = parse_run(&[
            "--rootfs",
            "/r",
            "--provision-gentoo",
            "amd64",
            "--gentoo-variant",
            "openrc",
            "--gentoo-prefer-use",
            "-systemd",
            "/bin/true",
        ])
        .expect("a valid command line");
        assert_eq!(options.gentoo_prefer_use, ["-systemd"]);
    }

    #[test]
    fn a_value_that_is_a_flags_spelling_is_written_joined() {
        // The escape hatch the refusal names, so a path that really is spelled
        // like a flag stays reachable.
        match parse_args(&["--remove-rootfs=--identity-map"]).expect("the removal should parse") {
            Invocation::Remove { dest, .. } => {
                assert_eq!(dest, PathBuf::from("--identity-map"));
            }
            _ => panic!("expected a removal"),
        }
    }

    #[test]
    fn remove_rootfs_refuses_every_launch_option() {
        // The removal vocabulary is closed, so a launch flag is a usage error
        // rather than a setting a removal would silently ignore. This holds for
        // flags added later too: the parser rejects by exhaustion, not by a
        // list kept in step by hand.
        for flag in [
            "--rootfs",
            "--restrict",
            "--share-net",
            "--provision-tar",
            "--profile",
            "--bind",
            "--seccomp",
        ] {
            let error = parse_error(&["--remove-rootfs", "/roots/a", flag]);
            assert!(
                error.contains(flag) && error.contains("--remove-rootfs"),
                "the error should name both flags, got {error:?}"
            );
        }
    }

    #[test]
    fn remove_rootfs_refuses_a_command() {
        let error = parse_error(&["--remove-rootfs", "/roots/a", "/bin/true"]);
        assert!(error.contains("/bin/true"), "{error}");
    }

    #[test]
    fn remove_rootfs_requires_a_destination() {
        assert!(parse_args(&["--remove-rootfs"]).is_err());
        // The map parser rejects the flag as a spelling before it can be
        // mistaken for the destination.
        assert!(parse_args(&["--identity-map", "--remove-rootfs"]).is_err());
    }

    /// The export an argument list parses to, panicking if it is anything else.
    fn parse_export_args(args: &[&str]) -> (PathBuf, Option<PathBuf>, IdentityMap, Option<i64>) {
        match parse_args(args).expect("the export should parse") {
            Invocation::Export {
                source,
                dest,
                map,
                clamp_mtime,
            } => (source, dest, map, clamp_mtime),
            _ => panic!("expected an export for {args:?}"),
        }
    }

    #[test]
    fn export_rootfs_takes_its_settings_in_either_form() {
        for args in [
            [
                "--export-rootfs",
                "/roots/trixie",
                "--export-to",
                "/tmp/out.tar",
                "--identity-map",
                "single",
                "--clamp-mtime",
                "1700000000",
            ]
            .as_slice(),
            [
                "--export-rootfs=/roots/trixie",
                "--export-to=/tmp/out.tar",
                "--identity-map=single",
                "--clamp-mtime=1700000000",
            ]
            .as_slice(),
        ] {
            let (source, dest, map, clamp) = parse_export_args(args);
            assert_eq!(source, PathBuf::from("/roots/trixie"));
            assert_eq!(dest, Some(PathBuf::from("/tmp/out.tar")));
            assert_eq!(map, IdentityMap::Single);
            assert_eq!(clamp, Some(1_700_000_000));
        }
    }

    #[test]
    fn export_rootfs_defaults_to_standard_output_and_the_subordinate_map() {
        // Absent a destination the archive goes to standard output, so it pipes
        // into a compressor without a temporary file. The map default is the
        // one a bundled-delegate sandbox writes under, matching removal, since
        // that is the case that needs the escalation at all.
        let (source, dest, map, clamp) = parse_export_args(&["--export-rootfs", "/roots/a"]);
        assert_eq!(source, PathBuf::from("/roots/a"));
        assert_eq!(dest, None, "the default sink is standard output");
        assert_eq!(map, IdentityMap::Subordinate);
        assert_eq!(clamp, None, "an unclamped export records real times");
    }

    #[test]
    fn export_rootfs_refuses_every_launch_option_and_a_command() {
        // The export vocabulary is closed by exhaustion, so a flag added to a
        // launch later is refused here without anyone remembering to add it.
        for flag in [
            "--rootfs",
            "--restrict",
            "--share-net",
            "--provision-tar",
            "--profile",
            "--bind",
            "--remove-rootfs",
        ] {
            let error = parse_error(&["--export-rootfs", "/roots/a", flag]);
            assert!(
                error.contains(flag) && error.contains("--export-rootfs"),
                "the error should name both flags, got {error:?}",
            );
        }
        let error = parse_error(&["--export-rootfs", "/roots/a", "/bin/true"]);
        assert!(error.contains("/bin/true"), "{error}");
    }

    #[test]
    fn export_rootfs_requires_a_source_and_a_well_formed_ceiling() {
        assert!(parse_args(&["--export-rootfs"]).is_err());
        assert!(parse_args(&["--export-rootfs", "/roots/a", "--export-to"]).is_err());
        for bad in ["yesterday", "1.5", ""] {
            assert!(
                parse_args(&["--export-rootfs", "/roots/a", "--clamp-mtime", bad]).is_err(),
                "{bad:?} must be refused as a timestamp",
            );
        }
        // The ceiling is a plain instant, so one before the epoch is a value
        // rather than an error.
        let (_, _, _, clamp) =
            parse_export_args(&["--export-rootfs", "/roots/a", "--clamp-mtime=-1"]);
        assert_eq!(clamp, Some(-1));
    }

    #[test]
    fn export_rootfs_still_answers_help_and_version() {
        assert!(matches!(
            parse_args(&["--export-rootfs", "/roots/a", "--help"]),
            Ok(Invocation::Help)
        ));
        assert!(matches!(
            parse_args(&["--export-rootfs", "/roots/a", "--version"]),
            Ok(Invocation::Version)
        ));
    }

    #[test]
    fn remove_rootfs_still_answers_help_and_version() {
        assert!(matches!(
            parse_args(&["--remove-rootfs", "/roots/a", "--help"]),
            Ok(Invocation::Help)
        ));
        assert!(matches!(
            parse_args(&["--remove-rootfs", "/roots/a", "--version"]),
            Ok(Invocation::Version)
        ));
    }

    #[test]
    fn rlimit_parses_a_shared_and_a_split_value() {
        let (resource, soft, hard) = parse_rlimit("processes=64").unwrap();
        assert_eq!(resource, Resource::Processes);
        assert_eq!(soft, Limit::of(64));
        assert_eq!(
            hard,
            Limit::of(64),
            "an omitted hard limit repeats the soft"
        );

        let (resource, soft, hard) = parse_rlimit("cpu-time=10:unlimited").unwrap();
        assert_eq!(resource, Resource::CpuTime);
        assert_eq!(soft, Limit::of(10));
        assert_eq!(hard, Limit::UNLIMITED);
    }

    #[test]
    fn rlimit_rejects_bad_input() {
        for bad in ["processes", "nonsense=1", "processes=x", "processes=1:x"] {
            assert!(parse_rlimit(bad).is_err(), "{bad:?} must be rejected");
        }
    }

    #[test]
    fn rlimit_names_the_resources_it_accepts() {
        // The list comes from the library's own `Deserialize`, so it stays
        // correct as resources are added rather than being restated here.
        let error = parse_rlimit("nonsense=1").unwrap_err();
        assert!(error.contains("address-space"), "{error}");
        assert!(error.contains("stack"), "{error}");
    }

    #[test]
    fn identity_map_parses_the_unit_and_range_forms() {
        assert!(matches!(
            parse_identity_map("--identity-map", "single").unwrap(),
            IdentityMap::Single
        ));
        assert!(matches!(
            parse_identity_map("--identity-map", "subordinate").unwrap(),
            IdentityMap::Subordinate
        ));
        let map = parse_identity_map("--identity-map", "uid=0:1000:1,1:100000:65536 gid=0:1000:1")
            .unwrap();
        match map {
            IdentityMap::Ranges { uid, gid, .. } => {
                assert_eq!(uid.len(), 2);
                assert_eq!(
                    uid[1],
                    IdRange {
                        inside: 1,
                        outside: 100_000,
                        count: 65_536
                    }
                );
                assert_eq!(gid.len(), 1);
            }
            other => panic!("expected an explicit range map, got {other:?}"),
        }
    }

    #[test]
    fn identity_map_rejects_a_half_specified_range() {
        // Both extent lists are required: a map missing one cannot be written.
        assert!(parse_identity_map("--identity-map", "uid=0:1000:1").is_err());
        assert!(parse_identity_map("--identity-map", "nonsense").is_err());
        assert!(parse_identity_map("--identity-map", "uid=0:1000").is_err());
    }

    #[test]
    fn run_as_parses_ids_and_groups() {
        let identity = parse_run_as("250:250").unwrap();
        assert_eq!(identity, Identity::new(250, 250));
        let with_groups = parse_run_as("250:250:10,20").unwrap();
        assert_eq!(with_groups, Identity::new(250, 250).groups([10, 20]));
        for bad in ["", "250", "250:", "x:1", "250:250:x"] {
            assert!(parse_run_as(bad).is_err(), "{bad:?} must be rejected");
        }
    }

    #[test]
    fn raw_mount_parses_its_fields() {
        let mount = parse_raw_mount("target=/sys fstype=sysfs flags=0xE").unwrap();
        assert_eq!(mount.get_target(), Path::new("/sys"));
        assert_eq!(mount.get_fstype(), Some("sysfs"));
        assert_eq!(mount.get_flags(), 0xE);
        assert_eq!(mount.get_source(), None);
        // A target is the one required field, and an unknown field is named.
        assert!(parse_raw_mount("fstype=sysfs").is_err());
        assert!(parse_raw_mount("target=/sys nonsense=1").is_err());
    }

    #[test]
    fn repository_requires_a_suite_and_orders_its_mirrors() {
        let repository = parse_repository(
            "suite=trixie mirror=file:///srv/pool mirror-fallback=file:///srv/snapshot \
             components=main,contrib trust-unsigned name=local",
        )
        .unwrap();
        let rendered = format!("{repository:?}");
        assert!(rendered.contains("file:///srv/pool"), "{rendered}");
        assert!(rendered.contains("trust: Unsigned"), "{rendered}");
        assert!(parse_repository("mirror=file:///srv/pool").is_err());
    }

    #[test]
    fn a_field_that_takes_no_value_refuses_one() {
        // `trust-unsigned=false` reads as the field being present, so a value
        // meaning the opposite turned archive signature verification off. A
        // field with no off state cannot honour one, so it is a usage error.
        for spec in [
            "suite=trixie mirror=file:///srv/pool trust-unsigned=false",
            "suite=trixie mirror=file:///srv/pool allow-stale-release=no",
        ] {
            let error = parse_repository(spec).expect_err("a value on a bare field is refused");
            assert!(error.contains("takes no value"), "{error}");
        }
        // Bare is the spelling, and it still means what it says.
        let repository = parse_repository("suite=trixie mirror=file:///srv/pool trust-unsigned")
            .expect("the bare field parses");
        assert!(format!("{repository:?}").contains("trust: Unsigned"));
    }

    #[test]
    fn priority_parses_the_archive_bands() {
        assert_eq!(parse_priority("required").unwrap(), Priority::Required);
        assert_eq!(parse_priority("optional").unwrap(), Priority::Optional);
        assert!(parse_priority("urgent").is_err());
    }

    #[test]
    fn an_overlay_root_needs_a_lower_and_an_upper() {
        let args = |items: &[&str]| {
            items
                .iter()
                .map(|item| OsString::from(*item))
                .collect::<Vec<_>>()
                .into_iter()
        };
        assert!(parse(args(&["--overlay-upper", "/tmp/up", "/bin/true"])).is_err());
        assert!(parse(args(&["--overlay-lower", "/tmp/low", "/bin/true"])).is_err());
        // A plain rootfs and an overlay root are alternatives, not a pair.
        assert!(
            parse(args(&[
                "--rootfs",
                "/tmp/root",
                "--overlay-lower",
                "/tmp/low",
                "--overlay-upper",
                "/tmp/up",
                "/bin/true",
            ]))
            .is_err()
        );
        assert!(
            parse(args(&[
                "--overlay-lower",
                "/tmp/low",
                "--overlay-upper",
                "/tmp/up",
                "/bin/true",
            ]))
            .is_ok()
        );
    }

    #[test]
    fn seconds_parse() {
        let parsed = parse_seconds("--timeout", OsStr::new("1.5")).unwrap();
        assert_eq!(parsed, Duration::from_millis(1500));
    }

    #[test]
    fn seconds_reject_bad_values() {
        // Includes values that are finite and positive but too large for a
        // Duration; these must be a usage error, not a panic.
        for bad in ["", "abc", "0", "-1", "nan", "inf", "1e300"] {
            assert!(
                parse_seconds("--timeout", OsStr::new(bad)).is_err(),
                "{bad:?} must be rejected"
            );
        }
    }

    #[test]
    fn cidr_rejects_an_out_of_range_prefix() {
        let (addr, len) = parse_cidr("10.0.2.0/24").unwrap();
        assert_eq!(addr, Ipv4Addr::new(10, 0, 2, 0));
        assert_eq!(len, 24);
        // A prefix past /32 is a usage error caught at parse time, not deferred
        // to the library's build-time rejection.
        for bad in ["10.0.2.0/33", "10.0.2.0/255"] {
            assert!(parse_cidr(bad).is_err(), "{bad:?} must be rejected");
        }
    }

    /// The syscall number for a name on the host, for test expectations.
    fn sysno(name: &str) -> i64 {
        resolve_syscall_name("--test", name).expect("a known syscall name")
    }

    #[test]
    fn seccomp_names_resolve_and_accumulate() {
        let mut target = Vec::new();
        parse_seccomp_names("--seccomp-allow", "read, write ,exit_group", &mut target).unwrap();
        assert_eq!(
            target,
            vec![sysno("read"), sysno("write"), sysno("exit_group")]
        );
        parse_seccomp_names("--seccomp-allow", "ioctl", &mut target).unwrap();
        assert_eq!(target.last(), Some(&sysno("ioctl")));
    }

    #[test]
    fn seccomp_rule_parses_a_simple_condition() {
        let (syscall, conditions) = parse_seccomp_rule(
            "--seccomp-allow-rule",
            "ioctl arg=1 len=dword op=eq value=0x5413",
        )
        .unwrap();
        assert_eq!(syscall, sysno("ioctl"));
        assert_eq!(conditions, vec![SeccompArg::eq_dword(1, 0x5413)]);
    }

    #[test]
    fn seccomp_rule_parses_masked_eq_and_decimal() {
        let (syscall, conditions) = parse_seccomp_rule(
            "--seccomp-allow-rule",
            "clone arg=0 len=qword op=masked-eq value=0 mask=268435456",
        )
        .unwrap();
        assert_eq!(syscall, sysno("clone"));
        assert_eq!(
            conditions,
            vec![SeccompArg::masked_eq_qword(0, 0x1000_0000, 0)]
        );
    }

    #[test]
    fn seccomp_rule_parses_anded_conditions() {
        let (_, conditions) = parse_seccomp_rule(
            "--seccomp-deny-rule",
            "socket arg=0 len=dword op=eq value=2, arg=1 len=dword op=eq value=1",
        )
        .unwrap();
        assert_eq!(
            conditions,
            vec![SeccompArg::eq_dword(0, 2), SeccompArg::eq_dword(1, 1)]
        );
    }

    #[test]
    fn seccomp_rule_without_conditions_lists_the_syscall() {
        let (syscall, conditions) = parse_seccomp_rule("--seccomp-deny-rule", "ptrace").unwrap();
        assert_eq!(syscall, sysno("ptrace"));
        assert!(conditions.is_empty());
    }

    #[test]
    fn seccomp_rule_rejects_malformed_conditions() {
        let cases = [
            ("ioctl arg=1 op=eq value=1", "len"),     // missing width
            ("ioctl len=dword op=eq value=1", "arg"), // missing index
            ("ioctl arg=1 len=dword value=1", "op"),  // missing op
            ("ioctl arg=1 len=dword op=eq", "value"), // missing value
            ("ioctl arg=1 len=dword op=eq value=1 mask=3", "masked-eq"), // stray mask
            ("clone arg=0 len=qword op=masked-eq value=0", "mask"), // masked-eq needs mask
            ("ioctl arg=9 len=dword op=eq value=1", "0 through 5"), // bad index
            ("ioctl arg=1 len=word op=eq value=1", "dword"), // bad width
            ("ioctl arg=1 len=dword op=lol value=1", "op must be"), // bad op
            ("ioctl arg=1 len=dword op=eq value=xyz", "number"), // bad value
            ("ioctl arg=1 len=dword eq value=1", "key=value"), // bare token
            (
                "ioctl arg=1 len=dword op=eq value=1 extra=2",
                "unknown condition key",
            ),
            ("nope arg=1 len=dword op=eq value=1", "unknown syscall"),
        ];
        for (input, needle) in cases {
            let err = parse_seccomp_rule("--seccomp-allow-rule", input)
                .expect_err(&format!("{input:?} must be rejected"));
            assert!(
                err.contains(needle),
                "error {err:?} for {input:?} should mention {needle:?}"
            );
        }
    }

    #[test]
    fn u64_literals_accept_decimal_and_hex() {
        assert_eq!(parse_u64_literal("--f", "value", "42").unwrap(), 42);
        assert_eq!(parse_u64_literal("--f", "value", "0x2a").unwrap(), 42);
        assert_eq!(parse_u64_literal("--f", "value", "0X2A").unwrap(), 42);
        assert!(parse_u64_literal("--f", "value", "").is_err());
        assert!(parse_u64_literal("--f", "value", "0xzz").is_err());
    }

    #[test]
    fn assemble_seccomp_reconciles_the_flags() {
        // Nothing given: no policy.
        assert!(
            assemble_seccomp(false, vec![], vec![], vec![], vec![])
                .unwrap()
                .is_none()
        );
        // Curated alone.
        assert!(matches!(
            assemble_seccomp(true, vec![], vec![], vec![], vec![]).unwrap(),
            Some(SeccompPolicy::Curated)
        ));
        // An allow side (bare plus a rule) yields Rules.
        assert!(matches!(
            assemble_seccomp(
                false,
                vec![sysno("read")],
                vec![],
                vec![(sysno("ioctl"), vec![SeccompArg::eq_dword(1, 0x5413)])],
                vec![],
            )
            .unwrap(),
            Some(SeccompPolicy::Rules(_))
        ));
    }

    #[test]
    fn assemble_seccomp_rejects_contradictions() {
        // Curated cannot be combined with named rules.
        assert!(
            assemble_seccomp(true, vec![sysno("read")], vec![], vec![], vec![])
                .unwrap_err()
                .contains("curated")
        );
        // An allow side and a deny side cannot be combined.
        assert!(
            assemble_seccomp(
                false,
                vec![sysno("read")],
                vec![sysno("write")],
                vec![],
                vec![]
            )
            .unwrap_err()
            .contains("cannot be combined")
        );
    }

    #[test]
    fn seccomp_flags_flow_through_parse() {
        let args = [
            "--restrict",
            "--seccomp-deny-rule",
            "write arg=0 len=dword op=eq value=1",
            "--",
            "/bin/echo",
            "hi",
        ]
        .into_iter()
        .map(OsString::from);
        let parsed = parse(args).expect("a valid command line");
        match parsed {
            Invocation::Run(options) => {
                assert!(matches!(options.seccomp, Some(SeccompPolicy::Rules(_))));
            }
            _ => panic!("expected a run invocation"),
        }
    }

    /// Parses a command line, expecting a run invocation.
    fn parse_run(args: &[&str]) -> Result<Options, String> {
        match parse(args.iter().map(|arg| OsString::from(*arg)))? {
            Invocation::Run(options) => Ok(*options),
            _ => panic!("expected a run invocation"),
        }
    }

    #[test]
    fn profile_flags_set_the_trust_mode() {
        // --profile loads fully trusted.
        let options =
            parse_run(&["--profile", "/p.toml", "/bin/true"]).expect("a valid command line");
        assert_eq!(options.profile.as_deref(), Some(Path::new("/p.toml")));
        assert!(!options.profile_restricted);

        // --restricted-profile loads under the restricted policy.
        let options = parse_run(&["--restricted-profile", "/p.toml", "/bin/true"])
            .expect("a valid command line");
        assert_eq!(options.profile.as_deref(), Some(Path::new("/p.toml")));
        assert!(options.profile_restricted);

        // The two are mutually exclusive.
        assert!(
            parse_run(&["--profile", "/a", "--restricted-profile", "/b", "/bin/true"]).is_err()
        );
    }

    #[test]
    fn netstack_flags_flow_through_parse() {
        let options = parse_run(&[
            "--rootfs",
            "/r",
            "--netstack",
            "--netstack-cidr",
            "192.168.5.0/24",
            "--netstack-mtu",
            "1400",
            "--netstack-host-loopback",
            "/bin/true",
        ])
        .expect("a valid command line");
        assert!(options.netstack);
        assert_eq!(
            options.netstack_cidr,
            Some((Ipv4Addr::new(192, 168, 5, 0), 24))
        );
        assert_eq!(options.netstack_mtu, Some(1400));
        assert!(options.netstack_host_loopback);
    }

    #[test]
    fn every_netstack_setting_the_library_offers_has_a_flag_that_reaches_it() {
        // The stack the flags describe is assembled by `netstack_from`, so
        // driving that is what proves a flag reaches the builder rather than
        // only reaching `Options`.
        let options = parse_run(&[
            "--rootfs",
            "/r",
            "--netstack",
            "--netstack-cidr",
            "192.168.5.0/24",
            "--netstack-cidr6",
            "fd11:2233::/64",
            "--netstack-no-ipv6",
            "--netstack-interface",
            "eth9",
            "--netstack-mtu",
            "1400",
            "/bin/true",
        ])
        .expect("a valid command line");
        assert_eq!(
            options.netstack_cidr6,
            Some(("fd11:2233::".parse::<Ipv6Addr>().unwrap(), 64))
        );
        assert!(options.netstack_no_ipv6);
        assert!(!options.netstack_no_ipv4);
        assert_eq!(options.netstack_interface.as_deref(), Some("eth9"));
        netstack_from(&options).expect("the settings compose a stack");

        // Both protocols off is the one combination the flags can name and the
        // stack has no answer for, and it is the library that says so.
        let neither = parse_run(&[
            "--rootfs",
            "/r",
            "--netstack",
            "--netstack-no-ipv4",
            "--netstack-no-ipv6",
            "/bin/true",
        ])
        .expect("a valid command line");
        assert!(netstack_from(&neither).is_err());
    }

    #[test]
    fn netstack_cidr_and_mtu_reject_bad_values() {
        assert!(
            parse_cidr("10.0.2.0").is_err(),
            "a CIDR needs a prefix length"
        );
        assert!(parse_cidr("not-an-ip/24").is_err());
        assert!(parse_cidr("10.0.2.0/schwa").is_err());
        parse_cidr("10.0.2.0/24").expect("a well-formed CIDR parses");
        assert!(parse_mtu("70000").is_err(), "an MTU must fit a u16");
        parse_mtu("1500").expect("a valid MTU parses");

        assert!(
            parse_cidr6("fd00::").is_err(),
            "a CIDR needs a prefix length"
        );
        assert!(
            parse_cidr6("10.0.2.0/24").is_err(),
            "that is not an IPv6 address"
        );
        assert!(parse_cidr6("fd00::/schwa").is_err());
        assert!(
            parse_cidr6("fd00::/129").is_err(),
            "129 is past the ceiling"
        );
        parse_cidr6("fd00::/64").expect("a well-formed CIDR parses");
    }

    #[test]
    fn netstack_conflicts_with_share_net() {
        let err = parse_run(&["--rootfs", "/r", "--netstack", "--share-net", "/bin/true"])
            .err()
            .expect("sharing the host network contradicts the native stack");
        assert!(err.contains("--share-net"), "{err}");
    }

    #[test]
    fn netstack_modifiers_require_netstack() {
        let err = parse_run(&["--rootfs", "/r", "--netstack-mtu", "1400", "/bin/true"])
            .err()
            .expect("a sub-flag without --netstack is a usage error");
        assert!(err.contains("require --netstack"), "{err}");
    }

    #[test]
    fn terminal_conflicts_with_a_null_stdin() {
        // A terminal is all three of the command's standard streams, so a
        // stated disposition for one means two different things were asked for.
        // Named here rather than left to the launch, so the message names both
        // flags.
        let err = parse_run(&[
            "--rootfs",
            "/r",
            "--terminal",
            "--stdin",
            "null",
            "/bin/true",
        ])
        .err()
        .expect("a directed stream contradicts a terminal");
        assert!(err.contains("--terminal"), "{err}");
        assert!(err.contains("--stdin"), "{err}");
    }

    #[test]
    fn terminal_conflicts_with_a_null_stdin_under_restrict() {
        // The restriction fallback supports a terminal too, so the same
        // contradiction has to be caught on that path — which returns before
        // the launch checks below it.
        let err = parse_run(&[
            "--restrict",
            "--seccomp",
            "curated",
            "--terminal",
            "--stdin=null",
            "/bin/true",
        ])
        .err()
        .expect("a directed stream contradicts a terminal here too");
        assert!(err.contains("--terminal"), "{err}");
    }

    #[test]
    fn terminal_composes_with_a_restriction_and_with_the_native_stack() {
        // Both are advertised independently, so both compose: a restriction
        // allocates its own pseudoterminal, and a native-stack run takes the
        // pending path and hands the primary over before the command runs.
        parse_run(&[
            "--restrict",
            "--seccomp",
            "curated",
            "--terminal",
            "/bin/true",
        ])
        .expect("a restriction takes a terminal");
        parse_run(&["--rootfs", "/r", "--netstack", "--terminal", "/bin/true"])
            .expect("the native stack takes a terminal");
    }

    #[test]
    fn netstack_conflicts_with_restrict() {
        let err = parse_run(&[
            "--restrict",
            "--netstack",
            "--landlock-ro",
            "/lib",
            "/bin/true",
        ])
        .err()
        .expect("the native stack has no meaning under a restriction");
        assert!(err.contains("--netstack"), "{err}");
    }

    #[test]
    fn restrict_requires_a_grant() {
        // Without a Landlock or seccomp grant a restriction confines nothing;
        // it is a usage error, not a launch error.
        let err = parse_run(&["--restrict", "/bin/true"])
            .err()
            .expect("a restriction with no grant is rejected");
        assert!(err.contains("at least one grant"), "{err}");
        // A single grant satisfies it.
        parse_run(&["--restrict", "--landlock-ro", "/lib", "/bin/true"])
            .expect("a Landlock grant is enough");
    }

    #[test]
    fn kill_after_requires_timeout() {
        let err = parse_run(&["--rootfs", "/r", "--kill-after", "5", "/bin/true"])
            .err()
            .expect("--kill-after alone has nothing to hang on");
        assert!(err.contains("--kill-after requires --timeout"), "{err}");
        // With a timeout it is accepted.
        parse_run(&[
            "--rootfs",
            "/r",
            "--timeout",
            "10",
            "--kill-after",
            "5",
            "/bin/true",
        ])
        .expect("--kill-after with --timeout is valid");
    }

    #[test]
    fn a_loopback_only_resolv_conf_is_not_routable() {
        assert!(!resolv_conf_has_routable_nameserver(
            "nameserver 127.0.0.53\noptions edns0\n"
        ));
        assert!(resolv_conf_has_routable_nameserver(
            "nameserver 127.0.0.53\nnameserver 9.9.9.9\n"
        ));
        assert!(resolv_conf_has_routable_nameserver(
            "nameserver 2606:4700:4700::1111\n"
        ));
        assert!(!resolv_conf_has_routable_nameserver("# only a comment\n"));
    }
}