numa 0.15.1

Portable DNS resolver in Rust — .numa local domains, ad blocking, developer overrides, DNS-over-HTTPS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
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
use std::net::SocketAddr;

use log::info;

#[cfg(any(target_os = "macos", target_os = "linux"))]
use crate::forward::Upstream;
use crate::forward::UpstreamPool;

fn print_recursive_hint() {
    let is_recursive = crate::config::load_config("numa.toml")
        .map(|c| c.config.upstream.mode == crate::config::UpstreamMode::Recursive)
        .unwrap_or(false);
    if !is_recursive {
        eprintln!("  Want full DNS sovereignty? Add to numa.toml:");
        eprintln!("    [upstream]");
        eprintln!("    mode = \"recursive\"\n");
    }
}

fn is_loopback_or_stub(addr: &str) -> bool {
    // fec0:0:0:ffff::1/2/3 are the deprecated IPv6 site-local stubs that
    // Get-DnsClientServerAddress returns for any IPv6-enabled adapter
    // without explicit DNS — they're not real upstreams.
    matches!(
        addr,
        "127.0.0.1"
            | "127.0.0.53"
            | "0.0.0.0"
            | "::1"
            | "fec0:0:0:ffff::1"
            | "fec0:0:0:ffff::2"
            | "fec0:0:0:ffff::3"
            | ""
    )
}

/// A conditional forwarding rule: domains matching `suffix` are forwarded to `upstream`.
#[derive(Clone)]
pub struct ForwardingRule {
    pub suffix: String,
    dot_suffix: String, // pre-computed ".suffix" for zero-alloc matching
    pub upstream: UpstreamPool,
}

impl ForwardingRule {
    pub fn new(suffix: String, upstream: UpstreamPool) -> Self {
        let dot_suffix = format!(".{}", suffix);
        Self {
            suffix,
            dot_suffix,
            upstream,
        }
    }
}

/// Result of system DNS discovery — default upstream + conditional forwarding rules.
pub struct SystemDnsInfo {
    pub default_upstream: Option<String>,
    pub forwarding_rules: Vec<ForwardingRule>,
}

/// Discover system DNS configuration in a single pass.
/// On macOS: parses `scutil --dns` once for both the default upstream and forwarding rules.
/// On Linux: reads `/etc/resolv.conf` for upstream, no forwarding rules yet.
pub fn discover_system_dns() -> SystemDnsInfo {
    #[cfg(target_os = "macos")]
    {
        discover_macos()
    }
    #[cfg(target_os = "linux")]
    {
        discover_linux()
    }
    #[cfg(windows)]
    {
        discover_windows()
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    {
        log::debug!("no conditional forwarding rules discovered");
        SystemDnsInfo {
            default_upstream: None,
            forwarding_rules: Vec::new(),
        }
    }
}

/// Advisory for port-53 bind failures (EADDRINUSE or EACCES); `None`
/// if not applicable so the caller can fall back to the raw error.
pub fn try_port53_advisory(bind_addr: &str, err: &std::io::Error) -> Option<String> {
    if !is_port_53(bind_addr) {
        return None;
    }
    let (title, cause) = match err.kind() {
        std::io::ErrorKind::AddrInUse => (
            "port 53 is already in use",
            "Another process is already bound to port 53. On Linux this is\n  \
             typically systemd-resolved; on Windows, the DNS Client service.",
        ),
        std::io::ErrorKind::PermissionDenied => (
            "permission denied",
            "Port 53 is privileged — binding it requires root on Linux/macOS\n  \
             or Administrator on Windows.",
        ),
        _ => return None,
    };
    let o = "\x1b[1;38;2;192;98;58m"; // bold orange
    let r = "\x1b[0m";
    Some(format!(
        "
{o}Numa{r} — cannot bind to {bind_addr}: {title}.

  {cause}

  Fix — pick one:

    1. Install Numa as the system resolver (frees port 53):

         sudo numa install       (on Windows, run as Administrator)

    2. Run on a non-privileged port for testing.
       Create {} with:

         [server]
         bind_addr = \"127.0.0.1:5354\"
         api_port  = 5380

       Then run:  numa
       Test with: dig @127.0.0.1 -p 5354 example.com

",
        crate::suggested_config_path().display()
    ))
}

fn is_port_53(bind_addr: &str) -> bool {
    bind_addr
        .parse::<SocketAddr>()
        .map(|s| s.port() == 53)
        .unwrap_or(false)
}

#[cfg(target_os = "macos")]
#[derive(Default)]
struct ScutilState {
    rules: Vec<ForwardingRule>,
    default_upstream: Option<String>,
    current_domain: Option<String>,
    current_nameserver: Option<String>,
    is_supplemental: bool,
}

#[cfg(target_os = "macos")]
impl ScutilState {
    fn flush(&mut self) {
        if let (Some(domain), Some(ns), true) = (
            self.current_domain.take(),
            self.current_nameserver.take(),
            self.is_supplemental,
        ) {
            if let Some(rule) = make_rule(&domain, &ns) {
                self.rules.push(rule);
            }
        }
        self.is_supplemental = false;
    }

    fn set_domain(&mut self, line: &str) {
        let Some(val) = line.split(':').nth(1) else {
            return;
        };
        let domain = val.trim().trim_end_matches('.').to_lowercase();
        if !domain.is_empty()
            && domain != "local"
            && !domain.ends_with("in-addr.arpa")
            && !domain.ends_with("ip6.arpa")
        {
            self.current_domain = Some(domain);
        }
    }

    fn set_nameserver(&mut self, line: &str) {
        let Some(val) = line.split(':').nth(1) else {
            return;
        };
        let ns = val.trim().to_string();
        if ns.parse::<std::net::Ipv4Addr>().is_err() {
            return;
        }
        if !self.is_supplemental && self.default_upstream.is_none() && !is_loopback_or_stub(&ns) {
            self.default_upstream = Some(ns.clone());
        }
        self.current_nameserver = Some(ns);
    }

    /// Returns true when the parser should stop.
    fn handle_line(&mut self, line: &str) -> bool {
        if line.starts_with("resolver #") {
            self.flush();
        } else if line.starts_with("domain") && line.contains(':') {
            self.set_domain(line);
        } else if line.starts_with("nameserver[0]") && line.contains(':') {
            self.set_nameserver(line);
        } else if line.starts_with("flags") && line.contains("Supplemental") {
            self.is_supplemental = true;
        } else if line.starts_with("DNS configuration (for scoped") {
            self.flush();
            return true;
        }
        false
    }
}

#[cfg(target_os = "macos")]
fn discover_macos() -> SystemDnsInfo {
    use log::{debug, warn};

    let output = match std::process::Command::new("scutil").arg("--dns").output() {
        Ok(o) => o,
        Err(e) => {
            warn!("failed to run scutil --dns: {}", e);
            return SystemDnsInfo {
                default_upstream: None,
                forwarding_rules: Vec::new(),
            };
        }
    };

    let text = String::from_utf8_lossy(&output.stdout);
    let mut state = ScutilState::default();
    for line in text.lines() {
        if state.handle_line(line.trim()) {
            break;
        }
    }
    state.flush();

    let ScutilState {
        mut rules,
        default_upstream,
        ..
    } = state;
    rules.sort_by_key(|r| std::cmp::Reverse(r.suffix.len()));

    for rule in &rules {
        info!(
            "auto-discovered forwarding: *.{} -> {}",
            rule.suffix,
            rule.upstream.label()
        );
    }
    if rules.is_empty() {
        debug!("no conditional forwarding rules discovered");
    }
    if let Some(ref ns) = default_upstream {
        info!("detected system upstream: {}", ns);
    }

    SystemDnsInfo {
        default_upstream,
        forwarding_rules: rules,
    }
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
fn make_rule(domain: &str, nameserver: &str) -> Option<ForwardingRule> {
    let addr = crate::forward::parse_upstream_addr(nameserver, 53).ok()?;
    let pool = UpstreamPool::new(vec![Upstream::Udp(addr)], vec![]);
    Some(ForwardingRule::new(domain.to_string(), pool))
}

#[cfg(target_os = "linux")]
const CLOUD_VPC_RESOLVER: &str = "169.254.169.253";

#[cfg(target_os = "linux")]
fn discover_linux() -> SystemDnsInfo {
    // Parse resolv.conf once for both upstream and search domains
    let (upstream, search_domains) = parse_resolv_conf("/etc/resolv.conf");

    let default_upstream = if let Some(ns) = upstream {
        info!("detected system upstream: {}", ns);
        Some(ns)
    } else if let Some(ns) = resolvectl_dns_server() {
        info!("detected system upstream via resolvectl: {}", ns);
        Some(ns)
    } else {
        // Fallback to backup from a previous `numa install`
        let backup = {
            let home = std::env::var("HOME")
                .map(std::path::PathBuf::from)
                .unwrap_or_else(|_| std::path::PathBuf::from("/root"));
            home.join(".numa").join("original-resolv.conf")
        };
        let (ns, _) = parse_resolv_conf(backup.to_str().unwrap_or(""));
        if let Some(ref ns) = ns {
            info!("detected original upstream from backup: {}", ns);
        }
        ns
    };

    // On cloud VMs (AWS/GCP), internal domains need to reach the VPC resolver
    let forwarding_rules = if search_domains.is_empty() {
        Vec::new()
    } else {
        let forwarder = resolvectl_dns_server().unwrap_or_else(|| CLOUD_VPC_RESOLVER.to_string());
        let rules: Vec<_> = search_domains
            .iter()
            .filter_map(|domain| {
                let rule = make_rule(domain, &forwarder)?;
                info!("forwarding .{} to {}", domain, forwarder);
                Some(rule)
            })
            .collect();
        if !rules.is_empty() {
            info!("detected {} search domain forwarding rules", rules.len());
        }
        rules
    };

    SystemDnsInfo {
        default_upstream,
        forwarding_rules,
    }
}

/// Yield each `nameserver` address from resolv.conf content. No filtering —
/// callers decide what counts as a real upstream.
#[cfg(any(target_os = "linux", test))]
fn iter_nameservers(content: &str) -> impl Iterator<Item = &str> {
    content.lines().filter_map(|line| {
        let mut parts = line.split_whitespace();
        (parts.next() == Some("nameserver")).then_some(())?;
        parts.next()
    })
}

/// Parse resolv.conf in a single pass, extracting the first non-loopback
/// nameserver and all search domains.
#[cfg(target_os = "linux")]
fn parse_resolv_conf(path: &str) -> (Option<String>, Vec<String>) {
    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(_) => return (None, Vec::new()),
    };
    let upstream = iter_nameservers(&text)
        .find(|ns| !is_loopback_or_stub(ns))
        .map(str::to_string);
    let mut search_domains = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if line.starts_with("search") || line.starts_with("domain") {
            for domain in line.split_whitespace().skip(1) {
                search_domains.push(domain.to_string());
            }
        }
    }
    (upstream, search_domains)
}

