sightingdb 0.7.1

A database designed for Sightings, a technique to count items
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
//! `--setup`: get from `cargo install sightingdb` to a running service.
//!
//! The wizard asks a handful of questions, prints exactly what it is going to
//! do, and only then touches anything. Two rules hold throughout:
//!
//! * Nothing existing is overwritten without being asked, one file at a time.
//!   A configuration or certificate already in place is far more likely to be
//!   wanted than a fresh default.
//! * Whatever it does, it says. Creating users and writing into `/etc` deserves
//!   a plan on screen rather than a surprise afterwards.

use std::fmt::Write as _;
use std::fs;
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result, bail};

use crate::acl::Acl;
use crate::config::TlsSettings;

/// Where an installation lives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
    /// System-wide, under `/etc` and `/var/lib`, running as its own user.
    System,
    /// Just for the current user, under their home directory.
    User,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
    Linux,
    MacOs,
}

impl Platform {
    fn detect() -> Result<Platform> {
        match std::env::consts::OS {
            "linux" => Ok(Platform::Linux),
            "macos" => Ok(Platform::MacOs),
            other => bail!("--setup does not know how to install on {other}"),
        }
    }

    fn service_manager(self) -> &'static str {
        match self {
            Platform::Linux => "systemd",
            Platform::MacOs => "launchd",
        }
    }
}

/// How a server takes part in a galaxy.
///
/// Not a kind of server — a server is whatever its storage set and peer set
/// add up to. This is the question put to someone installing one, because the
/// four combinations are what they are actually choosing between.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Stores everything, knows no peers. One server on its own.
    Standalone,
    /// Stores namespaces; other servers forward to it. It needs no peers of
    /// its own — they point at it.
    Node,
    /// Stores nothing of its own and forwards to peers. The entry point a
    /// client talks to.
    Router,
    /// Stores some namespaces and forwards the rest.
    Both,
}

impl Mode {
    fn label(self) -> &'static str {
        match self {
            Mode::Standalone => "standalone",
            Mode::Node => "a node in a galaxy",
            Mode::Router => "a router",
            Mode::Both => "a node and a router",
        }
    }

    /// Whether this mode has peers to forward to.
    fn forwards(self) -> bool {
        matches!(self, Mode::Router | Mode::Both)
    }

    /// Whether it is part of a galaxy at all, and so wants a name of its own.
    fn in_galaxy(self) -> bool {
        self != Mode::Standalone
    }
}

/// Everything the wizard decided, so it can be shown before it is done.
#[derive(Debug, Clone)]
pub struct Plan {
    pub scope: Scope,
    pub platform: Platform,
    /// The account the service runs as. `None` means the current user.
    pub service_user: Option<String>,
    pub config_dir: PathBuf,
    pub config_path: PathBuf,
    pub acl_path: PathBuf,
    pub tiers_path: PathBuf,
    /// Where tag colours are written, so the interface can edit them.
    pub tags_path: PathBuf,
    /// Where peers added from the interface are written. Only written into the
    /// configuration for a mode that forwards, since a server with no galaxy
    /// has no peers to manage.
    pub peers_path: PathBuf,
    pub log_config_path: PathBuf,
    pub dbdir: PathBuf,
    pub tls: Option<TlsSettings>,
    pub listen_ip: String,
    pub listen_port: u16,
    pub authenticate: bool,
    pub mode: Mode,
    /// What this server stores. `None` means everything, which is what a
    /// standalone one wants and what leaving the setting out means.
    pub namespaces: Option<Vec<String>>,
    /// This server's name in its own counters.
    pub node_id: String,
    pub admin_key: String,
    /// Where the binary should live so the service manager can reach it.
    pub binary: PathBuf,
    pub service_path: PathBuf,
    /// Off in tests, and when the caller only wants files written.
    pub create_user: bool,
    pub install_service: bool,
    pub start_service: bool,
}

impl Plan {
    /// A readable account of what will happen, shown before anything does.
    pub fn describe(&self) -> String {
        let mut out = String::new();
        let _ = writeln!(
            out,
            "SightingDB will be installed {} using {}.\n",
            match self.scope {
                Scope::System => "system-wide",
                Scope::User => "for the current user only",
            },
            self.platform.service_manager()
        );

        if self.create_user
            && let Some(user) = &self.service_user
        {
            let _ = writeln!(out, "  create the system user   {user}");
        }
        let _ = writeln!(
            out,
            "  configuration            {}",
            self.config_path.display()
        );
        let _ = writeln!(
            out,
            "  API keys                 {}",
            self.acl_path.display()
        );
        let _ = writeln!(
            out,
            "  namespace tiers          {}",
            self.tiers_path.display()
        );
        let _ = writeln!(
            out,
            "  logging configuration    {}",
            self.log_config_path.display()
        );
        let _ = writeln!(out, "  database                 {}", self.dbdir.display());
        match &self.tls {
            Some(tls) => {
                let _ = writeln!(out, "  self-signed certificate  {}", tls.cert.display());
                let _ = writeln!(out, "  its private key          {}", tls.key.display());
            }
            None => {
                let _ = writeln!(out, "  TLS                      off (plain HTTP)");
            }
        }
        if self.install_service {
            let _ = writeln!(
                out,
                "  service                  {}",
                self.service_path.display()
            );
            let _ = writeln!(out, "  binary                   {}", self.binary.display());
        }
        let _ = writeln!(
            out,
            "\n  listening on             {}://{}:{}",
            if self.tls.is_some() { "https" } else { "http" },
            self.listen_ip,
            self.listen_port
        );
        let _ = writeln!(
            out,
            "  API authentication       {}",
            if self.authenticate { "on" } else { "off" }
        );
        let _ = writeln!(out, "  running as               {}", self.mode.label());
        match &self.namespaces {
            None => {
                let _ = writeln!(out, "  stores                   every namespace");
            }
            Some(held) if held.is_empty() => {
                let _ = writeln!(
                    out,
                    "  stores                   nothing of its own; forwards to its peers"
                );
            }
            Some(held) => {
                let _ = writeln!(out, "  stores                   {}", held.join(", "));
            }
        }
        if self.mode.in_galaxy() {
            let _ = writeln!(out, "  known in the galaxy as   {}", self.node_id);
        }
        if self.mode.forwards() {
            let _ = writeln!(
                out,
                "\nIt starts with no peers, because a peer's key comes from that peer's own\n\
                 ACL, which does not exist until it is set up. Install the other servers,\n\
                 create a key on each for this one, then add them under Galaxy in the\n\
                 management interface — they take effect at once and are remembered in\n\
                 {}.\n\n\
                 Until then it has no peers, so it reports itself as a node rather than\n\
                 {} — which is what it is until they are added.",
                self.peers_path.display(),
                self.mode.label()
            );
        }
        out
    }

    /// The configuration file this plan produces.
    ///
    /// Commented throughout, because this file is where someone goes to change
    /// their mind and a setting whose purpose has to be looked up elsewhere is
    /// a setting that does not get changed.
    pub fn config_toml(&self) -> String {
        let mut out = String::new();
        let w = |out: &mut String, line: &str| {
            let _ = writeln!(out, "{line}");
        };

        w(&mut out, "# Written by `sightingdb --setup`.");
        w(&mut out, "#");
        w(
            &mut out,
            "# Edit freely: the program rewrites only the separate files named",
        );
        w(
            &mut out,
            "# below -- acl_file, tiers_file, tags_file and peers_file -- and only",
        );
        w(
            &mut out,
            "# when the matching thing is changed through the management interface.",
        );
        w(
            &mut out,
            "# Anything set directly here is read-only there, which it will say.",
        );
        w(&mut out, "#");
        let _ = writeln!(out, "# This server is set up as {}.", self.mode.label());
        w(&mut out, "");
        w(&mut out, "[daemon]");

        w(
            &mut out,
            "# Where the HTTP API listens. 127.0.0.1 answers only this",
        );
        w(&mut out, "# machine; 0.0.0.0 answers every interface.");
        let _ = writeln!(out, "listen_ip = \"{}\"", self.listen_ip);
        let _ = writeln!(out, "listen_port = {}", self.listen_port);

        w(&mut out, "");
        w(
            &mut out,
            "# Require an API key on the sighting API. The management interface",
        );
        w(&mut out, "# always requires one, whatever this says.");
        let _ = writeln!(out, "authenticate = {}", self.authenticate);

        w(&mut out, "");
        w(
            &mut out,
            "# Detaching is the service manager's job, so this stays false: it",
        );
        w(
            &mut out,
            "# wants a process in the foreground to supervise.",
        );
        w(&mut out, "daemonize = false");

        w(&mut out, "");
        match &self.tls {
            Some(tls) => {
                w(
                    &mut out,
                    "# A self-signed certificate, written by --setup. Replace both",
                );
                w(
                    &mut out,
                    "# files with a real pair when you have one; nothing else changes.",
                );
                w(&mut out, "ssl = true");
                let _ = writeln!(out, "ssl_cert = \"{}\"", tls.cert.display());
                let _ = writeln!(out, "ssl_key = \"{}\"", tls.key.display());
            }
            None => {
                w(
                    &mut out,
                    "# Plain HTTP. Anything on the network can read the API key as it",
                );
                w(
                    &mut out,
                    "# goes past, so this wants a trusted network or a proxy in front.",
                );
                w(&mut out, "ssl = false");
            }
        }

        w(&mut out, "");
        w(&mut out, "# One file per top-level namespace lives here.");
        let _ = writeln!(out, "dbdir = \"{}\"", self.dbdir.display());
        w(&mut out, "");
        w(
            &mut out,
            "# Seconds between snapshots, and on a clean shutdown as well.",
        );
        w(
            &mut out,
            "# There is no write-ahead log, so a crash loses up to this much.",
        );
        w(&mut out, "snapshot_interval = 300");
        w(&mut out, "");
        w(
            &mut out,
            "# How often expired values are reclaimed. A value stops being",
        );
        w(
            &mut out,
            "# visible the moment it expires; this is only when the space",
        );
        w(&mut out, "# comes back.");
        w(&mut out, "sweep_interval = 60");
        w(&mut out, "");
        w(
            &mut out,
            "# Hourly statistics buckets kept per value. 720 is 30 days.",
        );
        w(
            &mut out,
            "# 0 keeps all of them, and grows one bucket per hour forever.",
        );
        w(&mut out, "stats_retention = 720");
        w(&mut out, "");
        w(
            &mut out,
            "# How long a shadow sighting — the record that something was",
        );
        w(
            &mut out,
            "# searched for — is kept. 2592000 is 30 days; 0 keeps them for",
        );
        w(&mut out, "# ever, so `_shadow/*` grows without bound.");
        w(&mut out, "shadow_ttl = 2_592_000");
        w(&mut out, "");
        w(&mut out, "# Rejected values kept in memory, so");
        w(
            &mut out,
            "# /_management/api/rejections can say which values were turned",
        );
        w(&mut out, "# away and why. 0 switches the record off.");
        w(&mut out, "rejection_log = 1000");

        w(&mut out, "");
        if self.mode.in_galaxy() {
            w(
                &mut out,
                "# This server's name in its own counters. Sightings are counted",
            );
            w(
                &mut out,
                "# per server so that merging two copies adds separate",
            );
            w(
                &mut out,
                "# contributions rather than replaying increments.",
            );
            w(&mut out, "#");
            w(
                &mut out,
                "# It must be unique in the galaxy: two servers sharing a name",
            );
            w(
                &mut out,
                "# would each take the other's contribution for their own.",
            );
        } else {
            w(
                &mut out,
                "# This server's name in its own counters. \"local\" is right for a",
            );
            w(
                &mut out,
                "# server on its own; give each member of a galaxy its own name.",
            );
        }
        let _ = writeln!(out, "node_id = \"{}\"", self.node_id);

        w(&mut out, "");
        w(
            &mut out,
            "# API keys and what each may reach. Rewritten by the management",
        );
        w(
            &mut out,
            "# interface when a key is saved, so a new key works without a",
        );
        w(&mut out, "# restart.");
        let _ = writeln!(out, "acl_file = \"{}\"", self.acl_path.display());

        w(&mut out, "");
        w(
            &mut out,
            "# How tags are shown in the management interface: a colour and a",
        );
        w(
            &mut out,
            "# description each. Rewritten there when a tag is edited.",
        );
        w(
            &mut out,
            "# Presentation only -- a value can carry a tag nothing here",
        );
        w(
            &mut out,
            "# defines, and the interface lists those too so they can be",
        );
        w(
            &mut out,
            "# adopted. A name ending in ':' colours a whole family.",
        );
        let _ = writeln!(out, "tags_file = \"{}\"", self.tags_path.display());

        w(&mut out, "");
        w(&mut out, "[storage]");
        match &self.namespaces {
            None => {
                w(
                    &mut out,
                    "# Which namespaces this server stores. Absent means all of",
                );
                w(&mut out, "# them, which is what a server on its own wants.");
                w(&mut out, "#");
                w(
                    &mut out,
                    "#   namespaces = [\"feeds\", \"threats\"]   those subtrees only",
                );
                w(
                    &mut out,
                    "#   namespaces = []                      nothing: a pure router",
                );
                w(&mut out, "#");
                w(
                    &mut out,
                    "# Prefixes match whole path segments, so \"feeds\" holds",
                );
                w(&mut out, "# feeds/misp/ips and never feeds-internal.");
                w(&mut out, "#namespaces = [\"/\"]");
            }
            Some(held) if held.is_empty() => {
                w(
                    &mut out,
                    "# This server stores no namespace of its own: it forwards every",
                );
                w(
                    &mut out,
                    "# request to the peers below. A write to a namespace no peer",
                );
                w(&mut out, "# holds answers 421.");
                w(&mut out, "#");
                w(
                    &mut out,
                    "# The internal namespaces — _all, _shadow/*, _config — are held",
                );
                w(
                    &mut out,
                    "# regardless, because a server cannot keep its own consensus",
                );
                w(
                    &mut out,
                    "# tally otherwise. That tally is why a router is worth putting",
                );
                w(
                    &mut out,
                    "# in front of a galaxy: ask it /r/_all?val=<value> for a",
                );
                w(&mut out, "# value's consensus across everything below it.");
                w(&mut out, "namespaces = []");
            }
            Some(held) => {
                w(
                    &mut out,
                    "# Which namespaces this server stores. Prefixes match whole path",
                );
                w(
                    &mut out,
                    "# segments, so \"feeds\" holds feeds/misp/ips and never",
                );
                w(
                    &mut out,
                    "# feeds-internal. A write to anything else answers 421.",
                );
                let list = held
                    .iter()
                    .map(|n| format!("\"{n}\""))
                    .collect::<Vec<_>>()
                    .join(", ");
                let _ = writeln!(out, "namespaces = [{list}]");
            }
        }

        w(&mut out, "");
        w(
            &mut out,
            "# How long a top-level namespace stays in memory: hot is never",
        );
        w(
            &mut out,
            "# evicted, warm is dropped after warm_idle seconds untouched,",
        );
        w(&mut out, "# cold is read back on demand.");
        w(&mut out, "default_tier = \"hot\"");
        w(&mut out, "warm_idle = 3600");
        w(
            &mut out,
            "# Rewritten by the management interface when a tier is changed.",
        );
        let _ = writeln!(out, "tiers_file = \"{}\"", self.tiers_path.display());

        if self.mode.forwards() {
            w(&mut out, "");
            w(
                &mut out,
                "# ---------------------------------------------------------------",
            );
            w(&mut out, "# The other servers this one forwards to.");
            w(&mut out, "#");
            w(
                &mut out,
                "# Left commented out because a peer's key comes from that peer's",
            );
            w(
                &mut out,
                "# own ACL, which does not exist until it has been set up. Install",
            );
            w(
                &mut out,
                "# the other servers, create a key on each for this one, then fill",
            );
            w(&mut out, "# this in and restart.");
            w(&mut out, "#");
            w(
                &mut out,
                "# The key is the bound on what this server may do there: the",
            );
            w(
                &mut out,
                "# peer's own ACL decides, so a key granted \"rw:feeds\" cannot",
            );
            w(
                &mut out,
                "# write anywhere else however this server is configured or",
            );
            w(
                &mut out,
                "# compromised. Give each the narrowest grant that works.",
            );
            w(&mut out, "#");
            w(
                &mut out,
                "# `namespaces` on a peer says what that peer holds, so a request",
            );
            w(
                &mut out,
                "# can be sent where it can be served. Absent means a full mirror.",
            );
            w(
                &mut out,
                "# It has to agree with that peer's own [storage] namespaces.",
            );
            w(&mut out, "#");
            w(
                &mut out,
                "# Writes go to every mirror of a namespace; reads to one, chosen",
            );
            w(
                &mut out,
                "# by the value so the same value always comes from the same place.",
            );
            w(&mut out, "#");
            w(
                &mut out,
                "# max_hops is spent on each hop and refused at zero. A peer may",
            );
            w(
                &mut out,
                "# itself be a router, so this is what stops a miswired cycle.",
            );
            w(
                &mut out,
                "# ---------------------------------------------------------------",
            );
            w(
                &mut out,
                "# The section is live with no peers in it, which is a valid galaxy:",
            );
            w(
                &mut out,
                "# peers can then be added from the management interface, without",
            );
            w(
                &mut out,
                "# editing this file and without a restart. The settings below are",
            );
            w(
                &mut out,
                "# their defaults, shown commented so they can be changed.",
            );
            w(&mut out, "[galaxy]");
            w(
                &mut out,
                "# Peers added from the management interface are written here and",
            );
            w(
                &mut out,
                "# take effect at once. Its own file because this one is yours: a",
            );
            w(
                &mut out,
                "# program that rewrote it would destroy these comments.",
            );
            let _ = writeln!(out, "peers_file = \"{}\"", self.peers_path.display());
            w(&mut out, "#max_hops = 4");
            w(&mut out, "#health_interval = 30");
            w(
                &mut out,
                "# Seconds between catch-up passes: a server that was down finds",
            );
            w(
                &mut out,
                "# what it missed and pulls it from a peer that was up. 0 switches",
            );
            w(
                &mut out,
                "# it off, leaving such a server behind until someone syncs it by",
            );
            w(&mut out, "# hand.");
            w(&mut out, "#sync_interval = 300");
            w(
                &mut out,
                "# Seconds between rebuilds of the consensus tally from the galaxy:",
            );
            w(
                &mut out,
                "# a server in front of one counts a value towards consensus when a",
            );
            w(
                &mut out,
                "# mirror says the sighting was new, which only ever rises. This",
            );
            w(
                &mut out,
                "# surveys the galaxy and puts it right. 0 switches it off.",
            );
            w(&mut out, "#reconcile_interval = 3600");
            w(
                &mut out,
                "# Seconds between offering this server's keys to its peers, so one",
            );
            w(
                &mut out,
                "# that was down for a key change picks it up. A push goes through",
            );
            w(
                &mut out,
                "# the peer's own management interface, so the peer's ACL decides.",
            );
            w(
                &mut out,
                "# The offer is additive: a revocation made while a peer was down",
            );
            w(
                &mut out,
                "# does not reach it and must be repeated. 0 switches it off.",
            );
            w(&mut out, "#gossip_interval = 600");
            w(&mut out, "#");
            w(
                &mut out,
                "# One place to manage keys. The offer above is additive and cannot",
            );
            w(
                &mut out,
                "# carry a revocation to a server that was offline for it. Set",
            );
            w(
                &mut out,
                "# acl_authority on the server that owns the galaxy's keys and",
            );
            w(
                &mut out,
                "# acl_replaceable on each that accepts them, and the owner's offer",
            );
            w(
                &mut out,
                "# becomes the whole list, held exactly — which does remove. Both",
            );
            w(
                &mut out,
                "# ends must agree, and setting both on one server is refused.",
            );
            w(&mut out, "#acl_authority = false");
            w(&mut out, "#acl_replaceable = false");
            w(
                &mut out,
                "# Off for a galaxy of self-signed instances, which is what",
            );
            w(&mut out, "# --setup produces.");
            w(&mut out, "#verify_tls = true");
            w(&mut out, "");
            w(
                &mut out,
                "# A peer written into the list below is shown in the interface but",
            );
            w(
                &mut out,
                "# not editable there, since a change made there would last only",
            );
            w(
                &mut out,
                "# until the next restart. Prefer adding them above.",
            );
            w(&mut out, "#peers = [");
            w(
                &mut out,
                "#  { url = \"https://node-a.example:9999\", key = \"...\" },",
            );
            w(
                &mut out,
                "#  { url = \"https://node-b.example:9999\", key = \"...\", namespaces = [\"feeds\"] },",
            );
            w(&mut out, "#]");
        }

        out
    }

    fn service_unit(&self) -> String {
        match self.platform {
            Platform::Linux => {
                let user = self
                    .service_user
                    .clone()
                    .unwrap_or_else(|| "%i".to_string());
                format!(
                    "# Written by `sightingdb --setup`.\n\
                     [Unit]\n\
                     Description=SightingDB\n\
                     After=network-online.target\n\
                     Wants=network-online.target\n\n\
                     [Service]\n\
                     Type=exec\n\
                     ExecStart={binary} -c {config} -l {logcfg}\n\
                     # systemd restarts it when it dies, so `kill` does not stop it:\n\
                     # use `systemctl stop sightingdb`, or `sightingdb --stop`.\n\
                     Restart=on-failure\n\
                     RestartSec=5s\n\
                     User={user}\n\
                     KillSignal=SIGTERM\n\
                     # Long enough for the final snapshot to be written.\n\
                     TimeoutStopSec=60s\n\
                     NoNewPrivileges=yes\n\
                     PrivateTmp=yes\n\
                     ProtectSystem=strict\n\
                     ProtectHome=yes\n\
                     ReadWritePaths={dbdir}\n\n\
                     [Install]\n\
                     WantedBy=multi-user.target\n",
                    binary = self.binary.display(),
                    config = self.config_path.display(),
                    logcfg = self.log_config_path.display(),
                    dbdir = self.dbdir.display(),
                    user = user,
                )
            }
            Platform::MacOs => format!(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
                 <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \
                 \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
                 <plist version=\"1.0\">\n<dict>\n\
                 \x20 <key>Label</key><string>{label}</string>\n\
                 \x20 <key>ProgramArguments</key>\n\x20 <array>\n\
                 \x20   <string>{binary}</string>\n\
                 \x20   <string>-c</string><string>{config}</string>\n\
                 \x20   <string>-l</string><string>{logcfg}</string>\n\
                 \x20 </array>\n\
                 \x20 <key>RunAtLoad</key><true/>\n\
                 \x20 <key>KeepAlive</key><true/>\n\
                 \x20 <key>WorkingDirectory</key><string>{workdir}</string>\n\
                 \x20 <key>StandardOutPath</key><string>{logdir}/sightingdb.log</string>\n\
                 \x20 <key>StandardErrorPath</key><string>{logdir}/sightingdb.err</string>\n\
                 </dict>\n</plist>\n",
                label = LAUNCHD_LABEL,
                binary = self.binary.display(),
                config = self.config_path.display(),
                logcfg = self.log_config_path.display(),
                workdir = self.config_dir.display(),
                logdir = self.dbdir.display(),
            ),
        }
    }
}

const LAUNCHD_LABEL: &str = "com.github.stricaud.sightingdb";
/// What installs before 0.5 called the launchd job. Still looked for, because
/// one left behind holds the port and the new service then restarts forever —
/// a puzzle worth naming rather than leaving to be worked out from a log.
const LAUNCHD_LEGACY_LABEL: &str = "com.devo.sightingdb";
const SERVICE_USER: &str = "sightingdb";
/// Minimal logging configuration, so the service has one without hunting.
const LOG_CONFIG: &str = "refresh_rate: 30 seconds\n\
                          appenders:\n\
                          \x20 stdout:\n\
                          \x20   kind: console\n\
                          root:\n\
                          \x20 level: info\n\
                          \x20 appenders:\n\
                          \x20   - stdout\n";

// ---------------------------------------------------------------------------
// Asking
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Accounting for an installation
// ---------------------------------------------------------------------------