/// True if the resolv.conf *content* appears to be written by numa itself,
/// or has no real upstream — either way, it's not a safe source of truth
/// for a backup.
#[cfg(any(target_os = "linux", test))]
fn resolv_conf_is_numa_managed(content: &str) -> bool {
    content.contains("Generated by Numa") || !resolv_conf_has_real_upstream(content)
}

/// True if the resolv.conf content has at least one non-loopback, non-stub
/// nameserver. An all-loopback resolv.conf is self-referential.
#[cfg(any(target_os = "linux", test))]
fn resolv_conf_has_real_upstream(content: &str) -> bool {
    iter_nameservers(content).any(|ns| !is_loopback_or_stub(ns))
}

/// Query resolvectl for the real upstream DNS server (e.g. VPC resolver on AWS).
#[cfg(target_os = "linux")]
fn resolvectl_dns_server() -> Option<String> {
    let output = std::process::Command::new("resolvectl")
        .args(["status", "--no-pager"])
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&output.stdout);
    for line in text.lines() {
        if line.contains("DNS Servers") || line.contains("Current DNS Server") {
            if let Some(ip) = line.split(':').next_back() {
                let ip = ip.trim();
                if ip.parse::<std::net::IpAddr>().is_ok() && !is_loopback_or_stub(ip) {
                    return Some(ip.to_string());
                }
            }
        }
    }
    None
}

/// Detect DNS server from DHCP lease — fallback when scutil/resolv.conf only shows 127.0.0.1.
/// On macOS: parses `ipconfig getpacket en0` for domain_name_server.
/// On Linux/Windows: returns None (not implemented yet).
pub fn detect_dhcp_dns() -> Option<String> {
    #[cfg(target_os = "macos")]
    {
        detect_dhcp_dns_macos()
    }
    #[cfg(not(target_os = "macos"))]
    {
        None
    }
}

#[cfg(target_os = "macos")]
fn detect_dhcp_dns_macos() -> Option<String> {
    // Try common interfaces
    for iface in &["en0", "en1"] {
        let output = std::process::Command::new("ipconfig")
            .args(["getpacket", iface])
            .output()
            .ok()?;
        let text = String::from_utf8_lossy(&output.stdout);
        for line in text.lines() {
            if line.contains("domain_name_server") {
                // Format: "domain_name_server (ip_mult): {213.154.124.25, 1.0.0.1}"
                if let Some(braces) = line.split('{').nth(1) {
                    let inner = braces.trim_end_matches('}').trim();
                    // Take the first non-loopback DNS server
                    for addr in inner.split(',') {
                        let addr = addr.trim();
                        if !is_loopback_or_stub(addr) && addr.parse::<std::net::Ipv4Addr>().is_ok()
                        {
                            log::info!("detected DHCP DNS: {}", addr);
                            return Some(addr.to_string());
                        }
                    }
                }
            }
        }
    }
    None
}

// --- Windows implementation ---

#[cfg(windows)]
fn discover_windows() -> SystemDnsInfo {
    use log::{debug, warn};

    let output = match std::process::Command::new("ipconfig").arg("/all").output() {
        Ok(o) => o,
        Err(e) => {
            warn!("failed to run ipconfig /all: {}", e);
            return SystemDnsInfo {
                default_upstream: None,
                forwarding_rules: Vec::new(),
            };
        }
    };

    let text = String::from_utf8_lossy(&output.stdout);
    let mut upstream = None;

    for line in text.lines() {
        let trimmed = line.trim();
        // Match "DNS Servers" line (English) or similar localized variants
        if trimmed.contains("DNS Servers") || trimmed.contains("DNS-Server") {
            if let Some(ip) = trimmed.split(':').next_back() {
                let ip = ip.trim();
                if ip.parse::<std::net::IpAddr>().is_ok() && !is_loopback_or_stub(ip) {
                    upstream = Some(ip.to_string());
                    break;
                }
            }
        }
        // Continuation lines (indented IPs after DNS Servers line)
        if upstream.is_none() && trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) {
            // Skip continuation lines — we only need the first DNS server
        }
    }

    if let Some(ref ns) = upstream {
        info!("detected Windows upstream: {}", ns);
    } else {
        debug!("no DNS servers found in ipconfig output");
    }

    SystemDnsInfo {
        default_upstream: upstream,
        forwarding_rules: Vec::new(),
    }
}

#[cfg(any(windows, test))]
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
struct WindowsInterfaceDns {
    // Passed to netsh's [name=] slot since friendly names fail with
    // ERROR_INVALID_NAME on non-English locales (#160). Resolved live at
    // restore time — ifIndex isn't stable across reboots.
    #[serde(default, skip_serializing)]
    if_index: u32,
    servers: Vec<String>,
}

// PowerShell snippet that emits a JSON object keyed by adapter friendly name.
// Locale-invariant: cmdlet property names don't translate, unlike the
// `ipconfig /all` text we used to scrape — non-English Windows installs
// matched zero adapter headers and `numa install` aborted with "no active
// network interfaces found" (issue #146).
#[cfg(windows)]
const ENUMERATE_INTERFACES_PS: &str = r#"
$ErrorActionPreference = 'Stop'
$result = [ordered]@{}
$adapters = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }
foreach ($a in $adapters) {
    $v4 = @(Get-DnsClientServerAddress -InterfaceIndex $a.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses
    $v6 = @(Get-DnsClientServerAddress -InterfaceIndex $a.ifIndex -AddressFamily IPv6 -ErrorAction SilentlyContinue).ServerAddresses
    # Drop nulls: ServerAddresses can be $null when an adapter has no
    # configured DNS for one family, and `$v4 + $null` appends a literal
    # null entry that ConvertTo-Json emits as JSON `null`, breaking the
    # `Vec<String>` deserialize on the Rust side.
    $result[$a.Name] = @{ if_index = $a.ifIndex; servers = @(($v4 + $v6) | Where-Object { $_ }) }
}
$result | ConvertTo-Json -Compress -Depth 4
"#;

#[cfg(any(windows, test))]
fn parse_powershell_interfaces(
    json: &str,
) -> Result<std::collections::HashMap<String, WindowsInterfaceDns>, String> {
    let trimmed = json.trim();
    if trimmed.is_empty() {
        return Ok(std::collections::HashMap::new());
    }
    serde_json::from_str(trimmed).map_err(|e| format!("invalid powershell JSON: {}", e))
}

#[cfg(windows)]
fn get_windows_interfaces() -> Result<std::collections::HashMap<String, WindowsInterfaceDns>, String>
{
    let output = std::process::Command::new("powershell")
        .args([
            "-NoProfile",
            "-NonInteractive",
            "-ExecutionPolicy",
            "Bypass",
            "-Command",
            ENUMERATE_INTERFACES_PS,
        ])
        .output()
        .map_err(|e| format!("failed to run powershell: {}", e))?;
    if !output.status.success() {
        return Err(format!(
            "powershell adapter query failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    parse_powershell_interfaces(&String::from_utf8_lossy(&output.stdout))
}

#[cfg(windows)]
fn windows_backup_path() -> std::path::PathBuf {
    // Use ProgramData (not APPDATA) since install requires admin elevation
    // and APPDATA differs between user and admin contexts.
    std::path::PathBuf::from(
        std::env::var("PROGRAMDATA").unwrap_or_else(|_| "C:\\ProgramData".into()),
    )
    .join("numa")
    .join("original-dns.json")
}

#[cfg(windows)]
fn disable_dnscache() -> Result<bool, String> {
    // Check if Dnscache is running (it can hold port 53)
    let output = std::process::Command::new("sc")
        .args(["query", "Dnscache"])
        .output()
        .map_err(|e| format!("failed to query Dnscache: {}", e))?;
    let text = String::from_utf8_lossy(&output.stdout);
    if !text.contains("RUNNING") {
        return Ok(false);
    }

    eprintln!("  Disabling DNS Client (Dnscache) to free port 53...");
    // Dnscache can't be stopped via sc/net stop — must disable via registry
    let status = std::process::Command::new("reg")
        .args([
            "add",
            "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Dnscache",
            "/v",
            "Start",
            "/t",
            "REG_DWORD",
            "/d",
            "4",
            "/f",
        ])
        .status()
        .map_err(|e| format!("failed to disable Dnscache: {}", e))?;

    if !status.success() {
        return Err("failed to disable Dnscache via registry (run as Administrator?)".into());
    }

    // Dnscache is disabled for next boot. Check whether port 53 is
    // actually blocked right now — on many Windows configurations
    // Dnscache doesn't bind port 53 even while running.
    let port_blocked = std::net::UdpSocket::bind("127.0.0.1:53").is_err();
    if port_blocked {
        eprintln!("  Dnscache disabled. A reboot is required to free port 53.");
    } else {
        eprintln!("  Dnscache disabled. Port 53 is free.");
    }
    Ok(port_blocked)
}

#[cfg(windows)]
fn enable_dnscache() {
    let _ = std::process::Command::new("reg")
        .args([
            "add",
            "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Dnscache",
            "/v",
            "Start",
            "/t",
            "REG_DWORD",
            "/d",
            "2",
            "/f",
        ])
        .status();
}

/// True if the backup map has at least one real upstream (non-loopback, non-stub).
#[cfg(any(windows, test))]
fn backup_has_real_upstream_windows(
    interfaces: &std::collections::HashMap<String, WindowsInterfaceDns>,
) -> bool {
    interfaces
        .values()
        .any(|iface| iface.servers.iter().any(|s| !is_loopback_or_stub(s)))
}

#[cfg(windows)]
fn install_windows() -> Result<(), String> {
    let mut interfaces = get_windows_interfaces()?;
    if interfaces.is_empty() {
        return Err("no active network interfaces found".to_string());
    }

    let path = windows_backup_path();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("failed to create {}: {}", parent.display(), e))?;
    }

    // Preserve an existing useful backup rather than overwriting it with
    // numa-managed state (which would be self-referential after uninstall).
    let existing: Option<std::collections::HashMap<String, WindowsInterfaceDns>> =
        std::fs::read_to_string(&path)
            .ok()
            .and_then(|json| serde_json::from_str(&json).ok());
    let has_useful_existing = existing
        .as_ref()
        .map(backup_has_real_upstream_windows)
        .unwrap_or(false);

    if has_useful_existing {
        eprintln!("  Existing DNS backup preserved at {}", path.display());
    } else {
        // Filter loopback/stub addresses before saving so a fresh backup
        // captured from already-numa-managed state isn't self-referential.
        for iface in interfaces.values_mut() {
            iface.servers.retain(|s| !is_loopback_or_stub(s));
        }
        let json = serde_json::to_string_pretty(&interfaces)
            .map_err(|e| format!("failed to serialize backup: {}", e))?;
        std::fs::write(&path, json).map_err(|e| format!("failed to write backup: {}", e))?;
    }

    // On re-install, stop the running service first so the binary can be
    // overwritten and port 53 is released for the Dnscache probe.
    if is_service_registered() {
        eprintln!("  Stopping existing service...");
        stop_service_scm();
    }

    let needs_reboot = disable_dnscache()?;

    // Copy the binary to a stable path under ProgramData and register it
    // as a real Windows service (SCM-managed, boot-time, auto-restart).
    let service_exe = install_service_binary()?;
    register_service_scm(&service_exe)?;

    if needs_reboot {
        // Dnscache still holds port 53 until reboot. Do NOT redirect DNS
        // yet — nothing is listening on 127.0.0.1:53, so redirecting now
        // would kill DNS. The service will call redirect_dns_to_localhost()
        // on its first startup after reboot.
    } else {
        redirect_dns_with_interfaces(&interfaces)?;

        match start_service_scm() {
            Ok(_) => eprintln!("  Service started."),
            Err(e) => eprintln!(
                "  warning: service registered but could not start now: {}",
                e
            ),
        }
    }

    eprintln!();
    if !has_useful_existing {
        eprintln!("  Original DNS saved to {}", path.display());
    }
    eprintln!("  Run 'numa uninstall' to restore.\n");
    if needs_reboot {
        eprintln!("  *** Reboot required. Numa will start automatically. ***\n");
    } else {
        eprintln!("  Numa is running.\n");
    }
    print_recursive_hint();
    Ok(())
}

/// Stable install location for the service binary. SCM keeps a handle to
/// this path; the user's Downloads folder (where `current_exe()` points at
/// install time) is not durable.
#[cfg(windows)]
fn windows_service_exe_path() -> std::path::PathBuf {
    crate::data_dir().join("bin").join("numa.exe")
}

/// Run `sc.exe` with the given args and return its merged stdout/stderr on
/// failure. `sc` emits errors on stdout (not stderr) on Windows, so the
/// caller reads stdout to format a useful error.
#[cfg(windows)]
fn run_sc(args: &[&str]) -> Result<std::process::Output, String> {
    let out = std::process::Command::new("sc")
        .args(args)
        .output()
        .map_err(|e| format!("failed to run sc {}: {}", args.first().unwrap_or(&""), e))?;
    Ok(out)
}

/// Point all active network interfaces at 127.0.0.1 so Numa handles DNS.
/// Called from the service on first boot after a reboot that freed Dnscache.
#[cfg(windows)]
pub fn redirect_dns_to_localhost() -> Result<(), String> {
    let interfaces = get_windows_interfaces()?;
    redirect_dns_with_interfaces(&interfaces)
}

#[cfg(windows)]
fn run_netsh_ipv4(args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
    std::process::Command::new("netsh")
        .arg("interface")
        .arg("ipv4")
        .args(args)
        .status()
}

#[cfg(windows)]
fn redirect_dns_with_interfaces(
    interfaces: &std::collections::HashMap<String, WindowsInterfaceDns>,
) -> Result<(), String> {
    for (name, iface) in interfaces {
        let idx = iface.if_index.to_string();
        let status = run_netsh_ipv4(&["set", "dnsservers", &idx, "static", "127.0.0.1", "primary"])
            .map_err(|e| format!("failed to set DNS for {}: {}", name, e))?;

        if status.success() {
            eprintln!("  set DNS for \"{}\" -> 127.0.0.1", name);
        } else {
            eprintln!(
                "  warning: failed to set DNS for \"{}\" (run as Administrator?)",
                name
            );
        }
    }
    Ok(())
}

/// Copy the currently-running binary to the service install location. SCM
/// keeps a handle to this path, so it must be stable across user sessions.
#[cfg(windows)]
fn install_service_binary() -> Result<std::path::PathBuf, String> {
    let src = std::env::current_exe().map_err(|e| format!("current_exe(): {}", e))?;
    let dst = windows_service_exe_path();
    if let Some(parent) = dst.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("failed to create {}: {}", parent.display(), e))?;
    }
    // Copy only if source and destination differ; running the binary from
    // its install location is a supported (re-install) case.
    if src != dst {
        std::fs::copy(&src, &dst).map_err(|e| {
            format!(
                "failed to copy {} -> {}: {}",
                src.display(),
                dst.display(),
                e
            )
        })?;
    }
    Ok(dst)
}

/// Remove the service binary on uninstall. Ignore failures — the service
/// is already deleted; a leftover file in ProgramData is not a hard error.
#[cfg(windows)]
fn remove_service_binary() {
    let _ = std::fs::remove_file(windows_service_exe_path());
}

/// Register numa with the Service Control Manager, boot-time auto-start,
/// LocalSystem context, with a failure policy of restart-after-5s.
#[cfg(windows)]
fn register_service_scm(exe: &std::path::Path) -> Result<(), String> {
    let bin_path = format!("\"{}\" --service", exe.display());
    let name = crate::windows_service::SERVICE_NAME;

    // sc.exe uses a leading space as its `name= value` delimiter; the space
    // after `=` is mandatory.
    let create = run_sc(&[
        "create",
        name,
        "binPath=",
        &bin_path,
        "DisplayName=",
        "Numa DNS",
        "start=",
        "auto",
        "obj=",
        "LocalSystem",
    ])?;
    if !create.status.success() {
        let out = String::from_utf8_lossy(&create.stdout);
        // "service already exists" is 1073 — treat as idempotent success.
        if !out.contains("1073") {
            return Err(format!("sc create failed: {}", out.trim()));
        }
    }

    let _ = run_sc(&[
        "description",
        name,
        "Self-sovereign DNS resolver (ad blocking, DoH/DoT, local zones).",
    ]);

    // Restart on crash: 5s, 5s, 10s; reset failure counter after 60s.
    let _ = run_sc(&[
        "failure",
        name,
        "reset=",
        "60",
        "actions=",
        "restart/5000/restart/5000/restart/10000",
    ]);

    eprintln!("  Registered service '{}' (boot-time).", name);
    Ok(())
}

/// Start the service. Safe to call on a freshly-registered service — SCM
/// will fail with 1056 ("already running") or 1058 ("disabled") and we
/// return the underlying error string rather than masking it.
#[cfg(windows)]
fn start_service_scm() -> Result<(), String> {
    let out = run_sc(&["start", crate::windows_service::SERVICE_NAME])?;
    if !out.status.success() {
        let text = String::from_utf8_lossy(&out.stdout);
        if text.contains("1056") {
            return Ok(()); // already running
        }
        return Err(format!("sc start failed: {}", text.trim()));
    }
    Ok(())
}