/// One file an installation consists of.
struct Installed {
    what: &'static str,
    path: PathBuf,
    /// Why it is there, or when it appears — shown for anything whose absence
    /// is normal, so a missing file is not read as a broken install.
    note: String,
    /// Holds a secret: say so when anyone but its owner can read it.
    private: bool,
    /// This installation's own file, rather than one it merely uses.
    ///
    /// Erasing removes only these. A logging configuration found in `/etc` or
    /// a home directory may be shared with another instance — or be the only
    /// one on the machine — and the binary belongs to whoever installed it, so
    /// neither is this installation's to delete.
    owned: bool,
    kind: Kind,
}

/// What a file is, which is what decides whether erasing takes it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    /// Sightings. Gone with `--erase`, since a database is the thing people
    /// mean when they say start again.
    Data,
    /// The service unit, which has to go for `--setup` to install another.
    Service,
    /// Settings, keys and certificates: kept by `--erase`, so the same
    /// installation can be rebuilt without answering every question again.
    /// Only `--erase-hard` removes these.
    Config,
    /// Neither ours to remove nor ours to keep: the binary, a logging
    /// configuration belonging to the machine.
    Other,
}

/// Every file this installation uses, whether or not it exists yet.
///
/// Answers "what did this put on my disk, and is it all still there" — which
/// `--setup` is otherwise the only record of, and only at the moment it ran.
/// The configuration is the source of truth: these are the paths *this*
/// install actually reads and writes, not the ones a default install would.
pub fn installed_report(config_path: &Path, logging_config: Option<&Path>) -> Result<String> {
    let entries = inventory(config_path, logging_config)?;
    let mut out = render(&entries);

    // The question that follows "what is installed" is usually "how do I stop
    // it", and on both platforms the answer is not what people try first.
    let services: Vec<&Installed> = entries
        .iter()
        .filter(|entry| entry.what == "service" && entry.path.exists())
        .collect();
    if let Some(service) = services.first() {
        let _ = write!(out, "\n{}", stopping(&service.path));
    }

    // Two of them is the state that produces a daemon restarting every ten
    // seconds: one wins the port, the supervisor keeps rebooting the other.
    if services.len() > 1 {
        let _ = writeln!(
            out,
            "\nWARNING: {} services are installed for this configuration:",
            services.len()
        );
        for service in &services {
            let _ = writeln!(out, "  {}", service.path.display());
        }
        let _ = writeln!(
            out,
            "Only one can hold the port. The other will fail to start and be restarted\n\
             by its supervisor for as long as it is installed. Remove whichever is not\n\
             wanted, then check with: sightingdb --installed"
        );
    }
    Ok(out)
}

/// How to stop the thing, which is worth saying because the obvious way does
/// not work: both service managers restart the daemon when it dies, so a
/// `kill -9` is followed by it starting again a moment later.
fn stopping(service: &Path) -> String {
    let stop = service_commands(service, ServiceAction::Stop)
        .first()
        .map(|command| command.join(" "))
        .unwrap_or_default();
    let why = if service.display().to_string().ends_with(".plist") {
        "the plist sets KeepAlive, so launchd starts it again immediately"
    } else {
        "the unit sets Restart=on-failure, so systemd starts it again immediately"
    };
    format!(
        "To stop it:    {stop}\n\
         Or:            sightingdb --stop     (--start and --restart too)\n\
         `kill` will not do it — {why}.\n"
    )
}

/// Every file this installation uses, in the order a person reads them.
fn inventory(config_path: &Path, logging_config: Option<&Path>) -> Result<Vec<Installed>> {
    let settings = crate::config::Settings::load(config_path)?;
    let mut entries = vec![Installed {
        what: "configuration",
        path: config_path.to_path_buf(),
        note: String::new(),
        private: false,
        owned: true,
        kind: Kind::Config,
    }];

    // The one named on the command line, else the one the daemon would find.
    let logging = logging_config
        .map(Path::to_path_buf)
        .or_else(|| crate::logging_candidates().into_iter().find(|p| p.exists()));
    if let Some(logging) = logging {
        // Only ours if it lives with the configuration that names it. One
        // found by looking in the usual places belongs to the machine.
        let ours = logging.parent() == config_path.parent();
        entries.push(Installed {
            what: "logging config",
            path: logging,
            note: if ours {
                String::new()
            } else {
                "not this installation's; --erase leaves it".to_string()
            },
            private: false,
            owned: ours,
            kind: Kind::Config,
        });
    }

    if let Some(acl) = &settings.acl_file {
        entries.push(Installed {
            what: "API keys",
            path: acl.clone(),
            note: "rewritten when a key is saved".to_string(),
            private: true,
            owned: true,
            kind: Kind::Config,
        });
    } else {
        entries.push(Installed {
            what: "API keys",
            path: config_path.to_path_buf(),
            note: "no acl_file: the keys are in the [acl] section of it".to_string(),
            private: true,
            // Already listed as the configuration; naming it twice as
            // something to remove would be a way to remove it twice.
            owned: false,
            kind: Kind::Config,
        });
    }

    if let Some(tiers) = &settings.tiers_file {
        entries.push(Installed {
            what: "tiers",
            path: tiers.clone(),
            note: "written when a tier is changed".to_string(),
            private: false,
            owned: true,
            kind: Kind::Config,
        });
    }

    if let Some(tls) = &settings.tls {
        entries.push(Installed {
            what: "TLS certificate",
            path: tls.cert.clone(),
            note: String::new(),
            private: false,
            owned: true,
            kind: Kind::Config,
        });
        entries.push(Installed {
            what: "TLS key",
            path: tls.key.clone(),
            note: String::new(),
            private: true,
            owned: true,
            kind: Kind::Config,
        });
    }

    if let Some(dbdir) = &settings.dbdir {
        entries.push(Installed {
            what: "database",
            path: dbdir.clone(),
            note: String::new(),
            private: false,
            owned: true,
            kind: Kind::Data,
        });
    }

    // Only consulted when the daemon backgrounds itself; under a service
    // manager the logs go to the journal instead.
    if settings.daemonize {
        for (what, path) in [
            ("stdout log", &settings.log_out),
            ("stderr log", &settings.log_err),
        ] {
            if path != Path::new("/dev/null") {
                entries.push(Installed {
                    what,
                    path: path.clone(),
                    note: String::new(),
                    private: false,
                    owned: true,
                    kind: Kind::Data,
                });
            }
        }
    }

    if let Ok(binary) = std::env::current_exe() {
        entries.push(Installed {
            what: "binary",
            path: binary,
            // Removing the program you are running, on the strength of a
            // configuration file, is more than was asked for.
            note: "left alone by --erase".to_string(),
            private: false,
            owned: false,
            kind: Kind::Other,
        });
    }

    for path in service_candidates() {
        // Only the one that exists, or the system one to say it does not.
        if path.exists() {
            // A unit that runs *this* configuration is this installation's; a
            // unit for another one is somebody else's service.
            let ours = fs::read_to_string(&path).is_ok_and(|unit| {
                unit.contains(&config_path.display().to_string())
                    || unit.contains(&full(config_path).display().to_string())
            });
            entries.push(Installed {
                what: "service",
                path,
                note: if ours {
                    String::new()
                } else {
                    "runs a different configuration; --erase leaves it".to_string()
                },
                private: false,
                owned: ours,
                kind: Kind::Service,
            });
        }
    }
    if !entries.iter().any(|entry| entry.what == "service")
        && let Some(path) = service_candidates().into_iter().next()
    {
        entries.push(Installed {
            what: "service",
            path,
            note: "not installed; `--setup` can add one".to_string(),
            private: false,
            owned: false,
            kind: Kind::Service,
        });
    }

    // `-c short.toml` is a perfectly good way to start the daemon and a useless
    // thing to be told afterwards, so every path is reported in full.
    for entry in &mut entries {
        entry.path = full(&entry.path);
    }
    Ok(entries)
}

/// A path as somewhere you could paste into another command: symlinks resolved
/// when it exists, and made absolute when it does not.
fn full(path: &Path) -> PathBuf {
    if let Ok(real) = fs::canonicalize(path) {
        return real;
    }

    // A file that does not exist yet cannot be canonicalized, so as much of it
    // as does exist is resolved and the rest appended. Without that, a tiers
    // file that has never been written reads as `/var/…` while the directory
    // holding it reads as `/private/var/…`, and the two look like different
    // places.
    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
    let mut missing = Vec::new();
    let mut cursor = absolute.as_path();
    while let Some(parent) = cursor.parent() {
        if let Some(name) = cursor.file_name() {
            missing.push(name.to_os_string());
        }
        if let Ok(real) = fs::canonicalize(parent) {
            let mut resolved = real;
            resolved.extend(missing.iter().rev());
            return resolved;
        }
        cursor = parent;
    }
    absolute
}

/// Where a service unit lands, for this platform, system install first.
fn service_candidates() -> Vec<PathBuf> {
    let mut candidates = Vec::new();
    match Platform::detect() {
        Ok(Platform::Linux) => {
            candidates.push(PathBuf::from("/etc/systemd/system/sightingdb.service"));
            if let Some(home) = dirs::home_dir() {
                candidates.push(home.join(".config/systemd/user/sightingdb.service"));
            }
        }
        Ok(Platform::MacOs) => {
            for label in [LAUNCHD_LABEL, LAUNCHD_LEGACY_LABEL] {
                candidates.push(PathBuf::from(format!(
                    "/Library/LaunchDaemons/{label}.plist"
                )));
                if let Some(home) = dirs::home_dir() {
                    candidates.push(home.join(format!("Library/LaunchAgents/{label}.plist")));
                }
            }
        }
        Err(_) => {}
    }
    candidates
}

fn render(entries: &[Installed]) -> String {
    let mut out = format!(
        "SightingDB {} — the files this installation uses\n\n",
        env!("CARGO_PKG_VERSION")
    );

    let widest = entries
        .iter()
        .map(|entry| entry.what.len())
        .max()
        .unwrap_or(0);
    let widest_path = entries
        .iter()
        .map(|entry| entry.path.display().to_string().len())
        .max()
        .unwrap_or(0);

    let mut missing = 0;
    let mut exposed = Vec::new();
    for entry in entries {
        let state = describe(&entry.path);
        if state.is_none() {
            missing += 1;
        }
        if entry.private && state.as_ref().is_some_and(|state| state.others_can_read) {
            exposed.push(entry.path.display().to_string());
        }

        let (mark, detail) = match &state {
            Some(state) => ("present", state.detail.as_str()),
            None => ("missing", ""),
        };
        let note = if entry.note.is_empty() {
            String::new()
        } else {
            format!("  ({})", entry.note)
        };
        let _ = writeln!(
            out,
            "  {mark}  {:<widest$}  {:<widest_path$}  {detail}{note}",
            entry.what,
            entry.path.display(),
        );
    }

    let _ = writeln!(
        out,
        "\n{} of {} present. A missing file is not always a problem: the tiers file is\n\
         written when a tier is first changed, and a service is optional.",
        entries.len() - missing,
        entries.len()
    );

    for path in exposed {
        let _ = writeln!(
            out,
            "\nWARNING: {path} holds a secret and can be read by more than its owner.\n\
             Run: chmod 600 {path}"
        );
    }
    out
}

/// What is at a path.
struct State {
    detail: String,
    /// Unix mode allows group or other to read it.
    others_can_read: bool,
}

/// A size, or a directory's contents, or nothing at all.
fn describe(path: &Path) -> Option<State> {
    let meta = fs::metadata(path).ok()?;

    if meta.is_dir() {
        let mut files = 0;
        let mut bytes = 0;
        if let Ok(entries) = fs::read_dir(path) {
            for entry in entries.flatten() {
                if let Ok(meta) = entry.metadata()
                    && meta.is_file()
                {
                    files += 1;
                    bytes += meta.len();
                }
            }
        }
        return Some(State {
            detail: format!("{files} file(s), {}", human(bytes)),
            others_can_read: false,
        });
    }

    // The mode is shown for every file, because it is what `--setup` sets and
    // seeing it is how you notice it has been widened since.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = meta.permissions().mode() & 0o777;
        Some(State {
            detail: format!("{}, mode {mode:04o}", human(meta.len())),
            others_can_read: mode & 0o044 != 0,
        })
    }
    #[cfg(not(unix))]
    {
        Some(State {
            detail: human(meta.len()),
            others_can_read: false,
        })
    }
}