/// Stop the service and wait for it to fully exit. Idempotent —
/// already-stopped or missing service is not an error.
#[cfg(windows)]
fn stop_service_scm() {
    let name = crate::windows_service::SERVICE_NAME;
    let _ = run_sc(&["stop", name]);
    // Wait up to 10s for the service to reach STOPPED state so the
    // binary file handle is released before we try to overwrite it.
    for _ in 0..20 {
        if let Ok(out) = run_sc(&["query", name]) {
            let text = String::from_utf8_lossy(&out.stdout);
            if text.contains("STOPPED") || text.contains("1060") {
                return;
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
    eprintln!("  warning: service did not stop within 10s");
}

/// Remove the service from SCM. Idempotent — see `stop_service_scm`.
#[cfg(windows)]
fn delete_service_scm() {
    if let Err(e) = run_sc(&["delete", crate::windows_service::SERVICE_NAME]) {
        log::warn!("sc delete failed: {}", e);
    }
}

/// Check whether the service is registered with SCM (regardless of state).
#[cfg(windows)]
fn is_service_registered() -> bool {
    run_sc(&["query", crate::windows_service::SERVICE_NAME])
        .map(|o| parse_sc_registered(o.status.success(), &String::from_utf8_lossy(&o.stdout)))
        .unwrap_or(false)
}

/// Parse `sc query` output to determine if a service is registered.
/// Extracted for testability — the actual `sc` call is in `is_service_registered`.
#[cfg(any(windows, test))]
fn parse_sc_registered(exit_success: bool, stdout: &str) -> bool {
    if exit_success {
        return true;
    }
    // Error 1060 = "The specified service does not exist as an installed service."
    !stdout.contains("1060")
}

/// Print service state from SCM.
#[cfg(windows)]
fn service_status_windows() -> Result<(), String> {
    let out = run_sc(&["query", crate::windows_service::SERVICE_NAME])?;
    let text = String::from_utf8_lossy(&out.stdout);
    let display = parse_sc_state(&text);
    eprintln!("  {}\n", display);
    Ok(())
}

/// Parse the STATE line from `sc query` output. Returns a human-readable
/// string like "STATE : 4 RUNNING" or "Service is not installed."
#[cfg(any(windows, test))]
fn parse_sc_state(sc_output: &str) -> String {
    if sc_output.contains("1060") {
        return "Service is not installed.".to_string();
    }
    sc_output
        .lines()
        .find(|l| l.contains("STATE"))
        .map(|l| l.trim().to_string())
        .unwrap_or_else(|| "unknown".to_string())
}

#[cfg(windows)]
fn uninstall_windows() -> Result<(), String> {
    // Stop + remove the service before touching DNS, so port 53 is released
    // cleanly and the failure-restart policy doesn't resurrect it.
    stop_service_scm();
    delete_service_scm();
    remove_service_binary();
    let path = windows_backup_path();
    let json = std::fs::read_to_string(&path)
        .map_err(|e| format!("no backup found at {}: {}", path.display(), e))?;
    let original: std::collections::HashMap<String, WindowsInterfaceDns> =
        serde_json::from_str(&json).map_err(|e| format!("invalid backup file: {}", e))?;

    let live = get_windows_interfaces()?;
    let mut skipped: Vec<&str> = Vec::new();

    for (name, dns_info) in &original {
        let Some(idx) = live.get(name).map(|i| i.if_index.to_string()) else {
            eprintln!("  warning: adapter \"{}\" not currently up; skipped", name);
            skipped.push(name.as_str());
            continue;
        };

        let real_servers: Vec<&str> = dns_info
            .servers
            .iter()
            .map(String::as_str)
            .filter(|s| !is_loopback_or_stub(s))
            .collect();

        if real_servers.is_empty() {
            let status = run_netsh_ipv4(&["set", "dnsservers", &idx, "dhcp"])
                .map_err(|e| format!("failed to restore DNS for {}: {}", name, e))?;

            if status.success() {
                eprintln!("  restored DNS for \"{}\" -> DHCP", name);
            } else {
                eprintln!("  warning: failed to restore DNS for \"{}\"", name);
            }
        } else {
            let status = run_netsh_ipv4(&[
                "set",
                "dnsservers",
                &idx,
                "static",
                real_servers[0],
                "primary",
            ])
            .map_err(|e| format!("failed to restore DNS for {}: {}", name, e))?;

            if !status.success() {
                eprintln!("  warning: failed to restore primary DNS for \"{}\"", name);
                continue;
            }

            for (i, server) in real_servers.iter().skip(1).enumerate() {
                let _ = run_netsh_ipv4(&[
                    "add",
                    "dnsservers",
                    &idx,
                    server,
                    &format!("index={}", i + 2),
                ]);
            }

            eprintln!(
                "  restored DNS for \"{}\" -> {}",
                name,
                real_servers.join(", ")
            );
        }
    }

    // Keep the backup if any adapter wasn't reachable — an offline
    // uninstall would otherwise leave the registry pinned at 127.0.0.1
    // with no recovery state for when the network returns.
    enable_dnscache();
    if skipped.is_empty() {
        std::fs::remove_file(&path).ok();
        eprintln!("\n  System DNS restored. DNS Client re-enabled.");
    } else {
        eprintln!(
            "\n  Partial restore. Backup kept at {} — re-run 'numa uninstall' after reconnecting: {}",
            path.display(),
            skipped.join(", ")
        );
        eprintln!("  DNS Client re-enabled.");
    }
    eprintln!("  Reboot to fully restore the DNS Client service.\n");
    Ok(())
}

/// Find the upstream for a domain by checking forwarding rules.
/// Returns None if no rule matches (use default upstream).
/// Zero-allocation on the hot path — dot_suffix is pre-computed.
pub fn match_forwarding_rule<'a>(
    domain: &str,
    rules: &'a [ForwardingRule],
) -> Option<&'a UpstreamPool> {
    for rule in rules {
        if domain == rule.suffix || domain.ends_with(&rule.dot_suffix) {
            return Some(&rule.upstream);
        }
    }
    None
}

// --- System DNS configuration (install/uninstall) ---

// --- macOS implementation ---

#[cfg(target_os = "macos")]
fn numa_data_dir() -> std::path::PathBuf {
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("SUDO_USER").map(|u| format!("/Users/{}", u)))
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|_| std::path::PathBuf::from("/var/root"));
    home.join(".numa")
}

#[cfg(target_os = "macos")]
fn backup_path() -> std::path::PathBuf {
    numa_data_dir().join("original-dns.json")
}

#[cfg(target_os = "macos")]
fn get_network_services() -> Result<Vec<String>, String> {
    let output = std::process::Command::new("networksetup")
        .arg("-listallnetworkservices")
        .output()
        .map_err(|e| format!("failed to run networksetup: {}", e))?;

    let text = String::from_utf8_lossy(&output.stdout);
    let services: Vec<String> = text
        .lines()
        .skip(1) // first line is "An asterisk (*) denotes..."
        .map(|l| l.trim_start_matches('*').trim().to_string())
        .filter(|l| !l.is_empty())
        .collect();

    Ok(services)
}

#[cfg(target_os = "macos")]
fn get_dns_servers(service: &str) -> Result<Vec<String>, String> {
    let output = std::process::Command::new("networksetup")
        .args(["-getdnsservers", service])
        .output()
        .map_err(|e| format!("failed to get DNS for {}: {}", service, e))?;

    let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if text.contains("aren't any DNS Servers") {
        Ok(vec![]) // using DHCP defaults
    } else {
        Ok(text.lines().map(|l| l.trim().to_string()).collect())
    }
}

/// True if the backup map has at least one real upstream (non-loopback, non-stub).
/// An all-loopback backup is self-referential — restoring it is a no-op.
#[cfg(any(target_os = "macos", test))]
fn backup_has_real_upstream_macos(
    servers: &std::collections::HashMap<String, Vec<String>>,
) -> bool {
    servers
        .values()
        .any(|list| list.iter().any(|s| !is_loopback_or_stub(s)))
}

#[cfg(target_os = "macos")]
fn install_macos() -> Result<(), String> {
    use std::collections::HashMap;

    let services = get_network_services()?;
    let dir = numa_data_dir();
    std::fs::create_dir_all(&dir)
        .map_err(|e| format!("failed to create {}: {}", dir.display(), e))?;

    // If a useful backup already exists (at least one non-loopback upstream),
    // preserve it — overwriting would destroy the original DNS state when
    // re-installing on top of a numa-managed configuration.
    let existing_backup: Option<HashMap<String, Vec<String>>> =
        std::fs::read_to_string(backup_path())
            .ok()
            .and_then(|json| serde_json::from_str(&json).ok());
    let has_useful_existing = existing_backup
        .as_ref()
        .map(backup_has_real_upstream_macos)
        .unwrap_or(false);

    if has_useful_existing {
        eprintln!(
            "  Existing DNS backup preserved at {}",
            backup_path().display()
        );
    } else {
        // Capture fresh, filtering out loopback and stub addresses so we
        // never record a self-referential backup.
        let mut original: HashMap<String, Vec<String>> = HashMap::new();
        for service in &services {
            let servers: Vec<String> = get_dns_servers(service)?
                .into_iter()
                .filter(|s| !is_loopback_or_stub(s))
                .collect();
            original.insert(service.clone(), servers);
        }

        let json = serde_json::to_string_pretty(&original)
            .map_err(|e| format!("failed to serialize backup: {}", e))?;
        std::fs::write(backup_path(), json)
            .map_err(|e| format!("failed to write backup: {}", e))?;
    }

    // Set DNS to 127.0.0.1 and add "numa" search domain for each service
    for service in &services {
        let status = std::process::Command::new("networksetup")
            .args(["-setdnsservers", service, "127.0.0.1"])
            .status()
            .map_err(|e| format!("failed to set DNS for {}: {}", service, e))?;

        if status.success() {
            eprintln!("  set DNS for \"{}\" -> 127.0.0.1", service);
        } else {
            eprintln!("  warning: failed to set DNS for \"{}\"", service);
        }

        // Add "numa" as search domain so browsers resolve .numa without trailing slash
        let _ = std::process::Command::new("networksetup")
            .args(["-setsearchdomains", service, "numa"])
            .status();
    }

    eprintln!();
    if !has_useful_existing {
        eprintln!("  Original DNS saved to {}", backup_path().display());
    }
    eprintln!("  Run 'sudo numa uninstall' to restore.\n");

    Ok(())
}

#[cfg(target_os = "macos")]
fn uninstall_macos() -> Result<(), String> {
    use std::collections::HashMap;

    let path = backup_path();
    let json = std::fs::read_to_string(&path)
        .map_err(|e| format!("no backup found at {}: {}", path.display(), e))?;

    let original: HashMap<String, Vec<String>> =
        serde_json::from_str(&json).map_err(|e| format!("invalid backup file: {}", e))?;

    for (service, servers) in &original {
        let args = if servers.is_empty() {
            // Restore to "empty" (DHCP default) by setting to "Empty"
            vec!["-setdnsservers", service, "Empty"]
        } else {
            let mut a = vec!["-setdnsservers", service];
            a.extend(servers.iter().map(|s| s.as_str()));
            a
        };

        let status = std::process::Command::new("networksetup")
            .args(&args)
            .status()
            .map_err(|e| format!("failed to restore DNS for {}: {}", service, e))?;

        if status.success() {
            let display = if servers.is_empty() {
                "DHCP default".to_string()
            } else {
                servers.join(", ")
            };
            eprintln!("  restored DNS for \"{}\" -> {}", service, display);
        } else {
            eprintln!("  warning: failed to restore DNS for \"{}\"", service);
        }

        // Clear the "numa" search domain
        let _ = std::process::Command::new("networksetup")
            .args(["-setsearchdomains", service, "Empty"])
            .status();
    }

    std::fs::remove_file(&path).ok();
    eprintln!("\n  System DNS restored. Backup removed.\n");

    Ok(())
}

// --- Service management ---

#[cfg(target_os = "macos")]
const PLIST_LABEL: &str = "com.numa.dns";
#[cfg(target_os = "macos")]
const PLIST_DEST: &str = "/Library/LaunchDaemons/com.numa.dns.plist";
#[cfg(target_os = "linux")]
const SYSTEMD_UNIT: &str = "/etc/systemd/system/numa.service";

/// Install Numa as a system service that starts on boot and auto-restarts.
pub fn install_service() -> Result<(), String> {
    #[cfg(target_os = "macos")]
    let result = install_service_macos();
    #[cfg(target_os = "linux")]
    let result = install_service_linux();
    #[cfg(windows)]
    let result = install_windows();
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    let result = Err::<(), String>("service installation not supported on this OS".to_string());

    if result.is_ok() {
        if let Err(e) = trust_ca() {
            eprintln!("  warning: could not trust CA: {}", e);
            eprintln!("  HTTPS proxy will work but browsers will show certificate warnings.\n");
        }
    }
    result
}