fn human(bytes: u64) -> String {
    match bytes {
        0..=1023 => format!("{bytes} B"),
        1024..=1_048_575 => format!("{:.1} KB", bytes as f64 / 1024.0),
        1_048_576..=1_073_741_823 => format!("{:.1} MB", bytes as f64 / 1_048_576.0),
        _ => format!("{:.1} GB", bytes as f64 / 1_073_741_824.0),
    }
}

// ---------------------------------------------------------------------------
// Taking an installation away again
// ---------------------------------------------------------------------------

/// Stop before installing a second service beside an existing one.
///
/// The two would run the same binary against the same configuration; whichever
/// starts second cannot bind the port, exits, and is restarted by its service
/// manager on a timer — which reads as a daemon rebooting every few seconds and
/// takes a while to trace back to here.
fn refuse_if_a_service_exists() -> Result<()> {
    let installed: Vec<PathBuf> = service_candidates()
        .into_iter()
        .filter(|path| path.exists())
        .collect();
    if installed.is_empty() {
        return Ok(());
    }

    let mut message = String::from("a SightingDB service is already installed:\n");
    for path in &installed {
        let _ = writeln!(message, "  {}", path.display());
    }
    let _ = write!(
        message,
        "\nInstalling another would leave two of them running the same configuration, and \
         the one that loses the port would be restarted by its service manager forever.\n\n\
         To replace this installation:  sightingdb --erase       (keeps your configuration)\n\
         To remove it entirely:         sightingdb --erase-hard\n\
         To change a setting instead:   edit the configuration and `sightingdb --restart`\n\
         Or remove the service file by hand and run --setup again."
    );
    bail!(message)
}

/// The word that has to be typed. Not "y": this removes a database.
const ERASE_WORD: &str = "erase";

/// How the caller confirms. A parameter so the tests can answer without a
/// terminal, and so the prompt is in one place.
pub type Confirm<'a> = &'a dyn Fn(&str) -> Result<bool>;

/// Ask on the terminal, refusing when there is not one: a destructive command
/// with nobody to ask is a destructive command that should not run.
pub fn ask_to_erase(summary: &str) -> Result<bool> {
    if !std::io::stdin().is_terminal() {
        bail!(
            "--erase needs a terminal to confirm on. It removes a database; there is no \
             flag to skip the question."
        );
    }
    print!("{summary}\nType {ERASE_WORD} to remove all of this: ");
    std::io::stdout().flush().ok();
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    Ok(answer.trim() == ERASE_WORD)
}

/// Stop the daemon and remove what this installation put on disk.
///
/// The counterpart of [`run`]. It stops the *service* rather than the process,
/// because both service managers restart the daemon when it dies — which is
/// why `kill` appears not to work — and then removes only the paths the
/// configuration names, snapshot by snapshot, so a `dbdir` pointing somewhere
/// shared cannot take the rest of that directory with it.
///
/// `hard` decides how much goes:
///
/// * without it, the database and the service, keeping the configuration, the
///   API keys and the certificate — enough to start again with the same
///   settings, and enough for `--setup` to run;
/// * with it, those as well, leaving nothing behind.
///
/// The binary is left either way: removing the program you are running, on the
/// strength of a configuration file, is more than was asked for.
pub fn erase(
    config_path: &Path,
    logging_config: Option<&Path>,
    hard: bool,
    confirm: Confirm,
) -> Result<String> {
    let entries = inventory(config_path, logging_config)?;
    let service = entries
        .iter()
        .find(|entry| entry.what == "service" && entry.owned && entry.path.exists())
        .map(|entry| entry.path.clone());

    let goes = |entry: &Installed| {
        entry.owned
            && entry.path.exists()
            && match entry.kind {
                Kind::Data | Kind::Service => true,
                Kind::Config => hard,
                Kind::Other => false,
            }
    };

    let doomed: Vec<&Installed> = entries.iter().filter(|entry| goes(entry)).collect();
    let kept: Vec<&Installed> = entries
        .iter()
        .filter(|entry| entry.path.exists() && !goes(entry))
        .collect();

    let mut summary = String::from("This removes:\n");
    for entry in &doomed {
        let _ = writeln!(summary, "  {:<16} {}", entry.what, entry.path.display());
    }
    if !kept.is_empty() {
        let _ = writeln!(summary, "\nAnd leaves:");
        for entry in &kept {
            let _ = writeln!(summary, "  {:<16} {}", entry.what, entry.path.display());
        }
    }
    if !hard && kept.iter().any(|entry| entry.kind == Kind::Config) {
        let _ = writeln!(
            summary,
            "\n`--erase-hard` removes the configuration, the API keys and the certificate too."
        );
    }
    let _ = write!(summary, "\nThe data cannot be recovered afterwards.");

    if !confirm(&summary)? {
        return Ok("Nothing was removed.\n".to_string());
    }

    let mut out = String::new();
    if let Some(service) = &service {
        let _ = writeln!(out, "{}", stop_service(service));
    }
    let _ = writeln!(out, "{}", stop_processes(config_path));

    for entry in doomed {
        match remove(&entry.path) {
            Ok(what) => {
                let _ = writeln!(
                    out,
                    "removed  {:<16} {} {what}",
                    entry.what,
                    entry.path.display()
                );
            }
            Err(e) => {
                let _ = writeln!(
                    out,
                    "kept     {:<16} {}: {e}",
                    entry.what,
                    entry.path.display()
                );
            }
        }
    }

    // Directories that only existed to hold what has just gone.
    for dir in tidy_candidates(&entries) {
        if fs::read_dir(&dir).is_ok_and(|mut entries| entries.next().is_none())
            && fs::remove_dir(&dir).is_ok()
        {
            let _ = writeln!(out, "removed  {:<16} {}", "empty directory", dir.display());
        }
    }

    let _ = writeln!(
        out,
        "\nDone. {}",
        if hard {
            "`sightingdb --setup` starts again from nothing."
        } else {
            "The configuration is still there: `sightingdb --setup` will reinstall the \
             service, and starting the daemon gives an empty database."
        }
    );
    Ok(out)
}

/// What to ask the service manager for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceAction {
    Start,
    Stop,
    Restart,
    /// Stop and forget: what `--erase` needs, so nothing starts it again.
    Remove,
}

impl ServiceAction {
    fn parse(raw: &str) -> Result<ServiceAction> {
        match raw {
            "start" => Ok(ServiceAction::Start),
            "stop" => Ok(ServiceAction::Stop),
            "restart" => Ok(ServiceAction::Restart),
            other => bail!("unknown service action '{other}'"),
        }
    }
}

/// Whether a unit belongs to the user rather than the system, told from where
/// it lives — the only thing that distinguishes them for these commands.
fn is_user_service(service: &Path) -> bool {
    let path = service.display().to_string();
    path.contains("/.config/") || path.contains("/Library/LaunchAgents/")
}

/// The commands that carry out an action, in the order to try them.
///
/// Pure, so the shapes can be tested on a machine that has neither service
/// manager. Later entries are fallbacks for older systems; a command that
/// succeeds ends the sequence unless it is one of a pair that both have to run.
fn service_commands(service: &Path, action: ServiceAction) -> Vec<Vec<String>> {
    let path = service.display().to_string();
    let user = is_user_service(service);

    if path.ends_with(".plist") {
        let domain = if user {
            format!("gui/{}", current_uid())
        } else {
            "system".to_string()
        };
        let target = format!("{domain}/{LAUNCHD_LABEL}");
        return match action {
            // launchd has no restart; kickstart -k is how it is spelled.
            ServiceAction::Restart => vec![
                vec!["launchctl".into(), "kickstart".into(), "-k".into(), target],
                vec![
                    "launchctl".into(),
                    "unload".into(),
                    "-w".into(),
                    path.clone(),
                ],
                vec!["launchctl".into(), "load".into(), "-w".into(), path],
            ],
            ServiceAction::Start => vec![
                vec!["launchctl".into(), "bootstrap".into(), domain, path.clone()],
                vec!["launchctl".into(), "load".into(), "-w".into(), path],
            ],
            ServiceAction::Stop | ServiceAction::Remove => vec![
                vec!["launchctl".into(), "bootout".into(), target],
                vec!["launchctl".into(), "unload".into(), "-w".into(), path],
            ],
        };
    }

    let unit = "sightingdb".to_string();
    let systemctl = |verb: &str| {
        let mut command = vec!["systemctl".to_string()];
        if user {
            command.push("--user".to_string());
        }
        command.extend([verb.to_string(), unit.clone()]);
        command
    };
    match action {
        ServiceAction::Start => vec![systemctl("start")],
        ServiceAction::Stop => vec![systemctl("stop")],
        ServiceAction::Restart => vec![systemctl("restart")],
        // Disabling as well, so a reboot does not bring back what was erased.
        ServiceAction::Remove => vec![systemctl("stop"), systemctl("disable")],
    }
}

/// Run an action's commands, reporting what happened.
fn run_service_commands(service: &Path, action: ServiceAction) -> String {
    let commands = service_commands(service, action);
    // A pair that both have to run, rather than a first choice and a fallback.
    let all_of_them = matches!(action, ServiceAction::Remove)
        || (!service.display().to_string().ends_with(".plist"));

    let mut out = String::new();
    for command in commands {
        let line = command.join(" ");
        match Command::new(&command[0]).args(&command[1..]).output() {
            Ok(done) if done.status.success() => {
                let _ = writeln!(out, "ran      {line}");
                if !all_of_them {
                    break;
                }
            }
            Ok(done) => {
                let _ = writeln!(
                    out,
                    "note     {line}: {}",
                    String::from_utf8_lossy(&done.stderr).trim()
                );
            }
            Err(e) => {
                let _ = writeln!(out, "note     {line}: {e}");
            }
        }
    }
    out.trim_end().to_string()
}

fn stop_service(service: &Path) -> String {
    run_service_commands(service, ServiceAction::Remove)
}

/// Start, stop or restart the installed service.
///
/// Exists because the obvious way does not work: both managers restart the
/// daemon when it dies, so `kill` — even `kill -9` — is followed by it coming
/// straight back. Stopping it means telling the manager, and the command for
/// that differs by platform and by whether the service is the system's or the
/// user's.
pub fn service_control(
    config_path: &Path,
    logging_config: Option<&Path>,
    action: &str,
) -> Result<String> {
    let action = ServiceAction::parse(action)?;
    let entries = inventory(config_path, logging_config)?;
    let Some(service) = entries
        .iter()
        .find(|entry| entry.what == "service" && entry.path.exists())
    else {
        bail!(
            "no service is installed for this configuration.\n\
             `sightingdb --setup` can install one, or run the daemon in the foreground \
             with `sightingdb -c {}`.",
            config_path.display()
        );
    };

    let mut out = format!("{:?} {}\n", action, service.path.display());
    let _ = writeln!(out, "{}", run_service_commands(&service.path, action));
    Ok(out)
}

/// Stop anything still running with this configuration./// Stop anything still running with this configuration.
///
/// Matched on the configuration path rather than the program name, so another
/// instance serving a different configuration is left alone.
fn stop_processes(config_path: &Path) -> String {
    let pattern = config_path.display().to_string();
    let Ok(found) = Command::new("pgrep").arg("-f").arg(&pattern).output() else {
        return "note     pgrep is not available, so no process was looked for".to_string();
    };

    let mine = std::process::id();
    let pids: Vec<String> = String::from_utf8_lossy(&found.stdout)
        .lines()
        .filter_map(|line| line.trim().parse::<u32>().ok())
        .filter(|pid| *pid != mine)
        .map(|pid| pid.to_string())
        .collect();

    if pids.is_empty() {
        return "no daemon was running with this configuration".to_string();
    }

    // TERM first: the database is written out on the way down, and killing it
    // outright throws away everything since the last snapshot.
    let _ = Command::new("kill").args(&pids).output();
    std::thread::sleep(std::time::Duration::from_secs(2));
    let still: Vec<&String> = pids
        .iter()
        .filter(|pid| {
            Command::new("kill")
                .args(["-0", pid])
                .output()
                .is_ok_and(|out| out.status.success())
        })
        .collect();
    if !still.is_empty() {
        let _ = Command::new("kill")
            .arg("-9")
            .args(still.iter().map(|pid| pid.as_str()))
            .output();
    }
    format!("stopped  process(es) {}", pids.join(", "))
}