/// Start the service. If already installed, just starts it via the platform
/// service manager. If not installed, falls through to a full install.
pub fn start_service() -> Result<(), String> {
    #[cfg(target_os = "macos")]
    {
        install_service()
    }
    #[cfg(target_os = "linux")]
    {
        install_service()
    }
    #[cfg(windows)]
    {
        if is_service_registered() {
            start_service_scm()?;
            eprintln!("  Service started.\n");
            Ok(())
        } else {
            install_service()
        }
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    {
        Err("service start not supported on this OS".to_string())
    }
}

/// Stop the service without uninstalling it.
pub fn stop_service() -> Result<(), String> {
    #[cfg(target_os = "macos")]
    {
        uninstall_service()
    }
    #[cfg(target_os = "linux")]
    {
        uninstall_service()
    }
    #[cfg(windows)]
    {
        let out = run_sc(&["stop", crate::windows_service::SERVICE_NAME])?;
        if !out.status.success() {
            let text = String::from_utf8_lossy(&out.stdout);
            // 1062 = not started, 1060 = does not exist
            if !text.contains("1062") && !text.contains("1060") {
                return Err(format!("sc stop failed: {}", text.trim()));
            }
        }
        eprintln!("  Service stopped.\n");
        Ok(())
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    {
        Err("service stop not supported on this OS".to_string())
    }
}

/// Uninstall the Numa system service.
pub fn uninstall_service() -> Result<(), String> {
    let _ = untrust_ca();

    #[cfg(target_os = "macos")]
    {
        uninstall_service_macos()
    }
    #[cfg(target_os = "linux")]
    {
        uninstall_service_linux()
    }
    #[cfg(windows)]
    {
        uninstall_windows()
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    {
        Err("service uninstallation not supported on this OS".to_string())
    }
}

/// Restart the service (kill process, launchd/systemd auto-restarts with new binary).
pub fn restart_service() -> Result<(), String> {
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    let exe_path =
        std::env::current_exe().map_err(|e| format!("failed to get current exe: {}", e))?;

    #[cfg(any(target_os = "macos", target_os = "linux"))]
    let version = {
        match std::process::Command::new(&exe_path)
            .arg("--version")
            .output()
        {
            Ok(o) => String::from_utf8_lossy(&o.stderr).trim().to_string(),
            Err(_) => "unknown".to_string(),
        }
    };

    #[cfg(target_os = "macos")]
    {
        let exe_path = exe_path.to_string_lossy();
        let output = std::process::Command::new("launchctl")
            .args(["list", PLIST_LABEL])
            .output();
        match output {
            Ok(o) if o.status.success() => {
                eprintln!("  Tip: use 'make deploy' instead — handles codesign + restart.\n");
                // Codesign, then kill service. Launchd KeepAlive respawns it.
                // This will kill us too (we ARE /usr/local/bin/numa), so
                // codesign and print output first.
                let _ = std::process::Command::new("codesign")
                    .args(["-f", "-s", "-", &exe_path])
                    .output(); // use output() to suppress codesign stderr
                eprintln!("  Service restarting → {}\n", version);
                let _ = std::process::Command::new("pkill")
                    .args(["-f", &exe_path])
                    .status();
                Ok(())
            }
            _ => Err("Service is not installed. Run 'sudo numa service start' first.".to_string()),
        }
    }
    #[cfg(target_os = "linux")]
    {
        run_systemctl(&["restart", "numa"])?;
        eprintln!("  Service restarted → {}\n", version);
        Ok(())
    }
    #[cfg(windows)]
    {
        stop_service_scm();
        start_service_scm()?;
        eprintln!("  Service restarted.\n");
        Ok(())
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    {
        Err("service restart not supported on this OS".to_string())
    }
}

/// Show the service status.
pub fn service_status() -> Result<(), String> {
    #[cfg(target_os = "macos")]
    {
        service_status_macos()
    }
    #[cfg(target_os = "linux")]
    {
        service_status_linux()
    }
    #[cfg(windows)]
    {
        service_status_windows()
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    {
        Err("service status not supported on this OS".to_string())
    }
}

#[cfg(target_os = "macos")]
fn replace_exe_path(service: &str) -> Result<String, String> {
    let exe_path =
        std::env::current_exe().map_err(|e| format!("failed to get current exe: {}", e))?;
    Ok(service.replace("{{exe_path}}", &exe_path.to_string_lossy()))
}

#[cfg(target_os = "macos")]
fn install_service_macos() -> Result<(), String> {
    // Create log directory
    std::fs::create_dir_all("/usr/local/var/log")
        .map_err(|e| format!("failed to create log dir: {}", e))?;

    // Write plist
    let plist = include_str!("../com.numa.dns.plist");
    let plist = replace_exe_path(plist)?;

    std::fs::write(PLIST_DEST, plist)
        .map_err(|e| format!("failed to write {}: {}", PLIST_DEST, e))?;

    // Modern launchctl API: explicitly tear down any existing in-memory
    // state, then bootstrap fresh from the on-disk plist. The deprecated
    // `load -w` returns exit 0 even when it cannot actually reload (label
    // already in launchd state), silently leaving the daemon running a
    // stale binary path after `numa install` rewrites the plist on disk —
    // which is exactly what `brew upgrade numa` does.
    let _ = std::process::Command::new("launchctl")
        .args(["bootout", "system", PLIST_DEST])
        .status();

    let status = std::process::Command::new("launchctl")
        .args(["bootstrap", "system", PLIST_DEST])
        .status()
        .map_err(|e| format!("failed to run launchctl: {}", e))?;

    if !status.success() {
        return Err("launchctl bootstrap failed".to_string());
    }

    // Wait for numa to be ready before redirecting DNS
    let api_up = (0..10).any(|i| {
        if i > 0 {
            std::thread::sleep(std::time::Duration::from_millis(500));
        }
        std::net::TcpStream::connect(("127.0.0.1", crate::config::DEFAULT_API_PORT)).is_ok()
    });
    if !api_up {
        // Service failed to start — don't redirect DNS to a dead endpoint
        let _ = std::process::Command::new("launchctl")
            .args(["bootout", "system", PLIST_DEST])
            .status();
        return Err(
            "numa service did not start (port 53 may be in use). Service unloaded.".to_string(),
        );
    }

    if let Err(e) = install_macos() {
        eprintln!("  warning: failed to configure system DNS: {}", e);
    }

    eprintln!("  Service installed and started.");
    eprintln!("  Numa will auto-start on boot and restart if killed.");
    eprintln!("  Logs: /usr/local/var/log/numa.log");
    eprintln!("  Run 'sudo numa uninstall' to restore original DNS.\n");
    print_recursive_hint();
    Ok(())
}

#[cfg(target_os = "macos")]
fn uninstall_service_macos() -> Result<(), String> {
    // Restore DNS first, while numa is still running to handle any final queries
    if let Err(e) = uninstall_macos() {
        eprintln!("  warning: failed to restore system DNS: {}", e);
    }

    // Bootout the service from launchd's in-memory state BEFORE removing
    // the plist. The modern API needs the file path as the specifier;
    // doing this in the wrong order would leave the service loaded in
    // memory until reboot. (Deprecated `unload -w` had the same issue.)
    let bootout_status = std::process::Command::new("launchctl")
        .args(["bootout", "system", PLIST_DEST])
        .status();
    if let Ok(s) = bootout_status {
        if !s.success() {
            eprintln!(
                "  warning: launchctl bootout returned non-zero (service may not have been loaded)"
            );
        }
    }

    // Remove plist so the service won't restart on boot
    if let Err(e) = std::fs::remove_file(PLIST_DEST) {
        if e.kind() != std::io::ErrorKind::NotFound {
            return Err(format!("failed to remove {}: {}", PLIST_DEST, e));
        }
    }

    eprintln!("  Service uninstalled. Numa will no longer auto-start.\n");
    Ok(())
}

#[cfg(target_os = "macos")]
fn service_status_macos() -> Result<(), String> {
    let output = std::process::Command::new("launchctl")
        .args(["list", PLIST_LABEL])
        .output()
        .map_err(|e| format!("failed to run launchctl: {}", e))?;

    if output.status.success() {
        let text = String::from_utf8_lossy(&output.stdout);
        eprintln!("  Numa service is loaded.\n");
        for line in text.lines() {
            eprintln!("  {}", line);
        }
        eprintln!();
    } else {
        eprintln!("  Numa service is not installed.\n");
    }
    Ok(())
}

// --- Linux implementation ---

#[cfg(target_os = "linux")]
fn backup_path_linux() -> std::path::PathBuf {
    let home = std::env::var("HOME")
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|_| std::path::PathBuf::from("/root"));
    home.join(".numa").join("original-resolv.conf")
}

#[cfg(target_os = "linux")]
fn is_systemd_resolved_active() -> bool {
    std::process::Command::new("systemctl")
        .args(["is-active", "--quiet", "systemd-resolved"])
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

#[cfg(target_os = "linux")]
fn install_linux() -> Result<(), String> {
    // Detect systemd-resolved — direct resolv.conf manipulation won't persist
    if is_systemd_resolved_active() {
        let resolved_dir = std::path::Path::new("/etc/systemd/resolved.conf.d");
        std::fs::create_dir_all(resolved_dir)
            .map_err(|e| format!("failed to create {}: {}", resolved_dir.display(), e))?;

        let drop_in = resolved_dir.join("numa.conf");
        std::fs::write(
            &drop_in,
            "[Resolve]\nDNS=127.0.0.1\nDomains=~. numa\nDNSStubListener=no\n",
        )
        .map_err(|e| format!("failed to write {}: {}", drop_in.display(), e))?;

        let _ = run_systemctl(&["restart", "systemd-resolved"]);
        eprintln!("  systemd-resolved detected.");
        eprintln!("  Installed drop-in: {}", drop_in.display());
        eprintln!("  Run 'sudo numa uninstall' to remove.\n");
        return Ok(());
    }

    // Fallback: direct resolv.conf manipulation
    let resolv = std::path::Path::new("/etc/resolv.conf");
    let backup = backup_path_linux();

    // Ensure backup directory exists
    if let Some(parent) = backup.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("failed to create {}: {}", parent.display(), e))?;
    }

    // Back up current resolv.conf, but never overwrite a useful existing
    // backup with a numa-managed file — that would leave uninstall with
    // nothing to restore to.
    let current = std::fs::read_to_string(resolv).ok();
    let current_is_numa_managed = current
        .as_deref()
        .map(resolv_conf_is_numa_managed)
        .unwrap_or(false);
    let existing_backup_is_useful = std::fs::read_to_string(&backup)
        .ok()
        .as_deref()
        .map(resolv_conf_has_real_upstream)
        .unwrap_or(false);

    if existing_backup_is_useful {
        eprintln!(
            "  Existing resolv.conf backup preserved at {}",
            backup.display()
        );
    } else if current_is_numa_managed {
        eprintln!("  warning: /etc/resolv.conf is already numa-managed; no fresh backup written");
    } else if let Some(content) = current.as_deref() {
        std::fs::write(&backup, content)
            .map_err(|e| format!("failed to backup /etc/resolv.conf: {}", e))?;
        eprintln!("  Saved /etc/resolv.conf to {}", backup.display());
    }

    if resolv
        .symlink_metadata()
        .map(|m| m.file_type().is_symlink())
        .unwrap_or(false)
    {
        eprintln!("  warning: /etc/resolv.conf is a symlink — changes may not persist.");
        eprintln!("  Consider using systemd-resolved or NetworkManager instead.\n");
    }

    let content =
        "# Generated by Numa — run 'sudo numa uninstall' to restore\nnameserver 127.0.0.1\nsearch numa\n";
    std::fs::write(resolv, content)
        .map_err(|e| format!("failed to write /etc/resolv.conf: {}", e))?;

    eprintln!("  Set /etc/resolv.conf -> nameserver 127.0.0.1");
    eprintln!("  Run 'sudo numa uninstall' to restore.\n");
    Ok(())
}

#[cfg(target_os = "linux")]
fn uninstall_linux() -> Result<(), String> {
    // Check for systemd-resolved drop-in first
    let drop_in = std::path::Path::new("/etc/systemd/resolved.conf.d/numa.conf");
    if drop_in.exists() {
        std::fs::remove_file(drop_in)
            .map_err(|e| format!("failed to remove {}: {}", drop_in.display(), e))?;
        let _ = run_systemctl(&["restart", "systemd-resolved"]);
        eprintln!("  Removed systemd-resolved drop-in. DNS restored.\n");
        return Ok(());
    }

    // Fallback: restore resolv.conf from backup
    let backup = backup_path_linux();
    let resolv = std::path::Path::new("/etc/resolv.conf");

    match std::fs::copy(&backup, resolv) {
        Ok(_) => {
            std::fs::remove_file(&backup).ok();
            eprintln!("  Restored /etc/resolv.conf from backup. Backup removed.\n");
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            eprintln!("  No backup found at {}.", backup.display());
            eprintln!("  Manually edit /etc/resolv.conf to restore your DNS.\n");
        }
        Err(e) => return Err(format!("failed to restore /etc/resolv.conf: {}", e)),
    }
    Ok(())
}

/// Fallback install location when current_exe() sits on a path the
/// dynamic user cannot traverse (e.g. `/home/<user>/` mode 0700).
#[cfg(target_os = "linux")]
fn linux_service_exe_path() -> std::path::PathBuf {
    std::path::PathBuf::from("/usr/local/bin/numa")
}

/// True iff every ancestor of `p` (excluding `/`) grants world-execute —
/// i.e. the `DynamicUser=yes` service account can traverse the path and
/// exec the binary without being in any group. Linuxbrew's
/// `/home/linuxbrew` is 0755 (traversable, keep brew's path, upgrades
/// via `brew` propagate). A build tree under `/home/<user>/` (0700) or
/// `~/.cargo/bin/` is not (copy to /usr/local/bin so systemd can reach it).
#[cfg(target_os = "linux")]
fn path_world_traversable_linux(p: &std::path::Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    let mut current = p;
    while let Some(parent) = current.parent() {
        if parent.as_os_str().is_empty() || parent == std::path::Path::new("/") {
            break;
        }
        match std::fs::metadata(parent) {
            Ok(m) if m.permissions().mode() & 0o001 != 0 => {}
            _ => return false,
        }
        current = parent;
    }
    true
}

#[cfg(target_os = "linux")]
fn install_service_binary_linux() -> Result<std::path::PathBuf, String> {
    let src = std::env::current_exe().map_err(|e| format!("current_exe(): {}", e))?;
    if path_world_traversable_linux(&src) {
        return Ok(src);
    }
    let dst = linux_service_exe_path();
    if src == dst {
        return Ok(dst);
    }
    if let Some(parent) = dst.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("failed to create {}: {}", parent.display(), e))?;
    }
    // Atomic replace via temp + rename. Plain copy fails with ETXTBSY when
    // re-installing while the service is running the previous binary —
    // rename swaps the path while the running process keeps the old inode.
    let tmp = dst.with_extension("new");
    std::fs::copy(&src, &tmp).map_err(|e| {
        format!(
            "failed to copy {} -> {}: {}",
            src.display(),
            tmp.display(),
            e
        )
    })?;
    std::fs::rename(&tmp, &dst).map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        format!(
            "failed to rename {} -> {}: {}",
            tmp.display(),
            dst.display(),
            e
        )
    })?;
    Ok(dst)
}

#[cfg(target_os = "linux")]
fn install_service_linux() -> Result<(), String> {
    let exe = install_service_binary_linux()?;
    let unit = include_str!("../numa.service").replace("{{exe_path}}", &exe.to_string_lossy());
    std::fs::write(SYSTEMD_UNIT, unit)
        .map_err(|e| format!("failed to write {}: {}", SYSTEMD_UNIT, e))?;

    run_systemctl(&["daemon-reload"])?;
    run_systemctl(&["enable", "numa"])?;

    // Configure system DNS before starting numa so resolved releases port 53 first
    if let Err(e) = install_linux() {
        eprintln!("  warning: failed to configure system DNS: {}", e);
    }

    // restart, not start: on re-install the service is already running
    // the previous binary; restart picks up the new one.
    run_systemctl(&["restart", "numa"])?;

    eprintln!("  Service installed and started.");
    eprintln!("  Numa will auto-start on boot and restart if killed.");
    eprintln!("  Logs: journalctl -u numa -f");
    eprintln!("  Run 'sudo numa uninstall' to restore original DNS.\n");
    print_recursive_hint();
    Ok(())
}