fn current_uid() -> String {
    Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
        .unwrap_or_default()
}

/// Remove one path, reporting what went.
///
/// A directory is emptied of the files this program writes there and then
/// removed if that is all it held. Anything else is left, and said so: a
/// `dbdir` sharing a directory with something else is a mistake to report, not
/// one to act on.
fn remove(path: &Path) -> Result<String> {
    let meta = fs::symlink_metadata(path).with_context(|| format!("reading {}", path.display()))?;
    if !meta.is_dir() {
        fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
        return Ok(String::new());
    }

    let mut removed = 0;
    let mut left = 0;
    for entry in fs::read_dir(path).with_context(|| format!("reading {}", path.display()))? {
        let entry = entry?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        // What persistence writes: one zstd-compressed file per shard, plus the
        // single-file snapshot older builds wrote.
        let ours = name.ends_with(".json.zst") || name.ends_with(".json") || name.ends_with(".tmp");
        if ours && entry.path().is_file() {
            fs::remove_file(entry.path())?;
            removed += 1;
        } else {
            left += 1;
        }
    }

    if left == 0 {
        fs::remove_dir(path).with_context(|| format!("removing {}", path.display()))?;
        return Ok(format!("({removed} snapshot file(s))"));
    }
    Ok(format!(
        "({removed} snapshot file(s); {left} other file(s) left, so the directory stays)"
    ))
}

/// Directories worth removing once their contents have gone.
fn tidy_candidates(entries: &[Installed]) -> Vec<PathBuf> {
    let mut dirs: Vec<PathBuf> = Vec::new();
    for entry in entries {
        // The directory a file lived in, and its parent — an `ssl/` under a
        // config directory is worth taking, and so is the config directory.
        if let Some(parent) = entry.path.parent() {
            for dir in [
                parent.to_path_buf(),
                parent.parent().map(Path::to_path_buf).unwrap_or_default(),
            ] {
                if dir.as_os_str().is_empty() || !safe_to_tidy(&dir) || dirs.contains(&dir) {
                    continue;
                }
                dirs.push(dir);
            }
        }
    }
    // Deepest first, so `etc/ssl` goes before `etc`.
    dirs.sort_by_key(|dir| std::cmp::Reverse(dir.components().count()));
    dirs
}

/// Never tidy away somewhere that was not ours to begin with.
fn safe_to_tidy(dir: &Path) -> bool {
    const NEVER: [&str; 10] = [
        "/",
        "/etc",
        "/var",
        "/usr",
        "/opt",
        "/tmp",
        "/var/lib",
        "/usr/local",
        "/usr/local/etc",
        "/usr/local/var",
    ];
    if NEVER.contains(&dir.display().to_string().as_str()) {
        return false;
    }
    if dirs::home_dir().is_some_and(|home| home == dir) {
        return false;
    }
    // Two components is `/etc`; anything shallower is not an install of ours.
    dir.components().count() > 2
}

fn ask(question: &str, default: &str) -> Result<String> {
    print!("{question} [{default}]: ");
    std::io::stdout().flush().ok();
    let mut line = String::new();
    std::io::stdin()
        .read_line(&mut line)
        .context("reading your answer")?;
    let line = line.trim();
    Ok(if line.is_empty() {
        default.to_string()
    } else {
        line.to_string()
    })
}

/// Ask until the answer parses. Aborting the whole wizard over one typo would
/// throw away every answer given before it.
fn ask_parsed<T: std::str::FromStr>(question: &str, default: &str, what: &str) -> Result<T> {
    loop {
        let answer = ask(question, default)?;
        match answer.trim().parse() {
            Ok(value) => return Ok(value),
            Err(_) => println!("  '{}' is not {what}", answer.trim()),
        }
    }
}

fn ask_yes_no(question: &str, default: bool) -> Result<bool> {
    loop {
        let answer = ask(question, if default { "yes" } else { "no" })?;
        match answer.trim().to_ascii_lowercase().as_str() {
            "y" | "yes" => return Ok(true),
            "n" | "no" => return Ok(false),
            _ => println!("  please answer yes or no"),
        }
    }
}

/// What to do about a file that is already there.
/// Which of the four shapes this server is.
///
/// Asked as a question about what it is for rather than about settings,
/// because `namespaces` and `peers` are the settings and the four useful
/// combinations of them are what someone is actually choosing between.
fn ask_mode() -> Result<Mode> {
    println!(
        "\nHow should this server run?\n\
         \x20 1) standalone          stores everything, no other servers (the usual answer)\n\
         \x20 2) node in a galaxy    stores namespaces; other servers forward to it\n\
         \x20 3) router              stores nothing of its own; forwards to its peers\n\
         \x20 4) node and router     stores some namespaces and forwards the rest\n"
    );
    loop {
        match ask("Mode [1-4]", "1")?.trim() {
            "1" => return Ok(Mode::Standalone),
            "2" => return Ok(Mode::Node),
            "3" => return Ok(Mode::Router),
            "4" => return Ok(Mode::Both),
            other => println!("  '{other}' is not one of 1, 2, 3 or 4."),
        }
    }
}

/// What this server stores, for the modes where that is a choice.
fn ask_namespaces(mode: Mode) -> Result<Option<Vec<String>>> {
    match mode {
        // Everything, which is what leaving the setting out means.
        Mode::Standalone => Ok(None),
        // Stores nothing of its own.
        Mode::Router => Ok(Some(Vec::new())),
        Mode::Node | Mode::Both => {
            println!(
                "\nWhich namespaces does this server store? A comma separated list of\n\
                 prefixes — 'feeds, threats' holds those subtrees — or '/' for all of them.\n\
                 Prefixes match whole path segments, so 'feeds' holds feeds/misp/ips and\n\
                 never feeds-internal."
            );
            let answer = ask("Namespaces", if mode == Mode::Node { "/" } else { "feeds" })?;
            let held: Vec<String> = answer
                .split(',')
                .map(|part| part.trim().trim_matches('/').to_string())
                .filter(|part| !part.is_empty())
                .collect();
            // `/` trims to nothing, which here means everything rather than
            // the router's nothing — so an empty list from a non-empty answer
            // is the whole tree.
            Ok(if held.is_empty() { None } else { Some(held) })
        }
    }
}

/// A name for this server, defaulting to its hostname.
///
/// The hostname is the one name already unique among machines, which is what a
/// node id has to be. Falls back to the standalone name when it cannot be read.
fn default_node_id() -> String {
    let from_file = std::fs::read_to_string("/etc/hostname")
        .ok()
        .and_then(|text| text.split_whitespace().next().map(str::to_string));

    let from_command = || {
        std::process::Command::new("hostname")
            .output()
            .ok()
            .and_then(|out| String::from_utf8(out.stdout).ok())
            .and_then(|text| text.split_whitespace().next().map(str::to_string))
    };

    from_file
        .or_else(from_command)
        // Only the part before the first dot, and only characters a node id
        // may carry.
        .map(|name| {
            name.split('.')
                .next()
                .unwrap_or(&name)
                .chars()
                .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
                .take(64)
                .collect::<String>()
        })
        .filter(|name| !name.is_empty())
        .unwrap_or_else(|| crate::db::LOCAL_NODE.to_string())
}

fn ask_replace(path: &Path, what: &str) -> Result<bool> {
    println!("\n  {} already exists at {}", what, path.display());
    ask_yes_no("  replace it?", false)
}

// ---------------------------------------------------------------------------
// The wizard
// ---------------------------------------------------------------------------

pub fn run() -> Result<()> {
    if !std::io::stdin().is_terminal() {
        bail!("--setup asks questions, so it needs a terminal. Run it directly.");
    }

    let platform = Platform::detect()?;
    let root = is_root();

    // Installing a second service is the one mistake this cannot undo for you:
    // both run the same binary, one wins the port, and the supervisor restarts
    // the other for as long as it exists.
    refuse_if_a_service_exists()?;

    println!("SightingDB setup\n");
    println!(
        "Detected {} with {}, running as {}.\n",
        match platform {
            Platform::Linux => "Linux",
            Platform::MacOs => "macOS",
        },
        platform.service_manager(),
        if root { "root" } else { "an ordinary user" }
    );

    let scope = choose_scope(platform, root)?;
    let plan = build_plan(platform, scope, root)?;

    println!("\n{}", plan.describe());
    if !ask_yes_no("Go ahead?", true)? {
        println!("Nothing was changed.");
        return Ok(());
    }

    let applied = apply(&plan, &mut |path, what| ask_replace(path, what))?;
    report(&plan, applied);
    Ok(())
}

fn choose_scope(platform: Platform, root: bool) -> Result<Scope> {
    if !root {
        // Everything system-wide needs root, and re-running under sudo is a
        // better answer than failing halfway through.
        println!(
            "Installing for the current user. Run with sudo for a system-wide install\n\
             under /etc and /var/lib with its own service account.\n"
        );
        return Ok(Scope::User);
    }
    if platform == Platform::MacOs {
        // Creating a service account on macOS means hand-picking a UID through
        // dscl, which is not something to do silently on someone's machine.
        println!(
            "Running as root on macOS. This installs system-wide but does not create a\n\
             service account; the daemon runs as root unless you change the plist.\n"
        );
    }
    Ok(Scope::System)
}

fn build_plan(platform: Platform, scope: Scope, root: bool) -> Result<Plan> {
    let (config_dir, dbdir, service_path, binary) = match (scope, platform) {
        (Scope::System, Platform::Linux) => (
            PathBuf::from("/etc/sightingdb"),
            PathBuf::from("/var/lib/sightingdb"),
            PathBuf::from("/etc/systemd/system/sightingdb.service"),
            PathBuf::from("/usr/local/bin/sightingdb"),
        ),
        (Scope::System, Platform::MacOs) => (
            PathBuf::from("/usr/local/etc/sightingdb"),
            PathBuf::from("/usr/local/var/sightingdb"),
            PathBuf::from(format!("/Library/LaunchDaemons/{LAUNCHD_LABEL}.plist")),
            PathBuf::from("/usr/local/bin/sightingdb"),
        ),
        (Scope::User, _) => {
            let home = dirs::home_dir().context("finding your home directory")?;
            let config_dir = home.join(".sightingdb");
            let service_path = match platform {
                Platform::Linux => home.join(".config/systemd/user/sightingdb.service"),
                Platform::MacOs => home.join(format!("Library/LaunchAgents/{LAUNCHD_LABEL}.plist")),
            };
            // A user install runs the binary where cargo put it.
            let binary = std::env::current_exe().context("finding this executable")?;
            (
                config_dir.clone(),
                config_dir.join("db"),
                service_path,
                binary,
            )
        }
    };

    let mode = ask_mode()?;
    let namespaces = ask_namespaces(mode)?;
    let node_id = if mode.in_galaxy() {
        // Unique per server, because two sharing a name would each take the
        // other's contribution for their own.
        ask("This server's name in the galaxy", &default_node_id())?
    } else {
        crate::db::LOCAL_NODE.to_string()
    };

    let listen_ip = ask("Listen address", "127.0.0.1")?;
    let listen_port: u16 = ask_parsed("Listen port", "9999", "a port number")?;
    let use_tls = ask_yes_no("Serve HTTPS with a self-signed certificate?", true)?;
    let authenticate = ask_yes_no("Require an API key on the sighting API?", true)?;
    let dbdir = PathBuf::from(ask("Database directory", &dbdir.to_string_lossy())?);

    let tls = use_tls.then(|| TlsSettings {
        cert: config_dir.join("ssl/cert.pem"),
        key: config_dir.join("ssl/key.pem"),
    });

    let install_service = ask_yes_no(
        &format!("Install a {} service?", platform.service_manager()),
        true,
    )?;
    let start_service = install_service && ask_yes_no("Start it now?", true)?;

    Ok(Plan {
        scope,
        platform,
        service_user: (scope == Scope::System && platform == Platform::Linux)
            .then(|| SERVICE_USER.to_string()),
        config_path: config_dir.join("sightingdb.toml"),
        acl_path: config_dir.join("acl.toml"),
        tiers_path: config_dir.join("tiers.toml"),
        tags_path: config_dir.join("tags.toml"),
        peers_path: config_dir.join("peers.toml"),
        log_config_path: config_dir.join("log4rs.yml"),
        config_dir,
        dbdir,
        tls,
        listen_ip,
        listen_port,
        authenticate,
        mode,
        namespaces,
        node_id,
        admin_key: random_key(),
        binary,
        service_path,
        create_user: scope == Scope::System && platform == Platform::Linux && root,
        install_service,
        start_service,
    })
}