#[cfg(target_os = "linux")]
fn uninstall_service_linux() -> Result<(), String> {
    // Restore DNS first, while numa is still running
    if let Err(e) = uninstall_linux() {
        eprintln!("  warning: failed to restore system DNS: {}", e);
    }

    if let Err(e) = run_systemctl(&["stop", "numa"]) {
        eprintln!("  warning: {}", e);
    }
    if let Err(e) = run_systemctl(&["disable", "numa"]) {
        eprintln!("  warning: {}", e);
    }

    if let Err(e) = std::fs::remove_file(SYSTEMD_UNIT) {
        if e.kind() != std::io::ErrorKind::NotFound {
            return Err(format!("failed to remove {}: {}", SYSTEMD_UNIT, e));
        }
    }
    let _ = run_systemctl(&["daemon-reload"]);

    eprintln!("  Service uninstalled. Numa will no longer auto-start.\n");
    Ok(())
}

#[cfg(target_os = "linux")]
fn service_status_linux() -> Result<(), String> {
    let output = std::process::Command::new("systemctl")
        .args(["status", "numa"])
        .output()
        .map_err(|e| format!("failed to run systemctl: {}", e))?;

    let text = String::from_utf8_lossy(&output.stdout);
    if text.is_empty() {
        eprintln!("  Numa service is not installed.\n");
    } else {
        for line in text.lines() {
            eprintln!("  {}", line);
        }
        eprintln!();
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn run_systemctl(args: &[&str]) -> Result<(), String> {
    let status = std::process::Command::new("systemctl")
        .args(args)
        .status()
        .map_err(|e| format!("systemctl {} failed: {}", args.join(" "), e))?;
    if status.success() {
        Ok(())
    } else {
        Err(format!(
            "systemctl {} exited with {}",
            args.join(" "),
            status
        ))
    }
}

// --- CA trust management ---

/// One Linux trust-store backend (Debian, Fedora pki, Arch p11-kit).
#[cfg(target_os = "linux")]
struct LinuxTrustStore {
    name: &'static str,
    anchor_dir: &'static str,
    anchor_file: &'static str,
    refresh_install: &'static [&'static str],
    refresh_uninstall: &'static [&'static str],
}

// If you change this table, update tests/docker/install-trust.sh to match —
// it asserts the same paths/commands against real distro images.
#[cfg(target_os = "linux")]
const LINUX_TRUST_STORES: &[LinuxTrustStore] = &[
    // Debian / Ubuntu / Mint
    LinuxTrustStore {
        name: "debian",
        anchor_dir: "/usr/local/share/ca-certificates",
        anchor_file: "numa-local-ca.crt",
        refresh_install: &["update-ca-certificates"],
        refresh_uninstall: &["update-ca-certificates", "--fresh"],
    },
    // Fedora / RHEL / CentOS / SUSE (p11-kit via update-ca-trust wrapper)
    LinuxTrustStore {
        name: "pki",
        anchor_dir: "/etc/pki/ca-trust/source/anchors",
        anchor_file: "numa-local-ca.pem",
        refresh_install: &["update-ca-trust", "extract"],
        refresh_uninstall: &["update-ca-trust", "extract"],
    },
    // Arch / Manjaro (raw p11-kit)
    LinuxTrustStore {
        name: "p11kit",
        anchor_dir: "/etc/ca-certificates/trust-source/anchors",
        anchor_file: "numa-local-ca.pem",
        refresh_install: &["trust", "extract-compat"],
        refresh_uninstall: &["trust", "extract-compat"],
    },
];

#[cfg(target_os = "linux")]
fn detect_linux_trust_store() -> Option<&'static LinuxTrustStore> {
    LINUX_TRUST_STORES
        .iter()
        .find(|s| std::path::Path::new(s.anchor_dir).is_dir())
}

fn trust_ca() -> Result<(), String> {
    let ca_path = crate::data_dir().join(crate::tls::CA_FILE_NAME);
    if !ca_path.exists() {
        return Err("CA not generated yet — start numa first to create certificates".into());
    }

    #[cfg(target_os = "macos")]
    let result = trust_ca_macos(&ca_path);
    #[cfg(target_os = "linux")]
    let result = trust_ca_linux(&ca_path);
    #[cfg(windows)]
    let result = trust_ca_windows(&ca_path);
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    let result = Err::<(), String>("CA trust not supported on this OS".to_string());

    result
}

fn untrust_ca() -> Result<(), String> {
    #[cfg(target_os = "macos")]
    let result = untrust_ca_macos();
    #[cfg(target_os = "linux")]
    let result = untrust_ca_linux();
    #[cfg(windows)]
    let result = untrust_ca_windows();
    #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
    let result = Ok::<(), String>(());

    result
}

#[cfg(target_os = "macos")]
fn trust_ca_macos(ca_path: &std::path::Path) -> Result<(), String> {
    let status = std::process::Command::new("security")
        .args([
            "add-trusted-cert",
            "-d",
            "-r",
            "trustRoot",
            "-k",
            "/Library/Keychains/System.keychain",
        ])
        .arg(ca_path)
        .status()
        .map_err(|e| format!("security: {}", e))?;
    if !status.success() {
        return Err("security add-trusted-cert failed".into());
    }
    eprintln!("  Trusted Numa CA in system keychain");
    Ok(())
}

#[cfg(target_os = "macos")]
fn untrust_ca_macos() -> Result<(), String> {
    if let Ok(out) = std::process::Command::new("security")
        .args([
            "find-certificate",
            "-c",
            crate::tls::CA_COMMON_NAME,
            "-a",
            "-Z",
            "/Library/Keychains/System.keychain",
        ])
        .output()
    {
        let stdout = String::from_utf8_lossy(&out.stdout);
        for line in stdout.lines() {
            if let Some(hash) = line.strip_prefix("SHA-1 hash: ") {
                let hash = hash.trim();
                let _ = std::process::Command::new("security")
                    .args([
                        "delete-certificate",
                        "-Z",
                        hash,
                        "/Library/Keychains/System.keychain",
                    ])
                    .output();
            }
        }
    }
    eprintln!("  Removed Numa CA from system keychain");
    Ok(())
}

#[cfg(target_os = "linux")]
fn trust_ca_linux(ca_path: &std::path::Path) -> Result<(), String> {
    let store = detect_linux_trust_store().ok_or_else(|| {
        let names: Vec<&str> = LINUX_TRUST_STORES.iter().map(|s| s.name).collect();
        format!(
            "no supported CA trust store found (tried: {}). \
             Please report at https://github.com/razvandimescu/numa/issues",
            names.join(", ")
        )
    })?;

    let dest = std::path::Path::new(store.anchor_dir).join(store.anchor_file);
    std::fs::copy(ca_path, &dest).map_err(|e| format!("copy CA to {}: {}", dest.display(), e))?;

    run_refresh(store.name, store.refresh_install)?;
    eprintln!("  Trusted Numa CA system-wide ({})", store.name);
    Ok(())
}