// ---------------------------------------------------------------------------
// Doing
// ---------------------------------------------------------------------------

/// Whether an existing file should be replaced.
///
/// Passed in rather than asked for directly so that carrying out a plan is not
/// tied to a terminal — otherwise nothing here could be tested without one.
pub type Decide<'a> = &'a mut dyn FnMut(&Path, &str) -> Result<bool>;

/// Never replace anything already there. Used by the tests, which have no
/// terminal to ask at.
#[cfg(test)]
pub fn keep_existing(_: &Path, _: &str) -> Result<bool> {
    Ok(false)
}

/// What carrying out a plan actually changed.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Applied {
    /// Whether a new admin key was written. On a re-run the existing keys are
    /// kept, and reporting the freshly generated one would hand out a key that
    /// does not work.
    pub wrote_admin_key: bool,
}

/// Carry out a plan. Split from the questions so it can be tested.
pub fn apply(plan: &Plan, decide: Decide) -> Result<Applied> {
    let mut applied = Applied::default();
    if plan.create_user {
        create_service_user()?;
    }

    fs::create_dir_all(&plan.config_dir)
        .with_context(|| format!("creating {}", plan.config_dir.display()))?;
    fs::create_dir_all(&plan.dbdir)
        .with_context(|| format!("creating {}", plan.dbdir.display()))?;

    write_unless_kept(
        &plan.config_path,
        &plan.config_toml(),
        0o640,
        "A configuration",
        decide,
    )?;
    write_unless_kept(
        &plan.log_config_path,
        LOG_CONFIG,
        0o644,
        "A logging configuration",
        decide,
    )?;

    // Only written when absent: replacing it would revoke every existing key.
    if plan.acl_path.exists() {
        println!(
            "\n  Keeping the API keys already in {}",
            plan.acl_path.display()
        );
    } else {
        let mut acl = Acl::new();
        acl.grant_full(&plan.admin_key);
        write_file(&plan.acl_path, &acl.to_toml(), 0o600)?;
        applied.wrote_admin_key = true;
    }

    if let Some(tls) = &plan.tls {
        if tls.cert.exists() || tls.key.exists() {
            println!(
                "\n  Keeping the certificate already in {}",
                tls.cert.display()
            );
        } else {
            crate::tls::install_self_signed(tls)?;
        }
    }

    // The database and the keys are the sensitive parts.
    set_mode(&plan.dbdir, 0o750)?;
    set_mode(&plan.config_dir, 0o750)?;

    if let Some(user) = &plan.service_user
        && plan.create_user
    {
        chown(&plan.dbdir, user)?;
        chown(&plan.config_dir, user)?;
    }

    if plan.install_service {
        install_binary(plan)?;
        write_unless_kept(
            &plan.service_path,
            &plan.service_unit(),
            0o644,
            "A service unit",
            decide,
        )?;
        if plan.start_service {
            start(plan)?;
        }
    }

    Ok(applied)
}

/// Write a file unless something is already there and the caller wants it kept.
fn write_unless_kept(
    path: &Path,
    contents: &str,
    mode: u32,
    what: &str,
    decide: Decide,
) -> Result<()> {
    if path.exists() && !decide(path, what)? {
        println!("  Keeping {}", path.display());
        return Ok(());
    }
    write_file(path, contents, mode)
}

fn write_file(path: &Path, contents: &str, mode: u32) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
    }
    fs::write(path, contents).with_context(|| format!("writing {}", path.display()))?;
    set_mode(path, mode)
}

fn set_mode(path: &Path, mode: u32) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(mode))
            .with_context(|| format!("setting the mode of {}", path.display()))?;
    }
    #[cfg(not(unix))]
    let _ = (path, mode);
    Ok(())
}

fn chown(path: &Path, user: &str) -> Result<()> {
    run_command(
        "chown",
        &["-R", &format!("{user}:{user}"), &path.to_string_lossy()],
    )
}

fn is_root() -> bool {
    #[cfg(unix)]
    {
        // Cheaper and dependency-free compared with reading the real uid.
        std::env::var("USER").map(|u| u == "root").unwrap_or(false)
            || Command::new("id")
                .arg("-u")
                .output()
                .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "0")
                .unwrap_or(false)
    }
    #[cfg(not(unix))]
    false
}

fn create_service_user() -> Result<()> {
    // Already there from an earlier run, which is fine.
    if Command::new("id")
        .arg(SERVICE_USER)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        println!("  The user {SERVICE_USER} already exists");
        return Ok(());
    }
    run_command(
        "useradd",
        &[
            "--system",
            "--no-create-home",
            "--shell",
            "/usr/sbin/nologin",
            SERVICE_USER,
        ],
    )
}

fn install_binary(plan: &Plan) -> Result<()> {
    let current = std::env::current_exe().context("finding this executable")?;
    if current == plan.binary {
        return Ok(());
    }
    if let Some(parent) = plan.binary.parent() {
        fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
    }
    fs::copy(&current, &plan.binary)
        .with_context(|| format!("copying the binary to {}", plan.binary.display()))?;
    set_mode(&plan.binary, 0o755)
}

fn start(plan: &Plan) -> Result<()> {
    match plan.platform {
        Platform::Linux => {
            let user_flag: &[&str] = if plan.scope == Scope::User {
                &["--user"]
            } else {
                &[]
            };
            let mut reload = user_flag.to_vec();
            reload.push("daemon-reload");
            run_command("systemctl", &reload)?;

            let mut enable = user_flag.to_vec();
            enable.extend(["enable", "--now", "sightingdb"]);
            run_command("systemctl", &enable)
        }
        Platform::MacOs => {
            let domain = if plan.scope == Scope::User {
                format!("gui/{}", uid())
            } else {
                "system".to_string()
            };
            // Replaces any earlier registration rather than failing on it.
            let _ = run_command(
                "launchctl",
                &["bootout", &format!("{domain}/{LAUNCHD_LABEL}")],
            );
            run_command(
                "launchctl",
                &["bootstrap", &domain, &plan.service_path.to_string_lossy()],
            )
        }
    }
}

fn uid() -> String {
    Command::new("id")
        .arg("-u")
        .output()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default()
}

fn run_command(program: &str, args: &[&str]) -> Result<()> {
    let output = Command::new(program)
        .args(args)
        .output()
        .with_context(|| format!("running {program}"))?;
    if !output.status.success() {
        bail!(
            "{program} {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

fn random_key() -> String {
    use rand::RngExt;
    const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let mut rng = rand::rng();
    (0..40)
        .map(|_| ALPHABET[rng.random_range(0..ALPHABET.len())] as char)
        .collect()
}

fn report(plan: &Plan, applied: Applied) {
    let scheme = if plan.tls.is_some() { "https" } else { "http" };
    println!("\nDone.\n");

    if applied.wrote_admin_key {
        println!("  Admin API key: {}", plan.admin_key);
        println!("  This is the only time it is shown. It is stored in plain text in");
        println!(
            "  {} — keep that file readable only by",
            plan.acl_path.display()
        );
        println!("  the account the service runs as.\n");
    } else {
        println!(
            "  The API keys already in {} were kept.\n",
            plan.acl_path.display()
        );
    }

    println!(
        "  Management interface: {scheme}://{}:{}/_management/",
        plan.listen_ip, plan.listen_port
    );
    if plan.tls.is_some() {
        println!("  The certificate is self-signed, so clients need curl -k or an exception.");
    }

    if plan.install_service && !plan.start_service {
        match plan.platform {
            Platform::Linux if plan.scope == Scope::User => {
                println!("\n  Start it with: systemctl --user start sightingdb")
            }
            Platform::Linux => println!("\n  Start it with: systemctl start sightingdb"),
            Platform::MacOs => println!(
                "\n  Start it with: launchctl bootstrap gui/$(id -u) {}",
                plan.service_path.display()
            ),
        }
    } else if !plan.install_service {
        println!(
            "\n  Run it with: sightingdb -c {}",
            plan.config_path.display()
        );
    }
}

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

    struct TempDir(PathBuf);

    impl TempDir {
        fn new(tag: &str) -> Self {
            let path = std::env::temp_dir().join(format!("sightingdb-setup-{tag}"));
            let _ = fs::remove_dir_all(&path);
            fs::create_dir_all(&path).unwrap();
            TempDir(path)
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    /// An installation in a directory of its own: a configuration naming an
    /// acl file, a tiers file, a certificate, a key and a database.
    fn installation_in(dir: &Path) -> PathBuf {
        let etc = dir.join("etc");
        let db = dir.join("var");
        fs::create_dir_all(etc.join("ssl")).unwrap();
        fs::create_dir_all(&db).unwrap();

        let config = etc.join("sightingdb.toml");
        fs::write(
            &config,
            format!(
                "[daemon]\nssl = true\nssl_cert = \"ssl/cert.pem\"\nssl_key = \"ssl/key.pem\"\n\
                 dbdir = \"{}\"\nacl_file = \"acl.toml\"\n\n[storage]\ntiers_file = \"tiers.toml\"\n",
                db.display()
            ),
        )
        .unwrap();
        fs::write(
            etc.join("acl.toml"),
            "[acl]\n\"changeme\" = \"rw, admin\"\n",
        )
        .unwrap();
        fs::write(etc.join("ssl/cert.pem"), "certificate").unwrap();
        fs::write(etc.join("ssl/key.pem"), "key").unwrap();
        // As `--setup` leaves them: the secrets readable only by their owner.
        set_mode(&etc.join("acl.toml"), 0o600).unwrap();
        set_mode(&etc.join("ssl/key.pem"), 0o600).unwrap();
        fs::write(db.join("feeds-abc.json.zst"), "snapshot").unwrap();
        fs::write(db.join("sightingdb.json.zst"), "snapshot").unwrap();
        config
    }

    #[test]
    fn the_report_lists_every_file_in_full() {
        let dir = TempDir::new("installed");
        let config = installation_in(&dir.0);

        // Given relatively, because that is how someone runs it and the report
        // is useless if it echoes back "sightingdb.toml".
        let relative = config
            .strip_prefix(std::env::current_dir().unwrap())
            .unwrap_or(&config);
        let report = installed_report(relative, None).unwrap();

        for expected in [
            "configuration",
            "API keys",
            "tiers",
            "TLS certificate",
            "TLS key",
            "database",
        ] {
            assert!(
                report.contains(expected),
                "{expected} is missing:\n{report}"
            );
        }
        // Every path absolute, and the sizes read from disk.
        assert!(
            report.contains(&full(&config).display().to_string()),
            "{report}"
        );
        assert!(
            report.contains("2 file(s)"),
            "the database directory:\n{report}"
        );
        // The tiers file has not been written yet, which is normal.
        assert!(report.contains("missing"), "{report}");
    }

    #[test]
    fn a_secret_anyone_can_read_is_called_out() {
        let dir = TempDir::new("installedmode");
        let config = installation_in(&dir.0);
        let acl = dir.0.join("etc/acl.toml");

        set_mode(&acl, 0o600).unwrap();
        let report = installed_report(&config, None).unwrap();
        assert!(!report.contains("WARNING"), "{report}");

        set_mode(&acl, 0o644).unwrap();
        let report = installed_report(&config, None).unwrap();
        assert!(report.contains("WARNING"), "{report}");
        assert!(report.contains("chmod 600"), "{report}");
    }

    /// The commands differ by platform and by whose service it is, and this is
    /// the part that cannot be tried out on the machine running the tests.
    #[test]
    fn service_commands_match_the_platform() {
        let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/x"));

        let unit = PathBuf::from("/etc/systemd/system/sightingdb.service");
        assert_eq!(
            service_commands(&unit, ServiceAction::Restart),
            [["systemctl", "restart", "sightingdb"]]
        );
        assert_eq!(
            service_commands(&unit, ServiceAction::Stop),
            [["systemctl", "stop", "sightingdb"]]
        );
        // Erasing disables it as well, or a reboot brings back what went.
        assert_eq!(
            service_commands(&unit, ServiceAction::Remove),
            [
                vec!["systemctl", "stop", "sightingdb"],
                vec!["systemctl", "disable", "sightingdb"]
            ]
        );

        let user_unit = home.join(".config/systemd/user/sightingdb.service");
        assert_eq!(
            service_commands(&user_unit, ServiceAction::Restart),
            [["systemctl", "--user", "restart", "sightingdb"]]
        );

        // launchd has no restart verb; kickstart -k is how it is spelled, with
        // an unload/load pair for systems too old to have it.
        let plist = PathBuf::from("/Library/LaunchDaemons/com.github.stricaud.sightingdb.plist");
        let restart = service_commands(&plist, ServiceAction::Restart);
        assert_eq!(
            restart[0],
            [
                "launchctl",
                "kickstart",
                "-k",
                "system/com.github.stricaud.sightingdb"
            ]
        );
        assert_eq!(restart[1][1], "unload");
        assert_eq!(restart[2][1], "load");

        let agent = home.join("Library/LaunchAgents/com.github.stricaud.sightingdb.plist");
        let stop = service_commands(&agent, ServiceAction::Stop);
        assert!(stop[0][2].starts_with("gui/"), "{stop:?}");
        assert!(
            stop[0][2].ends_with("com.github.stricaud.sightingdb"),
            "{stop:?}"
        );
    }

    #[test]
    fn erasing_asks_first_and_removes_nothing_if_refused() {
        let dir = TempDir::new("erasesaid no");
        let config = installation_in(&dir.0);

        let report = erase(&config, None, true, &|_| Ok(false)).unwrap();

        assert!(report.contains("Nothing was removed"), "{report}");
        assert!(config.exists());
        assert!(dir.0.join("var/feeds-abc.json.zst").exists());
    }

    #[test]
    fn erasing_hard_removes_the_installation_and_says_what_went() {
        let dir = TempDir::new("erase");
        let config = installation_in(&dir.0);
        let summary_shown = std::cell::RefCell::new(String::new());

        let report = erase(&config, None, true, &|summary| {
            summary_shown.replace(summary.to_string());
            Ok(true)
        })
        .unwrap();
        let summary_shown = summary_shown.into_inner();

        // What it said it would remove is what it removed.
        assert!(
            summary_shown.contains("cannot be recovered"),
            "{summary_shown}"
        );
        // What it will not touch is stated too, the binary among it.
        assert!(summary_shown.contains("And leaves:"), "{summary_shown}");
        assert!(summary_shown.contains("binary"), "{summary_shown}");
        for gone in [
            config.clone(),
            dir.0.join("etc/acl.toml"),
            dir.0.join("etc/ssl/cert.pem"),
            dir.0.join("etc/ssl/key.pem"),
            dir.0.join("var/feeds-abc.json.zst"),
            dir.0.join("var"),
        ] {
            assert!(!gone.exists(), "{} survived:\n{report}", gone.display());
        }
        // And the directories that only held them.
        assert!(!dir.0.join("etc/ssl").exists(), "{report}");
        assert!(!dir.0.join("etc").exists(), "{report}");
        assert!(report.contains("removed"), "{report}");
    }

    /// The invariant behind all of this, stated once: nothing `--erase` would
    /// remove may live outside the installation it was pointed at.
    ///
    /// The lookup for a logging configuration reaches into `/etc` and the home
    /// directory, and marking what it finds as ours is how erasing a temporary
    /// install deleted `~/.sightingdb/log4rs.yml` and then this repository's
    /// `etc/log4rs.yml` — from a test run, twice, before anyone typed the word.
    #[test]
    fn nothing_owned_lives_outside_the_installation() {
        let dir = TempDir::new("ownership");
        let config = installation_in(&dir.0);
        let root = full(&dir.0);

        // No logging configuration given, so the global lookup runs — which is
        // exactly the case that went wrong.
        for entry in inventory(&config, None).unwrap() {
            if entry.owned {
                assert!(
                    entry.path.starts_with(&root),
                    "{} ({}) is outside {} and would be erased",
                    entry.path.display(),
                    entry.what,
                    root.display()
                );
            }
        }
    }

    /// The soft erase: the database and the service go, the settings stay, so
    /// the same installation can be started again without answering `--setup`
    /// all over.
    #[test]
    fn erasing_keeps_the_configuration_unless_told_otherwise() {
        let dir = TempDir::new("erasesoft");
        let config = installation_in(&dir.0);
        let summary = std::cell::RefCell::new(String::new());

        let report = erase(&config, None, false, &|shown| {
            summary.replace(shown.to_string());
            Ok(true)
        })
        .unwrap();

        // The database is gone.
        assert!(!dir.0.join("var/feeds-abc.json.zst").exists(), "{report}");
        assert!(!dir.0.join("var").exists(), "{report}");

        // The settings are not.
        for kept in [
            "etc/sightingdb.toml",
            "etc/acl.toml",
            "etc/ssl/cert.pem",
            "etc/ssl/key.pem",
        ] {
            assert!(dir.0.join(kept).exists(), "{kept} went:\n{report}");
        }

        // And it said as much before doing anything.
        let summary = summary.into_inner();
        assert!(summary.contains("And leaves:"), "{summary}");
        assert!(summary.contains("--erase-hard"), "{summary}");
        assert!(
            report.contains("The configuration is still there"),
            "{report}"
        );
    }

    /// Regression: a logging configuration found in the usual places belongs
    /// to the machine, not to whichever installation happened to be erased.
    /// This removed one out of a home directory while erasing a temporary
    /// install, which is exactly the sort of reach a destructive command must
    /// not have.
    #[test]
    fn erasing_leaves_a_logging_config_that_is_not_ours() {
        let dir = TempDir::new("eraselogging");
        let config = installation_in(&dir.0);

        // Somewhere else entirely, as /etc/log4rs.yml or ~/.sightingdb is.
        let elsewhere = dir.0.join("machine-wide");
        fs::create_dir_all(&elsewhere).unwrap();
        let logging = elsewhere.join("log4rs.yml");
        fs::write(&logging, LOG_CONFIG).unwrap();

        let listed = installed_report(&config, Some(&logging)).unwrap();
        assert!(listed.contains("not this installation's"), "{listed}");

        let report = erase(&config, Some(&logging), true, &|_| Ok(true)).unwrap();

        assert!(
            logging.exists(),
            "the logging configuration went:\n{report}"
        );
        assert!(!config.exists(), "{report}");
    }

    /// The same rule for a service: a unit that runs a different configuration
    /// is somebody else's, and is neither stopped nor removed.
    #[test]
    fn a_service_for_another_configuration_is_left_alone() {
        let dir = TempDir::new("erasefile");
        let config = installation_in(&dir.0);

        let entries = inventory(&config, None).unwrap();
        let service = entries
            .iter()
            .find(|entry| entry.what == "service")
            .unwrap();
        // Nothing on this machine's service path was written by this test, so
        // whatever is there — usually nothing — is not ours to touch.
        assert!(!service.owned, "{}", service.path.display());
    }

    /// A logging configuration written beside the configuration *is* ours.
    #[test]
    fn a_logging_config_in_the_install_directory_is_erased() {
        let dir = TempDir::new("eraseowned");
        let config = installation_in(&dir.0);
        let logging = dir.0.join("etc/log4rs.yml");
        fs::write(&logging, LOG_CONFIG).unwrap();

        let report = erase(&config, Some(&logging), true, &|_| Ok(true)).unwrap();

        assert!(!logging.exists(), "{report}");
    }

    /// A database directory shared with something else is a mistake to report,
    /// not one to act on: the snapshots go, the stranger stays, and so does
    /// the directory.
    #[test]
    fn erasing_leaves_files_that_are_not_ours() {
        let dir = TempDir::new("erasestranger");
        let config = installation_in(&dir.0);
        let stranger = dir.0.join("var/notes.txt");
        fs::write(&stranger, "someone else's").unwrap();

        let report = erase(&config, None, true, &|_| Ok(true)).unwrap();

        assert!(stranger.exists(), "{report}");
        assert!(!dir.0.join("var/feeds-abc.json.zst").exists(), "{report}");
        assert!(dir.0.join("var").exists(), "the directory stays:\n{report}");
        assert!(report.contains("other file(s) left"), "{report}");
    }

    /// Nothing shallow or shared is ever tidied away, whatever a configuration
    /// points at.
    #[test]
    fn common_directories_are_never_tidied() {
        for dir in ["/", "/etc", "/var", "/var/lib", "/usr/local", "/tmp"] {
            assert!(!safe_to_tidy(Path::new(dir)), "{dir}");
        }
        if let Some(home) = dirs::home_dir() {
            assert!(!safe_to_tidy(&home), "the home directory itself");
            assert!(
                safe_to_tidy(&home.join(".sightingdb")),
                "an install of ours"
            );
        }
        assert!(safe_to_tidy(Path::new("/etc/sightingdb")));
    }

    /// Whatever mode is chosen, the file it writes must load.
    ///
    /// The point of generating a configuration is that it starts; a template
    /// the program cannot read back is worse than no template, and the
    /// comments are easy to get wrong in a way only parsing catches.
    #[test]
    fn every_mode_writes_a_configuration_that_loads() {
        let cases = [
            ("standalone", Mode::Standalone, None),
            ("node-all", Mode::Node, None),
            ("node-some", Mode::Node, Some(vec!["feeds".to_string()])),
            ("router", Mode::Router, Some(Vec::new())),
            (
                "both",
                Mode::Both,
                Some(vec!["feeds".to_string(), "threats".to_string()]),
            ),
        ];

        for (name, mode, namespaces) in cases {
            for tls in [true, false] {
                let dir = TempDir::new(&format!("{name}-{tls}"));
                let plan = plan_as(&dir.0, Platform::Linux, tls, mode, namespaces.clone());
                let toml = plan.config_toml();

                fs::create_dir_all(plan.config_dir.clone()).unwrap();
                fs::write(&plan.config_path, &toml).unwrap();
                let settings = crate::config::Settings::load(&plan.config_path)
                    .unwrap_or_else(|e| panic!("{name} tls={tls} did not load: {e:#}\n{toml}"));

                // And what it loaded is what was asked for.
                assert_eq!(settings.node_id, plan.node_id, "{name}");
                match &namespaces {
                    None => assert!(
                        settings.storage.stores_everything(),
                        "{name} should store everything:\n{toml}"
                    ),
                    Some(held) if held.is_empty() => assert!(
                        settings.storage.is_router(),
                        "{name} should be a router:\n{toml}"
                    ),
                    Some(held) => {
                        for prefix in held {
                            assert!(
                                settings.storage.holds(prefix),
                                "{name} should hold {prefix}:\n{toml}"
                            );
                        }
                        assert!(
                            !settings.storage.holds("somewhere-else"),
                            "{name} should not hold everything:\n{toml}"
                        );
                    }
                }

                // Tag colours are editable, which needs the file to exist as a
                // setting rather than as a comment.
                assert_eq!(
                    settings.tags_file.as_deref(),
                    Some(plan.tags_path.as_path()),
                    "{name} cannot edit tag colours:\n{toml}"
                );

                // A mode that forwards gets a galaxy it can manage: the
                // section loads with no peers, and names where peers added
                // from the interface go. Without both, adding one means
                // editing this file and restarting.
                if mode.forwards() {
                    let galaxy = settings
                        .galaxy
                        .as_ref()
                        .unwrap_or_else(|| panic!("{name} has no galaxy:\n{toml}"));
                    assert!(
                        galaxy.peers.is_empty(),
                        "{name} was given peers whose keys nobody has yet:\n{toml}"
                    );
                    assert_eq!(
                        galaxy.peers_file.as_deref(),
                        Some(plan.peers_path.as_path()),
                        "{name} cannot be given peers from the interface:\n{toml}"
                    );
                } else {
                    assert!(
                        settings.galaxy.is_none(),
                        "{name} was given a galaxy it did not ask for:\n{toml}"
                    );
                }
            }
        }
    }

    /// A galaxy section is offered to the modes that forward and not to the
    /// others.
    ///
    /// It is *live* with no peers in it, which is a valid galaxy, and carries a
    /// `peers_file` — so peers can be added from the management interface once
    /// the other servers exist, rather than by editing this file and
    /// restarting. A peer's key comes from that peer's own ACL, which does not
    /// exist when this file is written, so the list cannot be filled in here
    /// however it is formatted; what this avoids is having to come back to the
    /// file at all.
    #[test]
    fn a_galaxy_template_is_offered_only_where_it_is_wanted() {
        let dir = TempDir::new("galaxytemplate");

        for mode in [Mode::Standalone, Mode::Node] {
            let toml = plan_as(&dir.0, Platform::Linux, true, mode, None).config_toml();
            assert!(
                !toml.contains("[galaxy]"),
                "{} was offered a galaxy section:\n{toml}",
                mode.label()
            );
        }

        for mode in [Mode::Router, Mode::Both] {
            let namespaces = if mode == Mode::Router {
                Some(Vec::new())
            } else {
                Some(vec!["feeds".to_string()])
            };
            let toml = plan_as(&dir.0, Platform::Linux, true, mode, namespaces).config_toml();

            // Live, not commented: the interface can only manage peers if the
            // section it writes them to exists.
            assert!(
                toml.lines().any(|line| line.trim_end() == "[galaxy]"),
                "{} has no live galaxy section:\n{toml}",
                mode.label()
            );
            assert!(
                toml.lines().any(|line| line.starts_with("peers_file = ")),
                "{} was given no peers_file, so its galaxy is read-only in the \
                 interface:\n{toml}",
                mode.label()
            );
            // The example list stays commented: a peer written there is not
            // editable from the interface, and its key is not known yet anyway.
            assert!(
                toml.contains("#peers = ["),
                "the example peer list should stay commented:\n{toml}"
            );
            assert!(
                !toml.lines().any(|line| line.starts_with("peers = [")),
                "a live peer list was written with keys nobody has yet:\n{toml}"
            );
            assert!(toml.contains("namespaces = [\"feeds\"]"), "{toml}");
        }
    }

    /// The generated configuration names a tags_file, so tag colours are
    /// editable in the interface rather than read-only.
    #[test]
    fn the_generated_configuration_can_edit_tag_colours() {
        let dir = TempDir::new("tagsfile");
        for mode in [Mode::Standalone, Mode::Node, Mode::Router, Mode::Both] {
            let namespaces = matches!(mode, Mode::Router).then(Vec::new);
            let toml = plan_as(&dir.0, Platform::Linux, true, mode, namespaces).config_toml();
            assert!(
                toml.lines().any(|line| line.starts_with("tags_file = ")),
                "{} was given no tags_file:\n{toml}",
                mode.label()
            );
        }
    }

    /// The generated file is mostly explanation, which is the point: it is
    /// where someone goes to change their mind.
    #[test]
    fn the_generated_configuration_explains_itself() {
        let dir = TempDir::new("comments");
        let toml = plan_as(
            &dir.0,
            Platform::Linux,
            true,
            Mode::Router,
            Some(Vec::new()),
        )
        .config_toml();

        let comments = toml
            .lines()
            .filter(|l| l.trim_start().starts_with('#'))
            .count();
        let settings = toml
            .lines()
            .filter(|l| l.contains('=') && !l.trim_start().starts_with('#'))
            .count();
        assert!(
            comments > settings,
            "only {comments} comment lines for {settings} settings:\n{toml}"
        );

        // Each section says what it is for.
        for mentioned in ["[daemon]", "[storage]", "node_id", "snapshot_interval"] {
            assert!(toml.contains(mentioned), "{mentioned} missing:\n{toml}");
        }
        assert!(
            toml.contains("set up as a router"),
            "the file does not say what mode it is:\n{toml}"
        );
    }

    /// A node id has to be usable as one: the hostname is cleaned up rather
    /// than written through, since a dotted or odd name would be refused by
    /// the configuration loader this same setup just wrote a file for.
    #[test]
    fn the_default_node_id_is_a_usable_one() {
        let id = default_node_id();

        assert!(!id.is_empty());
        assert!(id.len() <= 64, "{id}");
        assert!(
            id.chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')),
            "{id} has characters a node id may not carry"
        );
    }

    /// A plan that only touches the given directory: no user, no service.
    fn plan_in(dir: &Path, platform: Platform, tls: bool) -> Plan {
        plan_as(dir, platform, tls, Mode::Standalone, None)
    }

    /// The same, in a chosen mode.
    fn plan_as(
        dir: &Path,
        platform: Platform,
        tls: bool,
        mode: Mode,
        namespaces: Option<Vec<String>>,
    ) -> Plan {
        let config_dir = dir.join("etc");
        Plan {
            scope: Scope::User,
            platform,
            mode,
            namespaces,
            node_id: if mode == Mode::Standalone {
                crate::db::LOCAL_NODE.to_string()
            } else {
                "test-node".to_string()
            },
            service_user: None,
            config_path: config_dir.join("sightingdb.toml"),
            acl_path: config_dir.join("acl.toml"),
            tiers_path: config_dir.join("tiers.toml"),
            tags_path: config_dir.join("tags.toml"),
            peers_path: config_dir.join("peers.toml"),
            log_config_path: config_dir.join("log4rs.yml"),
            dbdir: dir.join("db"),
            tls: tls.then(|| TlsSettings {
                cert: config_dir.join("ssl/cert.pem"),
                key: config_dir.join("ssl/key.pem"),
            }),
            config_dir,
            listen_ip: "127.0.0.1".into(),
            listen_port: 9999,
            authenticate: true,
            admin_key: "test-admin-key".into(),
            binary: dir.join("bin/sightingdb"),
            service_path: dir.join("service"),
            create_user: false,
            install_service: false,
            start_service: false,
        }
    }

    #[test]
    fn a_plan_produces_a_configuration_the_program_can_read() {
        let dir = TempDir::new("config");
        let plan = plan_in(&dir.0, Platform::Linux, true);
        apply(&plan, &mut keep_existing).unwrap();

        // The real test: the config it wrote actually loads.
        let settings = crate::config::Settings::load(&plan.config_path).unwrap();
        assert_eq!(settings.listen, "127.0.0.1:9999");
        assert!(settings.authenticate);
        assert_eq!(settings.dbdir, Some(plan.dbdir.clone()));
        assert_eq!(settings.acl_file, Some(plan.acl_path.clone()));
        assert!(settings.tls.is_some());
    }

    #[test]
    fn the_generated_certificate_matches_the_configuration() {
        let dir = TempDir::new("certs");
        let plan = plan_in(&dir.0, Platform::Linux, true);
        apply(&plan, &mut keep_existing).unwrap();

        let tls = plan.tls.clone().unwrap();
        assert!(tls.cert.exists() && tls.key.exists());
        // Loads as a server identity, which is what the daemon will do.
        crate::tls::acceptor(&tls).unwrap();
    }

    #[test]
    fn without_tls_the_configuration_says_so() {
        let dir = TempDir::new("notls");
        let plan = plan_in(&dir.0, Platform::Linux, false);
        apply(&plan, &mut keep_existing).unwrap();

        let settings = crate::config::Settings::load(&plan.config_path).unwrap();
        assert_eq!(settings.tls, None);
        assert!(!plan.config_dir.join("ssl").exists());
    }

    #[test]
    fn the_admin_key_is_written_and_usable() {
        let dir = TempDir::new("key");
        let plan = plan_in(&dir.0, Platform::Linux, false);
        apply(&plan, &mut keep_existing).unwrap();

        let settings = crate::config::Settings::load(&plan.config_path).unwrap();
        let acl = settings.acl.unwrap();
        assert!(acl.is_admin("test-admin-key"));
        assert!(acl.can_write("test-admin-key", "anything"));
    }

    /// Reporting a key that was never written would hand out one that does
    /// not work.
    #[test]
    fn a_rerun_does_not_claim_to_have_written_a_key() {
        let dir = TempDir::new("rerunkey");
        let plan = plan_in(&dir.0, Platform::Linux, false);

        let first = apply(&plan, &mut keep_existing).unwrap();
        assert!(first.wrote_admin_key);

        let second = apply(&plan, &mut keep_existing).unwrap();
        assert!(!second.wrote_admin_key);
    }

    /// Re-running setup must not revoke every key that already exists.
    #[test]
    fn existing_api_keys_are_never_replaced() {
        let dir = TempDir::new("keepkeys");
        let plan = plan_in(&dir.0, Platform::Linux, false);
        apply(&plan, &mut keep_existing).unwrap();

        let mut second = plan.clone();
        second.admin_key = "a-different-key".into();
        apply(&second, &mut keep_existing).unwrap();

        let acl = crate::config::Settings::load(&plan.config_path)
            .unwrap()
            .acl
            .unwrap();
        assert!(acl.is_admin("test-admin-key"), "the original key was lost");
        assert!(!acl.contains("a-different-key"));
    }

    /// Likewise a certificate: replacing one silently would break every client
    /// that had accepted it.
    #[test]
    fn an_existing_certificate_is_kept() {
        let dir = TempDir::new("keepcert");
        let plan = plan_in(&dir.0, Platform::Linux, true);
        apply(&plan, &mut keep_existing).unwrap();
        let original = fs::read(&plan.tls.clone().unwrap().cert).unwrap();

        apply(&plan, &mut keep_existing).unwrap();

        assert_eq!(fs::read(&plan.tls.unwrap().cert).unwrap(), original);
    }

    #[cfg(unix)]
    #[test]
    fn the_sensitive_files_are_not_world_readable() {
        use std::os::unix::fs::PermissionsExt;

        let dir = TempDir::new("modes");
        let plan = plan_in(&dir.0, Platform::Linux, true);
        apply(&plan, &mut keep_existing).unwrap();

        let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode(&plan.acl_path), 0o600, "API keys");
        assert_eq!(mode(&plan.tls.clone().unwrap().key), 0o600, "private key");
        assert_eq!(mode(&plan.config_path), 0o640, "configuration");
        assert_eq!(mode(&plan.dbdir), 0o750, "database");
    }

    #[test]
    fn a_systemd_unit_names_the_paths_it_was_given() {
        let dir = TempDir::new("systemd");
        let mut plan = plan_in(&dir.0, Platform::Linux, true);
        plan.service_user = Some("sightingdb".into());
        let unit = plan.service_unit();

        assert!(unit.contains("User=sightingdb"), "{unit}");
        assert!(
            unit.contains(&plan.config_path.display().to_string()),
            "{unit}"
        );
        assert!(unit.contains(&plan.dbdir.display().to_string()), "{unit}");
        // Time for the final snapshot to be written.
        assert!(unit.contains("TimeoutStopSec"), "{unit}");
    }

    #[test]
    fn a_launchd_plist_is_well_formed_enough_to_name_its_paths() {
        let dir = TempDir::new("launchd");
        let plan = plan_in(&dir.0, Platform::MacOs, false);
        let plist = plan.service_unit();

        assert!(plist.starts_with("<?xml"), "{plist}");
        assert!(plist.contains("<key>Label</key>"), "{plist}");
        assert!(plist.contains(LAUNCHD_LABEL), "{plist}");
        assert!(
            plist.contains(&plan.config_path.display().to_string()),
            "{plist}"
        );
        assert_eq!(
            plist.matches("<dict>").count(),
            plist.matches("</dict>").count()
        );
    }

    #[test]
    fn the_plan_says_what_it_will_do_before_doing_it() {
        let dir = TempDir::new("describe");
        let mut plan = plan_in(&dir.0, Platform::Linux, true);
        plan.create_user = true;
        plan.service_user = Some("sightingdb".into());
        plan.install_service = true;

        let described = plan.describe();
        for expected in [
            "create the system user   sightingdb",
            "configuration",
            "self-signed certificate",
            "https://127.0.0.1:9999",
        ] {
            assert!(
                described.contains(expected),
                "missing {expected:?}:\n{described}"
            );
        }
    }

    #[test]
    fn a_generated_key_is_acceptable_as_an_api_key() {
        let key = random_key();
        assert_eq!(key.len(), 40);
        assert!(crate::acl::validate_key(&key).is_ok());
        assert_ne!(key, random_key());
    }
}