#[cfg(target_os = "linux")]
fn untrust_ca_linux() -> Result<(), String> {
    let Some(store) = detect_linux_trust_store() else {
        return Ok(());
    };

    let dest = std::path::Path::new(store.anchor_dir).join(store.anchor_file);
    match std::fs::remove_file(&dest) {
        Ok(()) => {
            let _ = run_refresh(store.name, store.refresh_uninstall);
            eprintln!("  Removed Numa CA from system trust store ({})", store.name);
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(_) => {} // best-effort uninstall
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn run_refresh(store_name: &str, argv: &[&str]) -> Result<(), String> {
    let (cmd, args) = argv
        .split_first()
        .expect("refresh command must be non-empty");
    let status = std::process::Command::new(cmd)
        .args(args)
        .status()
        .map_err(|e| format!("{} ({}): {}", cmd, store_name, e))?;
    if !status.success() {
        return Err(format!("{} ({}) failed", cmd, store_name));
    }
    Ok(())
}

#[cfg(windows)]
fn trust_ca_windows(ca_path: &std::path::Path) -> Result<(), String> {
    let status = std::process::Command::new("certutil")
        .args(["-addstore", "-f", "Root"])
        .arg(ca_path)
        .status()
        .map_err(|e| format!("certutil: {}", e))?;
    if !status.success() {
        return Err("certutil -addstore Root failed (run as Administrator?)".into());
    }
    eprintln!("  Trusted Numa CA in Windows Root store");
    Ok(())
}

#[cfg(windows)]
fn untrust_ca_windows() -> Result<(), String> {
    let _ = std::process::Command::new("certutil")
        .args(["-delstore", "Root", crate::tls::CA_COMMON_NAME])
        .status();
    eprintln!("  Removed Numa CA from Windows Root store");
    Ok(())
}

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

    #[test]
    fn parse_powershell_servers() {
        // Shape emitted by ENUMERATE_INTERFACES_PS — adapter name keys, each
        // value carries the live ifIndex and a merged IPv4+IPv6 server list.
        // Legacy `dhcp` field (in pre-fix backups on disk) is silently
        // ignored on read.
        let sample = r#"{"Ethernet":{"if_index":12,"servers":["8.8.8.8","8.8.4.4"]},"Wi-Fi":{"dhcp":true,"if_index":7,"servers":["1.1.1.1"]}}"#;
        let result = parse_powershell_interfaces(sample).expect("parse failed");
        assert_eq!(result.len(), 2);
        assert_eq!(
            result["Ethernet"],
            WindowsInterfaceDns {
                if_index: 12,
                servers: vec!["8.8.8.8".into(), "8.8.4.4".into()],
            }
        );
        assert_eq!(
            result["Wi-Fi"],
            WindowsInterfaceDns {
                if_index: 7,
                servers: vec!["1.1.1.1".into()],
            }
        );
    }

    #[test]
    fn parse_powershell_legacy_backup_without_if_index() {
        let sample = r#"{"Ethernet":{"servers":["8.8.8.8"]}}"#;
        let result = parse_powershell_interfaces(sample).expect("parse failed");
        assert_eq!(result["Ethernet"].if_index, 0);
        assert_eq!(result["Ethernet"].servers, vec!["8.8.8.8".to_string()]);
    }

    #[test]
    fn parse_powershell_empty_when_no_adapters_up() {
        // Get-NetAdapter | Where Status=Up returns nothing → empty hashtable
        // → ConvertTo-Json emits "{}". Must produce an empty map, not error,
        // so install_windows() can surface the right "no active interfaces"
        // message instead of a JSON parse failure.
        assert!(parse_powershell_interfaces("{}").unwrap().is_empty());
        assert!(parse_powershell_interfaces("").unwrap().is_empty());
        assert!(parse_powershell_interfaces("   \n").unwrap().is_empty());
    }

    #[test]
    fn parse_powershell_rejects_garbage() {
        assert!(parse_powershell_interfaces("not json").is_err());
    }

    #[test]
    fn parse_powershell_rejects_null_server_entry() {
        // Locks in the PS-side null filter (Where-Object { $_ }) — a real
        // install on a dual-stack adapter without IPv6 DNS used to emit
        // `["10.0.0.1", null]`, failing deserialize at install time.
        let sample = r#"{"Wi-Fi":{"servers":["1.1.1.1",null]}}"#;
        assert!(parse_powershell_interfaces(sample).is_err());
    }

    #[test]
    fn install_templates_contain_exe_path_placeholder() {
        // Both files are substituted at install time — plist via
        // replace_exe_path on macOS, numa.service via inline .replace
        // in install_service_linux. Catch placeholder removal early.
        let plist = include_str!("../com.numa.dns.plist");
        let unit = include_str!("../numa.service");
        assert!(plist.contains("{{exe_path}}"), "plist missing placeholder");
        assert!(
            unit.contains("{{exe_path}}"),
            "unit file missing placeholder"
        );
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn replace_exe_path_substitutes_template() {
        let plist = include_str!("../com.numa.dns.plist");
        let result = replace_exe_path(plist).expect("replace_exe_path failed for plist");
        assert!(!result.contains("{{exe_path}}"));
    }

    #[test]
    fn macos_backup_real_upstream_detection() {
        use std::collections::HashMap;
        let mut map: HashMap<String, Vec<String>> = HashMap::new();

        // Empty backup → no real upstream
        assert!(!backup_has_real_upstream_macos(&map));

        // All-loopback backup → still no real upstream (the bug case)
        map.insert("Wi-Fi".into(), vec!["127.0.0.1".into()]);
        map.insert("Ethernet".into(), vec!["::1".into()]);
        assert!(!backup_has_real_upstream_macos(&map));

        // One real entry → useful
        map.insert("Tailscale".into(), vec!["192.168.1.1".into()]);
        assert!(backup_has_real_upstream_macos(&map));
    }

    #[test]
    fn windows_backup_filters_loopback() {
        use std::collections::HashMap;
        let mut map: HashMap<String, WindowsInterfaceDns> = HashMap::new();

        // Empty backup → no real upstream
        assert!(!backup_has_real_upstream_windows(&map));

        // All-loopback backup → still no real upstream (the bug case)
        map.insert(
            "Wi-Fi".into(),
            WindowsInterfaceDns {
                servers: vec!["127.0.0.1".into()],
                if_index: 0,
            },
        );
        map.insert(
            "Ethernet".into(),
            WindowsInterfaceDns {
                servers: vec!["::1".into(), "0.0.0.0".into()],
                if_index: 0,
            },
        );
        assert!(!backup_has_real_upstream_windows(&map));

        // fec0:0:0:ffff::1/2/3 leak into every VPN/virtual adapter via
        // Get-DnsClientServerAddress.
        map.insert(
            "Tailscale".into(),
            WindowsInterfaceDns {
                servers: vec![
                    "fec0:0:0:ffff::1".into(),
                    "fec0:0:0:ffff::2".into(),
                    "fec0:0:0:ffff::3".into(),
                ],
                if_index: 0,
            },
        );
        assert!(!backup_has_real_upstream_windows(&map));

        // One real entry alongside loopback → useful
        map.insert(
            "Ethernet 2".into(),
            WindowsInterfaceDns {
                servers: vec!["192.168.1.1".into()],
                if_index: 0,
            },
        );
        assert!(backup_has_real_upstream_windows(&map));
    }

    #[test]
    fn resolv_conf_real_upstream_detection() {
        let real = "nameserver 192.168.1.1\nsearch lan\n";
        assert!(resolv_conf_has_real_upstream(real));
        assert!(!resolv_conf_is_numa_managed(real));

        let self_ref = "nameserver 127.0.0.1\nsearch numa\n";
        assert!(!resolv_conf_has_real_upstream(self_ref));
        assert!(resolv_conf_is_numa_managed(self_ref));

        let numa_marker =
            "# Generated by Numa — run 'sudo numa uninstall' to restore\nnameserver 127.0.0.1\nsearch numa\n";
        assert!(resolv_conf_is_numa_managed(numa_marker));

        let systemd_stub = "nameserver 127.0.0.53\noptions edns0\n";
        assert!(!resolv_conf_has_real_upstream(systemd_stub));

        let mixed = "nameserver 127.0.0.1\nnameserver 1.1.1.1\n";
        assert!(resolv_conf_has_real_upstream(mixed));
        assert!(!resolv_conf_is_numa_managed(mixed));
    }

    #[test]
    fn try_port53_advisory_addr_in_use() {
        let err = std::io::Error::from(std::io::ErrorKind::AddrInUse);
        let msg = try_port53_advisory("0.0.0.0:53", &err).expect("should advise on port 53");
        assert!(msg.contains("cannot bind to"));
        assert!(msg.contains("already in use"));
        assert!(msg.contains("numa install"));
        assert!(msg.contains("bind_addr"));
    }

    #[test]
    fn try_port53_advisory_permission_denied() {
        let err = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
        let msg = try_port53_advisory("0.0.0.0:53", &err).expect("should advise on port 53");
        assert!(msg.contains("cannot bind to"));
        assert!(msg.contains("permission denied"));
        assert!(msg.contains("numa install"));
        assert!(msg.contains("bind_addr"));
    }

    #[test]
    fn try_port53_advisory_skips_non_53_ports() {
        let err = std::io::Error::from(std::io::ErrorKind::AddrInUse);
        assert!(try_port53_advisory("127.0.0.1:5354", &err).is_none());
        assert!(try_port53_advisory("[::]:853", &err).is_none());
    }

    #[test]
    fn try_port53_advisory_skips_unrelated_error_kinds() {
        let err = std::io::Error::from(std::io::ErrorKind::NotFound);
        assert!(try_port53_advisory("0.0.0.0:53", &err).is_none());
    }

    #[test]
    fn try_port53_advisory_skips_malformed_bind_addr() {
        let err = std::io::Error::from(std::io::ErrorKind::AddrInUse);
        assert!(try_port53_advisory("not-an-address", &err).is_none());
    }

    #[test]
    fn sc_query_running_service_is_registered() {
        assert!(parse_sc_registered(true, ""));
    }

    #[test]
    fn sc_query_stopped_service_is_registered() {
        let output = "SERVICE_NAME: Numa\n        TYPE: 10  WIN32_OWN\n        STATE: 1  STOPPED\n";
        assert!(parse_sc_registered(true, output));
    }

    #[test]
    fn sc_query_missing_service_not_registered() {
        let output = "[SC] EnumQueryServicesStatus:OpenService FAILED 1060:\n\nThe specified service does not exist as an installed service.\n";
        assert!(!parse_sc_registered(false, output));
    }

    #[test]
    fn sc_query_other_error_assumes_registered() {
        // Permission denied or other errors — don't assume unregistered.
        let output = "[SC] OpenService FAILED 5:\n\nAccess is denied.\n";
        assert!(parse_sc_registered(false, output));
    }

    #[test]
    fn parse_sc_state_running() {
        let output = "SERVICE_NAME: Numa\n        TYPE               : 10  WIN32_OWN_PROCESS\n        STATE              : 4  RUNNING\n        WIN32_EXIT_CODE    : 0\n";
        assert!(parse_sc_state(output).contains("RUNNING"));
    }

    #[test]
    fn parse_sc_state_stopped() {
        let output = "SERVICE_NAME: Numa\n        TYPE               : 10  WIN32_OWN_PROCESS\n        STATE              : 1  STOPPED\n";
        assert!(parse_sc_state(output).contains("STOPPED"));
    }

    #[test]
    fn parse_sc_state_not_installed() {
        let output = "[SC] EnumQueryServicesStatus:OpenService FAILED 1060:\n\n";
        assert_eq!(parse_sc_state(output), "Service is not installed.");
    }

    #[test]
    fn parse_sc_state_empty_output() {
        assert_eq!(parse_sc_state(""), "unknown");
    }

    #[cfg(windows)]
    #[test]
    fn windows_config_dir_equals_data_dir() {
        assert_eq!(crate::config_dir(), crate::data_dir());
    }
}