wakezilla 0.2.10

A Wake-on-LAN proxy server written in Rust
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
use crate::{config, service, update};
use anyhow::{anyhow, Context, Result};
#[cfg(target_os = "windows")]
use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _};
use std::io::Cursor;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::io::Write as _;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::os::fd::AsRawFd;
#[cfg(target_os = "linux")]
use std::os::fd::{FromRawFd, OwnedFd};
#[cfg(target_os = "macos")]
use std::os::unix::fs::MetadataExt;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use tray_icon::{
    menu::{Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu},
    Icon, TrayIcon, TrayIconBuilder,
};
#[cfg(target_os = "macos")]
use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
use winit::{
    application::ApplicationHandler,
    event::{StartCause, WindowEvent},
    event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy},
    window::WindowId,
};

const TRAY_INSTANCE_NAME: &str = "dev.wakezilla.tray";
const OPEN_DASHBOARD_ID: &str = "open_dashboard";
const COPY_DASHBOARD_URL_ID: &str = "copy_dashboard_url";
const SETUP_ID: &str = "setup_services";
const CHECK_UPDATES_ID: &str = "check_updates";
const QUIT_ID: &str = "quit_tray";
const PROXY_START_ID: &str = "proxy_start";
const PROXY_STOP_ID: &str = "proxy_stop";
const PROXY_RESTART_ID: &str = "proxy_restart";
const PROXY_LOGS_ID: &str = "proxy_logs";
const CLIENT_START_ID: &str = "client_start";
const CLIENT_STOP_ID: &str = "client_stop";
const CLIENT_RESTART_ID: &str = "client_restart";
const CLIENT_LOGS_ID: &str = "client_logs";

#[derive(Debug)]
enum UserEvent {
    Menu(String),
    Refresh,
    Status(ServiceStatuses),
    Message(String),
}

#[derive(Debug, Clone, Copy)]
enum ServiceControl {
    Start,
    Stop,
    Restart,
}

struct ModeMenu {
    status: MenuItem,
    start: MenuItem,
    stop: MenuItem,
    restart: MenuItem,
    logs: MenuItem,
}

struct TrayMenu {
    message: MenuItem,
    proxy: ModeMenu,
    client: ModeMenu,
}

struct TrayApp {
    dashboard_url: String,
    proxy: EventLoopProxy<UserEvent>,
    menu: Option<TrayMenu>,
    tray_icon: Option<TrayIcon>,
    startup_error: Option<String>,
    status_refresh_in_flight: bool,
}

struct TrayInstanceGuard {
    #[cfg(target_os = "linux")]
    _socket: OwnedFd,
    #[cfg(target_os = "windows")]
    _instance: single_instance::SingleInstance,
    #[cfg(target_os = "macos")]
    _lock_file: std::fs::File,
}

impl TrayInstanceGuard {
    fn acquire_named(name: &str) -> Result<Option<Self>> {
        #[cfg(target_os = "linux")]
        {
            Self::acquire_linux(name)
        }

        #[cfg(target_os = "windows")]
        {
            let backend_name = name.to_owned();
            let instance =
                single_instance::SingleInstance::new(&backend_name).with_context(|| {
                    format!("failed to acquire tray instance lock `{name}` as `{backend_name}`")
                })?;
            if !instance.is_single() {
                return Ok(None);
            }

            Ok(Some(Self {
                _instance: instance,
            }))
        }

        #[cfg(target_os = "macos")]
        {
            Self::acquire_macos(name)
        }
    }

    #[cfg(target_os = "linux")]
    fn acquire_linux(name: &str) -> Result<Option<Self>> {
        let backend_name = linux_backend_name(name, effective_uid());
        let socket_type = combine_linux_socket_type(libc::SOCK_STREAM, libc::SOCK_CLOEXEC);

        // SAFETY: socket is called with valid Linux domain/type/protocol constants and no
        // pointers. A nonnegative result is a newly owned descriptor.
        let raw_socket = unsafe { libc::socket(libc::AF_UNIX, socket_type, 0) };
        if raw_socket < 0 {
            return Err(std::io::Error::last_os_error()).with_context(|| {
                format!("failed to create tray instance socket `{backend_name}`")
            });
        }
        // SAFETY: raw_socket was just returned as an owned descriptor and has not been wrapped
        // or closed. OwnedFd now closes it on every return path.
        let socket = unsafe { OwnedFd::from_raw_fd(raw_socket) };
        let (address, address_len) = linux_abstract_socket_address(&backend_name)?;

        // SAFETY: socket is a valid AF_UNIX descriptor; address points to an initialized
        // sockaddr_un and address_len covers only its family and populated abstract name.
        let rc = unsafe {
            libc::bind(
                socket.as_raw_fd(),
                std::ptr::addr_of!(address).cast::<libc::sockaddr>(),
                address_len,
            )
        };
        if rc == 0 {
            return Ok(Some(Self { _socket: socket }));
        }

        let error = std::io::Error::last_os_error();
        if error.raw_os_error() == Some(libc::EADDRINUSE) {
            Ok(None)
        } else {
            Err(error)
                .with_context(|| format!("failed to bind tray instance socket `{backend_name}`"))
        }
    }

    #[cfg(target_os = "macos")]
    fn acquire_macos(name: &str) -> Result<Option<Self>> {
        let lock_path = macos_lock_path(name)?;
        let mut options = std::fs::OpenOptions::new();
        options.read(true).write(true).create(true);
        options.mode(0o600);
        options.custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW);
        let lock_file = options
            .open(&lock_path)
            .with_context(|| format!("failed to open tray lock {}", lock_path.display()))?;
        lock_file
            .set_permissions(std::fs::Permissions::from_mode(0o600))
            .with_context(|| format!("failed to secure tray lock {}", lock_path.display()))?;

        // SAFETY: lock_file owns a valid descriptor for this call, and flock does not retain it
        // or access Rust-managed memory.
        let rc = unsafe { libc::flock(lock_file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
        let errno = if rc == 0 {
            0
        } else {
            std::io::Error::last_os_error()
                .raw_os_error()
                .unwrap_or(libc::EIO)
        };

        match classify_macos_flock_result(rc, errno)
            .with_context(|| format!("failed to lock tray instance file {}", lock_path.display()))?
        {
            MacosFlockOutcome::Acquired => Ok(Some(Self {
                _lock_file: lock_file,
            })),
            MacosFlockOutcome::Contended => Ok(None),
        }
    }
}

#[cfg(target_os = "linux")]
fn effective_uid() -> libc::uid_t {
    // SAFETY: geteuid has no preconditions and does not dereference any pointers.
    unsafe { libc::geteuid() }
}

#[cfg(target_os = "linux")]
fn linux_backend_name(name: &str, euid: libc::uid_t) -> String {
    format!("{name}.uid-{euid}")
}

#[cfg(any(target_os = "linux", test))]
fn combine_linux_socket_type(stream: i32, cloexec: i32) -> i32 {
    stream | cloexec
}

#[cfg(target_os = "linux")]
fn linux_abstract_socket_address(name: &str) -> Result<(libc::sockaddr_un, libc::socklen_t)> {
    // SAFETY: sockaddr_un contains only integer fields and a c_char array, for which all-zero is
    // a valid bit pattern. Zeroing also establishes the leading NUL for an abstract address.
    let mut address = unsafe { std::mem::zeroed::<libc::sockaddr_un>() };
    address.sun_family = libc::AF_UNIX as libc::sa_family_t;

    let name_bytes = name.as_bytes();
    let maximum_name_len = address.sun_path.len().saturating_sub(1);
    if name_bytes.len() > maximum_name_len {
        anyhow::bail!(
            "tray instance socket name is {} bytes; maximum is {maximum_name_len}",
            name_bytes.len()
        );
    }
    address.sun_path[0] = 0;
    for (index, byte) in name_bytes.iter().enumerate() {
        address.sun_path[index + 1] = *byte as libc::c_char;
    }

    let address_len = std::mem::offset_of!(libc::sockaddr_un, sun_path) + 1 + name_bytes.len();
    let address_len = libc::socklen_t::try_from(address_len)
        .context("tray instance socket address length overflowed socklen_t")?;
    Ok((address, address_len))
}

#[cfg(target_os = "macos")]
#[derive(Debug, Eq, PartialEq)]
enum MacosFlockOutcome {
    Acquired,
    Contended,
}

#[cfg(target_os = "macos")]
fn classify_macos_flock_result(
    rc: libc::c_int,
    errno: libc::c_int,
) -> std::io::Result<MacosFlockOutcome> {
    if rc == 0 {
        Ok(MacosFlockOutcome::Acquired)
    } else if errno == libc::EWOULDBLOCK {
        Ok(MacosFlockOutcome::Contended)
    } else {
        Err(std::io::Error::from_raw_os_error(errno))
    }
}

#[cfg(target_os = "macos")]
fn macos_lock_path(name: &str) -> Result<PathBuf> {
    let temp_dir = std::env::temp_dir()
        .canonicalize()
        .context("failed to resolve the per-user temporary directory")?;
    let lock_dir = temp_dir.join("Wakezilla");
    let mut builder = std::fs::DirBuilder::new();
    builder.mode(0o700);
    match builder.create(&lock_dir) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
        Err(error) => {
            return Err(error).with_context(|| format!("failed to create {}", lock_dir.display()));
        }
    }

    let metadata = std::fs::symlink_metadata(&lock_dir)
        .with_context(|| format!("failed to inspect {}", lock_dir.display()))?;
    if !metadata.file_type().is_dir() {
        anyhow::bail!(
            "tray lock directory is not a directory: {}",
            lock_dir.display()
        );
    }
    if metadata.permissions().mode() & 0o7777 != 0o700 {
        std::fs::set_permissions(&lock_dir, std::fs::Permissions::from_mode(0o700))
            .with_context(|| format!("failed to secure {}", lock_dir.display()))?;
    }

    let file_name = name
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_') {
                character
            } else {
                '_'
            }
        })
        .collect::<String>();
    Ok(lock_dir.join(format!("instance-{file_name}.lock")))
}

#[derive(Debug, Clone, Copy)]
struct ServiceStatuses {
    proxy: ModeStatus,
    client: ModeStatus,
}

#[derive(Debug, Clone, Copy)]
struct ModeStatus {
    installed: bool,
    running: bool,
}

pub fn run() -> Result<()> {
    let Some(_instance_guard) = TrayInstanceGuard::acquire_named(TRAY_INSTANCE_NAME)? else {
        return Ok(());
    };

    #[cfg(target_os = "linux")]
    gtk::init().context("failed to initialize GTK")?;

    let config = config::Config::load();
    let dashboard_url = dashboard_url(&config);

    let mut builder = EventLoop::<UserEvent>::with_user_event();
    #[cfg(target_os = "macos")]
    builder.with_activation_policy(ActivationPolicy::Accessory);
    let event_loop = builder
        .build()
        .context("failed to create tray event loop")?;
    event_loop.set_control_flow(ControlFlow::Wait);

    let proxy = event_loop.create_proxy();
    install_menu_event_handler(proxy.clone());
    start_refresh_timer(proxy.clone());

    let mut app = TrayApp {
        dashboard_url,
        proxy,
        menu: None,
        tray_icon: None,
        startup_error: None,
        status_refresh_in_flight: false,
    };

    event_loop
        .run_app(&mut app)
        .context("tray event loop failed")?;

    if let Some(error) = app.startup_error {
        anyhow::bail!(error);
    }
    Ok(())
}

fn install_menu_event_handler(proxy: EventLoopProxy<UserEvent>) {
    MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
        let _ = proxy.send_event(UserEvent::Menu(event.id().as_ref().to_string()));
    }));
}

fn start_refresh_timer(proxy: EventLoopProxy<UserEvent>) {
    std::thread::spawn(move || loop {
        std::thread::sleep(Duration::from_secs(10));
        if proxy.send_event(UserEvent::Refresh).is_err() {
            break;
        }
    });
}

impl ApplicationHandler<UserEvent> for TrayApp {
    fn resumed(&mut self, _event_loop: &ActiveEventLoop) {}

    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
        if !matches!(cause, StartCause::Init) || self.tray_icon.is_some() {
            return;
        }

        if let Err(error) = self.create_tray_icon() {
            self.startup_error = Some(error.to_string());
            tracing::error!("Tray startup failed: {error:#}");
            event_loop.exit();
        }
    }

    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
        match event {
            UserEvent::Menu(id) => self.handle_menu_event(event_loop, &id),
            UserEvent::Refresh => self.refresh_status(),
            UserEvent::Status(statuses) => self.apply_status(statuses),
            UserEvent::Message(message) => self.set_message(message),
        }
    }

    fn window_event(
        &mut self,
        _event_loop: &ActiveEventLoop,
        _window_id: WindowId,
        _event: WindowEvent,
    ) {
    }
}

impl TrayApp {
    fn create_tray_icon(&mut self) -> Result<()> {
        let (root_menu, tray_menu) = build_menu()?;
        let icon = load_tray_icon()?;

        let tray_icon = TrayIconBuilder::new()
            .with_tooltip("Wakezilla")
            .with_icon(icon)
            .with_menu(Box::new(root_menu))
            .with_menu_on_left_click(true)
            .build()
            .context("failed to build tray icon")?;

        self.menu = Some(tray_menu);
        self.tray_icon = Some(tray_icon);
        self.refresh_status();
        Ok(())
    }

    fn handle_menu_event(&mut self, event_loop: &ActiveEventLoop, id: &str) {
        match id {
            OPEN_DASHBOARD_ID => self.open_dashboard(),
            COPY_DASHBOARD_URL_ID => self.copy_dashboard_url(),
            SETUP_ID => self.configure_startup(),
            CHECK_UPDATES_ID => self.check_for_updates(),
            QUIT_ID => event_loop.exit(),
            PROXY_START_ID => self.run_service_control(service::Mode::Proxy, ServiceControl::Start),
            PROXY_STOP_ID => self.run_service_control(service::Mode::Proxy, ServiceControl::Stop),
            PROXY_RESTART_ID => {
                self.run_service_control(service::Mode::Proxy, ServiceControl::Restart)
            }
            PROXY_LOGS_ID => self.open_logs(service::Mode::Proxy),
            CLIENT_START_ID => {
                self.run_service_control(service::Mode::Client, ServiceControl::Start)
            }
            CLIENT_STOP_ID => self.run_service_control(service::Mode::Client, ServiceControl::Stop),
            CLIENT_RESTART_ID => {
                self.run_service_control(service::Mode::Client, ServiceControl::Restart)
            }
            CLIENT_LOGS_ID => self.open_logs(service::Mode::Client),
            _ => {}
        }
    }

    fn open_dashboard(&mut self) {
        match open::that(&self.dashboard_url) {
            Ok(()) => self.set_message(format!("Opened {}", self.dashboard_url)),
            Err(error) => self.set_message(format!("Failed to open dashboard: {error}")),
        }
    }

    fn copy_dashboard_url(&mut self) {
        let result = arboard::Clipboard::new()
            .and_then(|mut clipboard| clipboard.set_text(self.dashboard_url.clone()));

        match result {
            Ok(()) => self.set_message("Dashboard URL copied.".to_string()),
            Err(error) => self.set_message(format!("Failed to copy dashboard URL: {error}")),
        }
    }

    fn configure_startup(&mut self) {
        let autostart = install_tray_autostart();
        let setup = open_wakezilla_command(true, &["setup"], true);

        match (autostart, setup) {
            (Ok(path), Ok(())) => self.set_message(format!(
                "Tray autostart installed at {}; opened service setup.",
                path.display()
            )),
            (Ok(path), Err(error)) => self.set_message(format!(
                "Tray autostart installed at {}; failed to open service setup: {error}",
                path.display()
            )),
            (Err(error), Ok(())) => self.set_message(format!(
                "Failed to install tray autostart: {error}; opened service setup."
            )),
            (Err(autostart_error), Err(setup_error)) => self.set_message(format!(
                "Startup setup failed: {autostart_error}; service setup failed: {setup_error}"
            )),
        }
    }

    fn open_logs(&mut self, mode: service::Mode) {
        let result = open_wakezilla_command(
            true,
            &[
                "--no-update-check",
                "service",
                "logs",
                "--mode",
                mode.service_arg(),
                "--lines",
                "100",
            ],
            true,
        );

        match result {
            Ok(()) => self.set_message(format!("Opened {} logs.", mode_label(mode))),
            Err(error) => {
                self.set_message(format!("Failed to open {} logs: {error}", mode_label(mode)))
            }
        }
    }

    fn check_for_updates(&mut self) {
        self.set_message("Checking for updates...".to_string());
        let proxy = self.proxy.clone();

        std::thread::spawn(move || {
            let message = match check_latest_version() {
                Ok(message) => message,
                Err(error) => format!("Update check failed: {error}"),
            };
            let _ = proxy.send_event(UserEvent::Message(message));
        });
    }

    fn run_service_control(&mut self, mode: service::Mode, control: ServiceControl) {
        self.set_message(format!(
            "{} {} requested...",
            mode_label(mode),
            control.verb()
        ));

        let proxy = self.proxy.clone();
        std::thread::spawn(move || {
            let message = match run_service_control(mode, control) {
                Ok(message) => message,
                Err(error) => format!("{} {} failed: {error}", mode_label(mode), control.verb()),
            };
            let _ = proxy.send_event(UserEvent::Message(message));
            let _ = proxy.send_event(UserEvent::Refresh);
        });
    }

    fn refresh_status(&mut self) {
        if self.menu.is_none() || self.status_refresh_in_flight {
            return;
        }

        self.status_refresh_in_flight = true;
        let proxy = self.proxy.clone();
        std::thread::spawn(move || {
            let statuses = ServiceStatuses {
                proxy: query_mode_status(service::Mode::Proxy),
                client: query_mode_status(service::Mode::Client),
            };
            let _ = proxy.send_event(UserEvent::Status(statuses));
        });
    }

    fn apply_status(&mut self, statuses: ServiceStatuses) {
        self.status_refresh_in_flight = false;
        if let Some(menu) = &self.menu {
            update_mode_menu(service::Mode::Proxy, &menu.proxy, statuses.proxy);
            update_mode_menu(service::Mode::Client, &menu.client, statuses.client);
        }
    }

    fn set_message(&mut self, message: String) {
        if let Some(menu) = &self.menu {
            menu.message.set_text(message);
        }
    }
}

impl ServiceControl {
    fn verb(self) -> &'static str {
        match self {
            ServiceControl::Start => "start",
            ServiceControl::Stop => "stop",
            ServiceControl::Restart => "restart",
        }
    }
}

fn build_menu() -> Result<(Menu, TrayMenu)> {
    let open_dashboard = MenuItem::with_id(OPEN_DASHBOARD_ID, "Open dashboard", true, None);
    let copy_dashboard_url =
        MenuItem::with_id(COPY_DASHBOARD_URL_ID, "Copy dashboard URL", true, None);
    let setup = MenuItem::with_id(SETUP_ID, "Configure startup", true, None);
    let check_updates = MenuItem::with_id(CHECK_UPDATES_ID, "Check for updates", true, None);
    let quit = MenuItem::with_id(QUIT_ID, "Quit tray", true, None);
    let message = MenuItem::with_id("tray_message", "Ready", false, None);

    let (proxy_submenu, proxy) = build_mode_submenu(service::Mode::Proxy)?;
    let (client_submenu, client) = build_mode_submenu(service::Mode::Client)?;

    let separator1 = PredefinedMenuItem::separator();
    let separator2 = PredefinedMenuItem::separator();
    let separator3 = PredefinedMenuItem::separator();
    let separator4 = PredefinedMenuItem::separator();

    let root = Menu::new();
    root.append_items(&[
        &message,
        &separator1,
        &open_dashboard,
        &copy_dashboard_url,
        &separator2,
        &proxy_submenu,
        &client_submenu,
        &separator3,
        &setup,
        &check_updates,
        &separator4,
        &quit,
    ])
    .context("failed to build tray menu")?;

    Ok((
        root,
        TrayMenu {
            message,
            proxy,
            client,
        },
    ))
}

fn build_mode_submenu(mode: service::Mode) -> Result<(Submenu, ModeMenu)> {
    let (status_id, start_id, stop_id, restart_id, logs_id) = match mode {
        service::Mode::Proxy => (
            "proxy_status",
            PROXY_START_ID,
            PROXY_STOP_ID,
            PROXY_RESTART_ID,
            PROXY_LOGS_ID,
        ),
        service::Mode::Client => (
            "client_status",
            CLIENT_START_ID,
            CLIENT_STOP_ID,
            CLIENT_RESTART_ID,
            CLIENT_LOGS_ID,
        ),
    };

    let status = MenuItem::with_id(
        status_id,
        format!("{}: unknown", mode_label(mode)),
        false,
        None,
    );
    let start = MenuItem::with_id(start_id, "Start", true, None);
    let stop = MenuItem::with_id(stop_id, "Stop", true, None);
    let restart = MenuItem::with_id(restart_id, "Restart", true, None);
    let logs = MenuItem::with_id(logs_id, "Logs", true, None);
    let separator1 = PredefinedMenuItem::separator();
    let separator2 = PredefinedMenuItem::separator();

    let submenu = Submenu::with_id(mode.service_arg(), mode_label(mode), true);
    submenu
        .append_items(&[
            &status,
            &separator1,
            &start,
            &stop,
            &restart,
            &separator2,
            &logs,
        ])
        .with_context(|| format!("failed to build {} tray menu", mode_label(mode)))?;

    Ok((
        submenu,
        ModeMenu {
            status,
            start,
            stop,
            restart,
            logs,
        },
    ))
}

fn update_mode_menu(mode: service::Mode, menu: &ModeMenu, status: ModeStatus) {
    let installed = status.installed;
    let running = status.running;
    let label = service_status_label(status);

    menu.status
        .set_text(format!("{}: {label}", mode_label(mode)));
    menu.start.set_enabled(installed && !running);
    menu.stop.set_enabled(installed && running);
    menu.restart.set_enabled(installed);
    menu.logs.set_enabled(installed);
}

fn query_mode_status(mode: service::Mode) -> ModeStatus {
    let installed = service::is_installed(mode);
    let running = installed && service::is_running(mode);

    ModeStatus { installed, running }
}

fn service_status_label(status: ModeStatus) -> &'static str {
    if !status.installed {
        "not installed"
    } else if status.running {
        "running"
    } else {
        "stopped"
    }
}

fn run_service_control(mode: service::Mode, control: ServiceControl) -> Result<String> {
    if service::is_elevated() {
        match control {
            ServiceControl::Start => service::start(mode),
            ServiceControl::Stop => service::stop(mode),
            ServiceControl::Restart => service::restart(mode),
        }
        .with_context(|| format!("failed to {} {} service", control.verb(), mode_label(mode)))?;

        return Ok(format!(
            "{} {} completed.",
            mode_label(mode),
            control.verb()
        ));
    }

    open_wakezilla_command(
        true,
        &[
            "--no-update-check",
            "service",
            control.verb(),
            "--mode",
            mode.service_arg(),
        ],
        true,
    )?;
    Ok(format!(
        "Opened elevated {} {} command.",
        mode_label(mode),
        control.verb()
    ))
}

fn check_latest_version() -> Result<String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("failed to create update check runtime")?;

    runtime.block_on(async {
        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(5))
            .build()
            .context("failed to create update check HTTP client")?;

        match update::check_latest(&client, env!("CARGO_PKG_VERSION")).await? {
            update::UpdateStatus::Current { current } => {
                Ok(format!("Wakezilla is up to date ({current})."))
            }
            update::UpdateStatus::Available { current, latest } => Ok(format!(
                "Wakezilla {latest} is available (current {current})."
            )),
        }
    })
}

fn dashboard_url(config: &config::Config) -> String {
    format!("http://127.0.0.1:{}", config.server.proxy_port)
}

fn mode_label(mode: service::Mode) -> &'static str {
    match mode {
        service::Mode::Proxy => "Proxy",
        service::Mode::Client => "Client",
    }
}

fn load_tray_icon() -> Result<Icon> {
    let bytes = include_bytes!("../../frontend/public/images/wakezilla.png");
    let mut decoder = png::Decoder::new(Cursor::new(&bytes[..]));
    decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
    let mut reader = decoder.read_info().context("failed to decode tray icon")?;
    let output_size = reader
        .output_buffer_size()
        .context("tray icon output buffer is too large")?;
    let mut buffer = vec![0; output_size];
    let frame = reader
        .next_frame(&mut buffer)
        .context("failed to read tray icon frame")?;
    let bytes = &buffer[..frame.buffer_size()];
    let rgba = rgba_from_png_frame(bytes, frame.color_type)?;

    Icon::from_rgba(rgba, frame.width, frame.height).context("failed to create tray icon")
}

fn rgba_from_png_frame(bytes: &[u8], color_type: png::ColorType) -> Result<Vec<u8>> {
    match color_type {
        png::ColorType::Rgba => Ok(bytes.to_vec()),
        png::ColorType::Rgb => {
            let mut rgba = Vec::with_capacity(bytes.len() / 3 * 4);
            for chunk in bytes.chunks_exact(3) {
                rgba.extend_from_slice(chunk);
                rgba.push(255);
            }
            Ok(rgba)
        }
        png::ColorType::Grayscale => {
            let mut rgba = Vec::with_capacity(bytes.len() * 4);
            for gray in bytes {
                rgba.extend_from_slice(&[*gray, *gray, *gray, 255]);
            }
            Ok(rgba)
        }
        png::ColorType::GrayscaleAlpha => {
            let mut rgba = Vec::with_capacity(bytes.len() / 2 * 4);
            for chunk in bytes.chunks_exact(2) {
                rgba.extend_from_slice(&[chunk[0], chunk[0], chunk[0], chunk[1]]);
            }
            Ok(rgba)
        }
        png::ColorType::Indexed => Err(anyhow!("indexed tray icon was not expanded to RGBA")),
    }
}

fn open_wakezilla_command(elevated: bool, args: &[&str], keep_open: bool) -> Result<()> {
    let exe = wakezilla_cli_exe()?;
    open_command(elevated, &exe, args, keep_open)
}

fn wakezilla_cli_exe() -> Result<PathBuf> {
    let exe = std::env::current_exe().context("failed to resolve wakezilla executable")?;
    if !is_wakezilla_tray_exe(&exe) {
        return Ok(exe);
    }

    sibling_exe(&exe, "wakezilla").with_context(|| {
        format!(
            "failed to find wakezilla CLI executable next to {}",
            exe.display()
        )
    })
}

#[cfg(target_os = "windows")]
fn wakezilla_tray_command() -> Result<(PathBuf, Vec<&'static str>)> {
    let exe = std::env::current_exe().context("failed to resolve wakezilla executable")?;
    if is_wakezilla_tray_exe(&exe) {
        return Ok((exe, Vec::new()));
    }

    if let Some(tray_exe) = sibling_exe(&exe, "wakezilla-tray") {
        return Ok((tray_exe, Vec::new()));
    }

    Err(anyhow!(
        "wakezilla-tray helper is required for graphical startup; refusing to launch the console CLI"
    ))
}

fn is_wakezilla_tray_exe(exe: &Path) -> bool {
    exe.file_stem()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.eq_ignore_ascii_case("wakezilla-tray"))
}

fn sibling_exe(exe: &Path, name: &str) -> Option<PathBuf> {
    #[cfg(target_os = "windows")]
    let file_name = format!("{name}.exe");
    #[cfg(not(target_os = "windows"))]
    let file_name = name;

    let candidate = exe.parent()?.join(file_name);
    candidate.is_file().then_some(candidate)
}

#[cfg(target_os = "linux")]
fn install_tray_autostart() -> Result<std::path::PathBuf> {
    let current_exe = std::env::current_exe().context("failed to resolve wakezilla executable")?;
    let helper = if is_wakezilla_tray_exe(&current_exe) {
        current_exe
    } else {
        sibling_exe(&current_exe, "wakezilla-tray").with_context(|| {
            format!(
                "failed to find wakezilla-tray next to {}",
                current_exe.display()
            )
        })?
    };
    let xdg_config_home = std::env::var_os("XDG_CONFIG_HOME");
    let home = std::env::var_os("HOME");
    let config_home = resolve_linux_config_home(xdg_config_home.as_deref(), home.as_deref())?;
    install_linux_tray_autostart_at(&config_home, &helper)
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn resolve_linux_config_home(
    xdg_config_home: Option<&std::ffi::OsStr>,
    home: Option<&std::ffi::OsStr>,
) -> Result<PathBuf> {
    if let Some(path) = xdg_config_home
        .map(Path::new)
        .filter(|path| path.is_absolute())
    {
        return Ok(path.to_path_buf());
    }
    let home = home
        .map(Path::new)
        .filter(|path| path.is_absolute())
        .context("absolute HOME or XDG_CONFIG_HOME is required to install tray autostart")?;
    Ok(home.join(".config"))
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn install_linux_tray_autostart_at(config_home: &Path, helper: &Path) -> Result<PathBuf> {
    let helper = helper
        .to_str()
        .context("wakezilla-tray path must be valid UTF-8 for a desktop entry")?;
    let autostart_dir = config_home.join("autostart");
    let mut directory_builder = std::fs::DirBuilder::new();
    directory_builder.recursive(true).mode(0o700);
    directory_builder
        .create(&autostart_dir)
        .with_context(|| format!("failed to create {}", autostart_dir.display()))?;
    let canonical = autostart_dir.join("dev.wakezilla.tray.desktop");
    let content = format!(
        "[Desktop Entry]\n\
         Type=Application\n\
         Name=Wakezilla\n\
         Comment=Wakezilla network wake-on-LAN tray application\n\
         TryExec={}\n\
         Exec={}\n\
         Icon=dev.wakezilla.Wakezilla\n\
         Terminal=false\n\
         StartupNotify=false\n",
        desktop_string_escape(helper)?,
        desktop_entry_quote(helper)?,
    );
    atomic_write_linux_autostart(&canonical, content.as_bytes())?;

    let legacy = autostart_dir.join("wakezilla-tray.desktop");
    if let Ok(metadata) = std::fs::symlink_metadata(&legacy) {
        if metadata.file_type().is_file()
            && std::fs::read(&legacy).is_ok_and(|legacy_content| {
                std::str::from_utf8(&legacy_content).is_ok_and(linux_legacy_autostart_is_owned)
            })
        {
            std::fs::remove_file(&legacy)
                .with_context(|| format!("failed to remove {}", legacy.display()))?;
        }
    }
    Ok(canonical)
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn atomic_write_linux_autostart(path: &Path, content: &[u8]) -> Result<()> {
    use std::sync::atomic::{AtomicU64, Ordering};

    static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
    let parent = path
        .parent()
        .context("Linux autostart path has no parent directory")?;
    let file_name = path
        .file_name()
        .context("Linux autostart path has no file name")?
        .to_string_lossy();
    let (temp_path, mut temp_file) = loop {
        let suffix = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
        let candidate = parent.join(format!(
            ".{file_name}.tmp.{}.{}",
            std::process::id(),
            suffix
        ));
        match std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(&candidate)
        {
            Ok(file) => break (candidate, file),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => {
                return Err(error)
                    .with_context(|| format!("failed to create {}", candidate.display()));
            }
        }
    };

    let publish_result = (|| -> Result<()> {
        temp_file
            .write_all(content)
            .with_context(|| format!("failed to write {}", temp_path.display()))?;
        temp_file
            .sync_all()
            .with_context(|| format!("failed to sync {}", temp_path.display()))?;
        std::fs::set_permissions(&temp_path, std::fs::Permissions::from_mode(0o644))
            .with_context(|| format!("failed to chmod {}", temp_path.display()))?;
        std::fs::rename(&temp_path, path).with_context(|| {
            format!(
                "failed to publish Linux autostart {} -> {}",
                temp_path.display(),
                path.display()
            )
        })?;
        Ok(())
    })();
    if publish_result.is_err() {
        let _ = std::fs::remove_file(&temp_path);
    }
    publish_result
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn linux_legacy_autostart_is_owned(content: &str) -> bool {
    let mut in_desktop_entry = false;
    let mut entry_type = false;
    let mut name = false;
    let mut exec = false;
    for raw_line in content.lines() {
        let line = raw_line.trim();
        if line.starts_with('[') && line.ends_with(']') {
            if in_desktop_entry && entry_type && name && exec {
                return true;
            }
            in_desktop_entry = line == "[Desktop Entry]";
            entry_type = false;
            name = false;
            exec = false;
            continue;
        }
        if !in_desktop_entry {
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let value = value.trim();
        match key.trim() {
            "Type" => entry_type = value == "Application",
            "Name" => name = matches!(value, "Wakezilla" | "Wakezilla Tray"),
            "Exec" => exec = linux_legacy_exec_is_owned(value),
            _ => {}
        }
    }
    entry_type && name && exec
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn linux_legacy_exec_is_owned(value: &str) -> bool {
    let tokens = linux_desktop_exec_tokens(value, 2);
    let Some(executable) = tokens.first() else {
        return false;
    };
    let Some(basename) = Path::new(executable)
        .file_name()
        .and_then(|name| name.to_str())
    else {
        return false;
    };
    basename == "wakezilla-tray"
        || (basename == "wakezilla" && tokens.get(1).is_some_and(|argument| argument == "tray"))
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn linux_desktop_exec_tokens(value: &str, limit: usize) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut characters = value.chars().peekable();
    while tokens.len() < limit {
        while characters
            .peek()
            .is_some_and(|character| character.is_ascii_whitespace())
        {
            characters.next();
        }
        if characters.peek().is_none() {
            break;
        }
        let quoted = characters.peek() == Some(&'"');
        if quoted {
            characters.next();
        }
        let mut token = String::new();
        let mut terminated = !quoted;
        while let Some(character) = characters.next() {
            if quoted && character == '"' {
                terminated = true;
                break;
            }
            if !quoted && character.is_ascii_whitespace() {
                break;
            }
            if character == '\\' {
                let Some(escaped) = characters.next() else {
                    return Vec::new();
                };
                token.push(escaped);
            } else {
                token.push(character);
            }
        }
        if !terminated || token.is_empty() {
            return Vec::new();
        }
        tokens.push(token);
    }
    tokens
}

#[cfg(target_os = "macos")]
fn install_tray_autostart() -> Result<std::path::PathBuf> {
    let executable = std::env::current_exe().context("failed to resolve wakezilla executable")?;
    let home = std::env::var_os("HOME")
        .map(std::path::PathBuf::from)
        .context("HOME is required to install tray autostart")?;
    install_macos_tray_autostart_at(&home, &executable)
}

#[cfg(target_os = "macos")]
fn install_macos_tray_autostart_at(home: &Path, executable: &Path) -> Result<PathBuf> {
    // SAFETY: geteuid has no preconditions and does not dereference pointers.
    let effective_uid = unsafe { libc::geteuid() };
    install_macos_tray_autostart_for_uid(home, executable, effective_uid)
}

#[cfg(target_os = "macos")]
fn install_macos_tray_autostart_for_uid(
    home: &Path,
    executable: &Path,
    effective_uid: libc::uid_t,
) -> Result<PathBuf> {
    if effective_uid == 0 {
        anyhow::bail!("macOS tray autostart must be installed without sudo");
    }
    if !home.is_absolute() {
        anyhow::bail!("HOME must be absolute to install macOS tray autostart");
    }
    let home_metadata = std::fs::symlink_metadata(home)
        .with_context(|| format!("failed to inspect HOME {}", home.display()))?;
    if !home_metadata.file_type().is_dir() || home_metadata.file_type().is_symlink() {
        anyhow::bail!("HOME must be a real, non-symlink directory");
    }
    if home_metadata.uid() != effective_uid {
        anyhow::bail!("HOME is not owned by the effective user");
    }
    let home = home
        .canonicalize()
        .with_context(|| format!("failed to resolve HOME {}", home.display()))?;
    let bundle = macos_bundle_from_executable(executable)?;
    let content = macos_launch_agent_content(&bundle)?;

    let library = home.join("Library");
    ensure_macos_profile_directory(&home, &library, effective_uid)?;
    let launch_agents = library.join("LaunchAgents");
    ensure_macos_profile_directory(&home, &launch_agents, effective_uid)?;
    let path = launch_agents.join("dev.wakezilla.tray.plist");
    atomic_write_macos_launch_agent(&path, content.as_bytes())?;
    Ok(path)
}

#[cfg(target_os = "macos")]
fn macos_bundle_from_executable(executable: &Path) -> Result<PathBuf> {
    let executable = executable
        .canonicalize()
        .with_context(|| format!("failed to resolve executable {}", executable.display()))?;
    if !executable.is_file() || !is_wakezilla_tray_exe(&executable) {
        anyhow::bail!(
            "macOS tray autostart requires a wakezilla-tray executable inside Wakezilla.app"
        );
    }
    let macos = executable
        .parent()
        .filter(|path| path.file_name().is_some_and(|name| name == "MacOS"))
        .context("wakezilla-tray is not inside a bundle Contents/MacOS directory")?;
    let contents = macos
        .parent()
        .filter(|path| path.file_name().is_some_and(|name| name == "Contents"))
        .context("wakezilla-tray is not inside a bundle Contents/MacOS directory")?;
    let bundle = contents
        .parent()
        .filter(|path| path.extension().is_some_and(|extension| extension == "app"))
        .context("wakezilla-tray is not inside a macOS application bundle")?;
    if !bundle.is_dir() {
        anyhow::bail!("macOS application bundle is not a directory");
    }
    Ok(bundle.to_path_buf())
}

#[cfg(target_os = "macos")]
fn macos_launch_agent_content(bundle: &Path) -> Result<String> {
    let bundle = bundle
        .to_str()
        .context("Wakezilla.app path must be valid UTF-8 for a LaunchAgent")?;
    let bundle = xml_escape(bundle)?;
    Ok(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\
           <key>Label</key>\n\
           <string>dev.wakezilla.tray</string>\n\
           <key>ProgramArguments</key>\n\
           <array>\n\
             <string>/usr/bin/open</string>\n\
             <string>-g</string>\n\
             <string>{bundle}</string>\n\
           </array>\n\
           <key>RunAtLoad</key>\n\
           <true/>\n\
           <key>LimitLoadToSessionType</key>\n\
           <string>Aqua</string>\n\
           <key>ProcessType</key>\n\
           <string>Interactive</string>\n\
           <key>AssociatedBundleIdentifiers</key>\n\
           <array>\n\
             <string>dev.wakezilla.Wakezilla</string>\n\
           </array>\n\
         </dict>\n\
         </plist>\n"
    ))
}

#[cfg(target_os = "macos")]
fn ensure_macos_profile_directory(
    home: &Path,
    directory: &Path,
    effective_uid: libc::uid_t,
) -> Result<()> {
    match std::fs::symlink_metadata(directory) {
        Ok(metadata) => {
            if !metadata.file_type().is_dir() || metadata.file_type().is_symlink() {
                anyhow::bail!("unsafe macOS profile directory: {}", directory.display());
            }
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            let mut builder = std::fs::DirBuilder::new();
            builder.mode(0o700);
            builder
                .create(directory)
                .with_context(|| format!("failed to create {}", directory.display()))?;
        }
        Err(error) => {
            return Err(error)
                .with_context(|| format!("failed to inspect {}", directory.display()));
        }
    }
    let canonical = directory
        .canonicalize()
        .with_context(|| format!("failed to resolve {}", directory.display()))?;
    if !canonical.starts_with(home) || canonical == home {
        anyhow::bail!(
            "macOS profile directory escaped HOME: {}",
            directory.display()
        );
    }
    let owner = std::fs::metadata(&canonical)
        .with_context(|| format!("failed to inspect {}", canonical.display()))?
        .uid();
    if owner != effective_uid {
        anyhow::bail!(
            "macOS profile directory is not owned by the effective user: {}",
            directory.display()
        );
    }
    Ok(())
}

#[cfg(target_os = "macos")]
struct MacosAtomicTemp(PathBuf);

#[cfg(target_os = "macos")]
impl Drop for MacosAtomicTemp {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

#[cfg(target_os = "macos")]
fn atomic_write_macos_launch_agent(path: &Path, content: &[u8]) -> Result<()> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) => {
            if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
                anyhow::bail!(
                    "refusing unsafe LaunchAgent destination: {}",
                    path.display()
                );
            }
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => {
            return Err(error).with_context(|| format!("failed to inspect {}", path.display()));
        }
    }
    let directory = path.parent().context("LaunchAgent path has no parent")?;
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .context("LaunchAgent file name must be valid UTF-8")?;
    let mut temporary = None;
    let mut file = None;
    for attempt in 0..100_u32 {
        let candidate =
            directory.join(format!(".{file_name}.tmp.{}.{attempt}", std::process::id()));
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create_new(true).mode(0o600);
        match options.open(&candidate) {
            Ok(opened) => {
                temporary = Some(MacosAtomicTemp(candidate));
                file = Some(opened);
                break;
            }
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => {
                return Err(error).with_context(|| format!("failed to stage {}", path.display()));
            }
        }
    }
    let mut file = file.context("failed to allocate a unique LaunchAgent staging file")?;
    let mut temporary = temporary.context("LaunchAgent staging path was not recorded")?;
    file.write_all(content)
        .with_context(|| format!("failed to stage {}", path.display()))?;
    file.set_permissions(std::fs::Permissions::from_mode(0o644))
        .with_context(|| format!("failed to set mode on staged {}", path.display()))?;
    file.sync_all()
        .with_context(|| format!("failed to sync staged {}", path.display()))?;
    drop(file);
    std::fs::rename(&temporary.0, path)
        .with_context(|| format!("failed to publish {}", path.display()))?;
    temporary.0 = PathBuf::new();
    Ok(())
}

#[cfg(target_os = "windows")]
fn install_tray_autostart() -> Result<std::path::PathBuf> {
    let (exe, args) = wakezilla_tray_command()?;
    let command = windows_command(&exe, &args);
    let status = Command::new("reg")
        .args([
            "add",
            r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run",
            "/v",
            "WakezillaTray",
            "/t",
            "REG_SZ",
            "/d",
        ])
        .arg(&command)
        .arg("/f")
        .status()
        .context("failed to invoke reg.exe")?;
    if !status.success() {
        anyhow::bail!("reg.exe failed to install tray autostart with status {status}");
    }
    Ok(exe)
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn desktop_entry_quote(value: &str) -> Result<String> {
    reject_desktop_controls(value)?;
    let exec_layer = value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('`', "\\`")
        .replace('$', "\\$")
        .replace('%', "%%");
    Ok(format!("\"{}\"", exec_layer.replace('\\', "\\\\")))
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn desktop_string_escape(value: &str) -> Result<String> {
    reject_desktop_controls(value)?;
    Ok(value.replace('\\', "\\\\"))
}

#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
fn reject_desktop_controls(value: &str) -> Result<()> {
    if value.chars().any(|character| character.is_ascii_control()) {
        anyhow::bail!("desktop entry value contains an ASCII control character");
    }
    Ok(())
}

#[cfg(target_os = "macos")]
fn xml_escape(value: &str) -> Result<String> {
    if value.chars().any(|character| character.is_ascii_control()) {
        anyhow::bail!("LaunchAgent value contains an ASCII control character");
    }
    Ok(value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;"))
}

#[cfg(target_os = "windows")]
fn windows_command(exe: &Path, args: &[&str]) -> String {
    std::iter::once(format!("\"{}\"", exe.display()))
        .chain(args.iter().map(|arg| format!("\"{arg}\"")))
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn open_command(elevated: bool, exe: &Path, args: &[&str], keep_open: bool) -> Result<()> {
    let mut parts = Vec::with_capacity(args.len() + 2);
    if elevated {
        parts.push("sudo".to_string());
    }
    parts.push(exe.to_string_lossy().into_owned());
    parts.extend(args.iter().map(|arg| (*arg).to_string()));

    #[cfg(target_os = "linux")]
    {
        open_linux_terminal(&parts, keep_open)
    }
    #[cfg(target_os = "macos")]
    {
        open_macos_terminal(&parts, keep_open)
    }
}

#[cfg(target_os = "linux")]
fn open_linux_terminal(parts: &[String], keep_open: bool) -> Result<()> {
    let script = shell_script(parts, keep_open);
    let candidates: [(&str, Vec<&str>); 5] = [
        ("x-terminal-emulator", vec!["-e", "sh", "-lc", &script]),
        ("gnome-terminal", vec!["--", "sh", "-lc", &script]),
        ("konsole", vec!["-e", "sh", "-lc", &script]),
        ("xfce4-terminal", vec!["-e", &script]),
        ("xterm", vec!["-e", "sh", "-lc", &script]),
    ];

    for (program, args) in candidates {
        if Command::new(program).args(args).spawn().is_ok() {
            return Ok(());
        }
    }

    Err(anyhow!(
        "no supported terminal emulator found (tried x-terminal-emulator, gnome-terminal, konsole, xfce4-terminal, xterm)"
    ))
}

#[cfg(target_os = "macos")]
fn open_macos_terminal(parts: &[String], keep_open: bool) -> Result<()> {
    let script = shell_script(parts, keep_open);
    let script = script.replace('\\', "\\\\").replace('"', "\\\"");
    let apple_script = format!("tell application \"Terminal\" to do script \"{script}\"");

    Command::new("osascript")
        .args(["-e", &apple_script])
        .spawn()
        .context("failed to open macOS Terminal")?;
    Ok(())
}

#[cfg(target_os = "windows")]
fn open_command(elevated: bool, exe: &Path, args: &[&str], keep_open: bool) -> Result<()> {
    let ps_command = powershell_invocation(exe, args);
    let encoded_command = powershell_encoded_command(&ps_command);
    let mut powershell_args = vec!["-NoProfile", "-ExecutionPolicy", "Bypass"];
    if keep_open {
        powershell_args.push("-NoExit");
    }
    powershell_args.push("-EncodedCommand");
    powershell_args.push(&encoded_command);
    let argument_list = powershell_array_literal(&powershell_args);

    if elevated {
        let script = format!(
            "Start-Process -FilePath powershell -Verb RunAs -ArgumentList @({argument_list})"
        );
        let mut command = Command::new("powershell");
        command.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"]);
        command.arg(&script);
        command
            .spawn()
            .context("failed to open elevated PowerShell")?;
    } else {
        let script = format!("Start-Process -FilePath powershell -ArgumentList @({argument_list})");
        let mut command = Command::new("powershell");
        command.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"]);
        command
            .arg(&script)
            .spawn()
            .context("failed to open PowerShell")?;
    }

    Ok(())
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn open_command(_elevated: bool, _exe: &Path, _args: &[&str], _keep_open: bool) -> Result<()> {
    Err(anyhow!("tray commands are not supported on this OS"))
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn shell_script(parts: &[String], keep_open: bool) -> String {
    let command = parts
        .iter()
        .map(|part| shell_quote(part))
        .collect::<Vec<_>>()
        .join(" ");

    if keep_open {
        format!("{command}; echo; printf 'Press Enter to close...'; read _")
    } else {
        command
    }
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

#[cfg(target_os = "windows")]
fn powershell_invocation(exe: &Path, args: &[&str]) -> String {
    let invocation = std::iter::once(exe.to_string_lossy().into_owned())
        .chain(args.iter().map(|arg| (*arg).to_string()))
        .map(|part| powershell_quote(&part))
        .collect::<Vec<_>>()
        .join(" ");
    format!("& {invocation}")
}

#[cfg(target_os = "windows")]
fn powershell_encoded_command(command: &str) -> String {
    let bytes: Vec<u8> = command
        .encode_utf16()
        .flat_map(|unit| unit.to_le_bytes())
        .collect();
    BASE64_STANDARD.encode(bytes)
}

#[cfg(target_os = "windows")]
fn powershell_array_literal(values: &[&str]) -> String {
    values
        .iter()
        .map(|value| powershell_quote(value))
        .collect::<Vec<_>>()
        .join(",")
}

#[cfg(target_os = "windows")]
fn powershell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "''"))
}

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

    #[test]
    fn tray_instance_rejects_a_second_guard() {
        const CHILD_ENV: &str = "WAKEZILLA_TEST_TRAY_INSTANCE_CHILD";

        if let Some(name) = std::env::var_os(CHILD_ENV) {
            let name = name.to_string_lossy();
            assert!(TrayInstanceGuard::acquire_named(&name)
                .expect("child acquire")
                .is_none());
            return;
        }

        let name = format!("dev.wakezilla.tray.test.{}", std::process::id());
        let first = TrayInstanceGuard::acquire_named(&name)
            .expect("first acquire")
            .expect("first instance");

        assert!(TrayInstanceGuard::acquire_named(&name)
            .expect("second acquire")
            .is_none());

        let child = std::process::Command::new(std::env::current_exe().expect("test executable"))
            .args([
                "--exact",
                "tray::desktop::tests::tray_instance_rejects_a_second_guard",
            ])
            .env(CHILD_ENV, &name)
            .status()
            .expect("run child test process");
        assert!(child.success(), "child should observe the held guard");

        drop(first);

        let reacquired = TrayInstanceGuard::acquire_named(&name)
            .expect("acquire after drop")
            .expect("instance after drop");
        drop(reacquired);

        #[cfg(target_os = "macos")]
        std::fs::remove_file(macos_lock_path(&name).expect("test lock path"))
            .expect("remove test lock file");
    }

    #[test]
    fn tray_instance_linux_socket_type_combines_cloexec_atomically() {
        assert_eq!(combine_linux_socket_type(0b0001, 0b1000), 0b1001);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn tray_instance_linux_backend_name_is_scoped_by_euid() {
        let first_user = linux_backend_name(TRAY_INSTANCE_NAME, 1000);
        let second_user = linux_backend_name(TRAY_INSTANCE_NAME, 1001);

        assert_eq!(first_user, "dev.wakezilla.tray.uid-1000");
        assert_ne!(first_user, second_user);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn tray_instance_linux_socket_does_not_survive_exec() {
        use std::io::{BufRead as _, Read as _, Write as _};
        use std::process::{Child, Stdio};

        const CHILD_ENV: &str = "WAKEZILLA_TEST_TRAY_INSTANCE_CLOEXEC_CHILD";
        const READY_MARKER: &str = "WAKEZILLA_TRAY_INSTANCE_CHILD_READY";

        if std::env::var_os(CHILD_ENV).is_some() {
            let mut stdout = std::io::stdout().lock();
            writeln!(stdout, "{READY_MARKER}").expect("write child ready marker");
            stdout.flush().expect("flush child ready marker");
            drop(stdout);

            let mut release = [0_u8; 1];
            std::io::stdin()
                .read_exact(&mut release)
                .expect("wait for parent release");
            return;
        }

        struct ChildGuard(Option<Child>);

        impl ChildGuard {
            fn child_mut(&mut self) -> &mut Child {
                self.0.as_mut().expect("child process")
            }

            fn wait(mut self) -> std::io::Result<std::process::ExitStatus> {
                let result = self.0.as_mut().expect("child process").wait();
                if result.is_ok() {
                    self.0.take();
                }
                result
            }
        }

        impl Drop for ChildGuard {
            fn drop(&mut self) {
                if let Some(mut child) = self.0.take() {
                    let _ = child.kill();
                    let _ = child.wait();
                }
            }
        }

        let name = format!("dev.wakezilla.tray.cloexec.test.{}", std::process::id());
        let first = TrayInstanceGuard::acquire_named(&name)
            .expect("first acquire")
            .expect("first instance");
        let child = std::process::Command::new(std::env::current_exe().expect("test executable"))
            .args([
                "--exact",
                "tray::desktop::tests::tray_instance_linux_socket_does_not_survive_exec",
                "--nocapture",
            ])
            .env(CHILD_ENV, "1")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .expect("spawn child test process");
        let mut child = ChildGuard(Some(child));
        let stdout = child.child_mut().stdout.take().expect("child stdout pipe");
        let mut stdout = std::io::BufReader::new(stdout);
        let mut line = String::new();
        loop {
            line.clear();
            assert_ne!(stdout.read_line(&mut line).expect("read child output"), 0);
            if line.contains(READY_MARKER) {
                break;
            }
        }

        drop(first);
        let reacquired = TrayInstanceGuard::acquire_named(&name)
            .expect("reacquire while child lives")
            .expect("socket fd must close during exec");
        drop(reacquired);

        child
            .child_mut()
            .stdin
            .as_mut()
            .expect("child stdin pipe")
            .write_all(b"x")
            .expect("release child");
        let status = child.wait().expect("wait for child test process");
        assert!(status.success(), "child test process should exit cleanly");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn tray_instance_flock_success_is_acquired() {
        assert_eq!(
            classify_macos_flock_result(0, 0).expect("successful flock"),
            MacosFlockOutcome::Acquired
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn tray_instance_flock_would_block_is_duplicate() {
        assert_eq!(
            classify_macos_flock_result(-1, libc::EWOULDBLOCK).expect("contended flock"),
            MacosFlockOutcome::Contended
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn tray_instance_flock_other_errno_is_error() {
        let error = classify_macos_flock_result(-1, libc::EINVAL)
            .expect_err("unexpected flock errno must fail closed");

        assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_autostart_uses_canonical_bundle_and_native_open_contract() {
        use std::os::unix::fs::PermissionsExt as _;

        let temp = tempfile::tempdir().expect("temporary macOS home parent");
        let home = temp.path().join("Home & <Primary>");
        let executable = home.join("Applications/Wakezilla.app/Contents/MacOS/wakezilla-tray");
        std::fs::create_dir_all(executable.parent().expect("bundle executable parent"))
            .expect("create bundle fixture");
        std::fs::write(&executable, b"tray executable fixture")
            .expect("write bundle executable fixture");

        let installed = install_macos_tray_autostart_at(&home, &executable)
            .expect("install native macOS LaunchAgent");
        let canonical_home = home.canonicalize().expect("canonical fixture HOME");
        assert_eq!(
            installed,
            canonical_home.join("Library/LaunchAgents/dev.wakezilla.tray.plist")
        );
        let bundle = executable
            .parent()
            .and_then(Path::parent)
            .and_then(Path::parent)
            .expect("bundle fixture path")
            .canonicalize()
            .expect("canonical bundle fixture");
        let content = std::fs::read_to_string(&installed).expect("read LaunchAgent");
        for required in [
            "<key>Label</key>",
            "<string>dev.wakezilla.tray</string>",
            "<key>ProgramArguments</key>",
            "<string>/usr/bin/open</string>",
            "<string>-g</string>",
            "<key>RunAtLoad</key>\n<true/>",
            "<key>LimitLoadToSessionType</key>",
            "<string>Aqua</string>",
            "<key>ProcessType</key>",
            "<string>Interactive</string>",
            "<key>AssociatedBundleIdentifiers</key>\n<array>\n<string>dev.wakezilla.Wakezilla</string>\n</array>",
        ] {
            assert!(content.contains(required), "missing contract: {required}");
        }
        assert!(content.contains(
            &xml_escape(bundle.to_str().expect("UTF-8 bundle fixture"))
                .expect("escape bundle path")
        ));
        assert!(!content.contains("KeepAlive"));
        assert!(!content.contains("Terminal"));
        assert!(!content.contains("wakezilla-tray</string>"));
        assert!(!content.contains("/bin/sh"));
        assert_eq!(
            std::fs::metadata(&installed)
                .expect("LaunchAgent metadata")
                .permissions()
                .mode()
                & 0o777,
            0o644
        );
        let lint = std::process::Command::new("/usr/bin/plutil")
            .args(["-lint"])
            .arg(&installed)
            .status()
            .expect("run real plutil against runtime LaunchAgent");
        assert!(
            lint.success(),
            "real plutil must accept runtime LaunchAgent"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_autostart_rejects_nonbundle_and_control_paths_before_publish() {
        let temp = tempfile::tempdir().expect("temporary macOS fixture");
        let home = temp.path().join("home");
        std::fs::create_dir(&home).expect("create fixture HOME");
        let loose_helper = temp.path().join("wakezilla-tray");
        std::fs::write(&loose_helper, b"loose helper").expect("write loose helper");

        assert!(install_macos_tray_autostart_at(&home, &loose_helper).is_err());
        assert!(!home.join("Library").exists());
        assert!(
            install_macos_tray_autostart_at(Path::new("relative-home"), &loose_helper).is_err()
        );
        assert!(xml_escape("bad\npath").is_err());
        assert!(xml_escape("bad\u{1b}path").is_err());
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_autostart_rejects_root_and_wrong_owner_before_publish() {
        let temp = tempfile::tempdir().expect("temporary macOS fixture");
        let home = temp.path().join("home");
        let executable = home.join("Applications/Wakezilla.app/Contents/MacOS/wakezilla-tray");
        std::fs::create_dir_all(executable.parent().expect("bundle executable parent"))
            .expect("create bundle fixture");
        std::fs::write(&executable, b"tray executable fixture")
            .expect("write bundle executable fixture");
        let owner = std::fs::metadata(&home).expect("HOME metadata").uid();

        assert!(install_macos_tray_autostart_for_uid(&home, &executable, 0).is_err());
        assert!(!home.join("Library").exists());
        assert!(install_macos_tray_autostart_for_uid(&home, &executable, owner + 1).is_err());
        assert!(!home.join("Library").exists());
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_autostart_replaces_atomically_and_rejects_symlink_destination() {
        let temp = tempfile::tempdir().expect("temporary macOS fixture");
        let home = temp.path().join("home");
        let executable = home.join("Applications/Wakezilla.app/Contents/MacOS/wakezilla-tray");
        std::fs::create_dir_all(executable.parent().expect("bundle executable parent"))
            .expect("create bundle fixture");
        std::fs::write(&executable, b"tray executable fixture")
            .expect("write bundle executable fixture");
        let launch_agents = home.join("Library/LaunchAgents");
        std::fs::create_dir_all(&launch_agents).expect("create LaunchAgents fixture");
        let destination = launch_agents.join("dev.wakezilla.tray.plist");
        std::fs::write(&destination, b"old contents").expect("write prior LaunchAgent");

        install_macos_tray_autostart_at(&home, &executable)
            .expect("atomically replace LaunchAgent");
        let temporary_count = std::fs::read_dir(&launch_agents)
            .expect("read LaunchAgents")
            .filter_map(Result::ok)
            .filter(|entry| entry.file_name().to_string_lossy().contains(".tmp."))
            .count();
        assert_eq!(temporary_count, 0);

        std::fs::remove_file(&destination).expect("remove installed LaunchAgent");
        let foreign = temp.path().join("foreign-agent");
        std::fs::write(&foreign, b"foreign contents").expect("write foreign agent");
        std::os::unix::fs::symlink(&foreign, &destination)
            .expect("create LaunchAgent symlink fixture");
        assert!(install_macos_tray_autostart_at(&home, &executable).is_err());
        assert_eq!(
            std::fs::read(&foreign).expect("read preserved foreign agent"),
            b"foreign contents"
        );
    }

    #[test]
    fn dashboard_url_uses_proxy_port_from_config() {
        let mut config = config::Config::default();
        config.server.proxy_port = 4567;

        assert_eq!(dashboard_url(&config), "http://127.0.0.1:4567");
    }

    #[test]
    fn mode_labels_match_menu_text() {
        assert_eq!(mode_label(service::Mode::Proxy), "Proxy");
        assert_eq!(mode_label(service::Mode::Client), "Client");
    }

    #[test]
    fn service_status_labels_match_state() {
        assert_eq!(
            service_status_label(ModeStatus {
                installed: false,
                running: false
            }),
            "not installed"
        );
        assert_eq!(
            service_status_label(ModeStatus {
                installed: true,
                running: false
            }),
            "stopped"
        );
        assert_eq!(
            service_status_label(ModeStatus {
                installed: true,
                running: true
            }),
            "running"
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn shell_quote_wraps_single_quotes() {
        assert_eq!(shell_quote("a'b"), "'a'\\''b'");
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn desktop_entry_quote_escapes_quotes() {
        assert_eq!(
            desktop_entry_quote("/tmp/a\"b%20").expect("quote desktop entry"),
            "\"/tmp/a\\\\\"b%%20\""
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn desktop_entry_quote_rejects_ascii_controls() {
        assert!(desktop_entry_quote("/tmp/bad\npath").is_err());
        assert!(desktop_entry_quote("/tmp/bad\u{1b}path").is_err());
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn linux_autostart_is_canonical_atomic_and_removes_owned_legacy() {
        let temp = tempfile::tempdir().expect("temporary config home");
        let helper = temp.path().join("bin with spaces/wakezilla-tray");
        std::fs::create_dir_all(helper.parent().expect("helper parent"))
            .expect("create helper parent");
        std::fs::write(&helper, b"helper").expect("write helper fixture");
        let autostart = temp.path().join("autostart");
        std::fs::create_dir_all(&autostart).expect("create autostart fixture");
        let legacy = autostart.join("wakezilla-tray.desktop");
        std::fs::write(
            &legacy,
            b"[Desktop Entry]\nType=Application\nName=Wakezilla Tray\nExec=/old/wakezilla-tray\n",
        )
        .expect("write owned legacy entry");
        let canonical = autostart.join("dev.wakezilla.tray.desktop");
        std::fs::write(&canonical, b"old canonical contents").expect("write old canonical entry");

        let installed = install_linux_tray_autostart_at(temp.path(), &helper)
            .expect("install canonical Linux autostart");

        assert_eq!(installed, canonical);
        assert!(!legacy.exists(), "owned legacy entry must be removed");
        let content = std::fs::read_to_string(&installed).expect("read canonical entry");
        assert!(content.contains("Name=Wakezilla"));
        assert!(content.contains(&format!("Exec=\"{}\"", helper.display())));
        assert!(!content.contains(" wakezilla tray"));
        assert!(!content.contains("Version=0.1"));
        let temporary_entries = std::fs::read_dir(&autostart)
            .expect("read autostart directory")
            .filter_map(Result::ok)
            .filter(|entry| entry.file_name().to_string_lossy().contains(".tmp."))
            .count();
        assert_eq!(temporary_entries, 0);
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn linux_autostart_preserves_foreign_legacy_named_entry() {
        let temp = tempfile::tempdir().expect("temporary config home");
        let helper = temp.path().join("wakezilla-tray");
        std::fs::write(&helper, b"helper").expect("write helper fixture");
        let autostart = temp.path().join("autostart");
        std::fs::create_dir_all(&autostart).expect("create autostart fixture");
        let legacy = autostart.join("wakezilla-tray.desktop");
        let foreign = "[Other Group]\nName=Wakezilla Tray\nExec=/old/wakezilla-tray\n\
                       [Desktop Entry]\nType=Application\nName=Another App\nExec=/other/app\n";
        std::fs::write(&legacy, foreign).expect("write foreign legacy entry");

        install_linux_tray_autostart_at(temp.path(), &helper)
            .expect("install canonical Linux autostart");

        assert_eq!(
            std::fs::read_to_string(&legacy).expect("read preserved legacy entry"),
            foreign
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn linux_legacy_autostart_matcher_requires_one_exact_owned_group() {
        assert!(linux_legacy_autostart_is_owned(
            "[Desktop Entry]\nType=Application\nName=Wakezilla Tray\nExec=/old/bin/wakezilla-tray\n"
        ));
        assert!(linux_legacy_autostart_is_owned(
            "[Desktop Entry]\nType=Application\nName=Wakezilla\nExec=\"/old/bin/wakezilla\" tray\n"
        ));
        assert!(!linux_legacy_autostart_is_owned(
            "[Desktop Entry]\nType=Application\nName=Wakezilla Tray\nExec=/other/not-wakezilla-tray-helper\n"
        ));
        assert!(!linux_legacy_autostart_is_owned(
            "[Desktop Entry]\nType=Application\nName=Wakezilla Tray\n[Desktop Entry]\nExec=/old/bin/wakezilla-tray\n"
        ));
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn linux_autostart_directory_is_private_without_chmodding_existing_directory() {
        use std::os::unix::fs::PermissionsExt as _;

        let temp = tempfile::tempdir().expect("temporary config home");
        let new_config = temp.path().join("new-config");
        let helper = temp.path().join("wakezilla-tray");
        std::fs::write(&helper, b"helper").expect("write helper fixture");
        install_linux_tray_autostart_at(&new_config, &helper)
            .expect("install into new config home");
        let new_mode = std::fs::metadata(new_config.join("autostart"))
            .expect("new autostart metadata")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(new_mode, 0o700);

        let existing_config = temp.path().join("existing-config");
        let existing_autostart = existing_config.join("autostart");
        std::fs::create_dir_all(&existing_autostart).expect("create existing autostart");
        std::fs::set_permissions(&existing_autostart, std::fs::Permissions::from_mode(0o755))
            .expect("set existing directory mode");
        install_linux_tray_autostart_at(&existing_config, &helper)
            .expect("install into existing config home");
        let existing_mode = std::fs::metadata(&existing_autostart)
            .expect("existing autostart metadata")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(existing_mode, 0o755);
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn linux_config_home_requires_an_absolute_path_with_home_fallback() {
        use std::ffi::OsStr;

        assert_eq!(
            resolve_linux_config_home(Some(OsStr::new("/xdg/config")), Some(OsStr::new("/home/u")))
                .expect("absolute XDG config home"),
            PathBuf::from("/xdg/config")
        );
        for invalid_xdg in ["", "relative/config"] {
            assert_eq!(
                resolve_linux_config_home(
                    Some(OsStr::new(invalid_xdg)),
                    Some(OsStr::new("/home/u"))
                )
                .expect("absolute HOME fallback"),
                PathBuf::from("/home/u/.config")
            );
        }
        assert!(resolve_linux_config_home(None, Some(OsStr::new("relative-home"))).is_err());
        assert!(resolve_linux_config_home(None, None).is_err());
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn linux_autostart_rejects_non_utf8_helper_before_publish() {
        use std::os::unix::ffi::OsStringExt as _;

        let temp = tempfile::tempdir().expect("temporary config home");
        let helper = temp.path().join(std::ffi::OsString::from_vec(vec![
            b'w', b'a', b'k', b'e', b'z', b'i', b'l', b'l', b'a', b'-', 0xff,
        ]));

        assert!(install_linux_tray_autostart_at(temp.path(), &helper).is_err());
        assert!(!temp
            .path()
            .join("autostart/dev.wakezilla.tray.desktop")
            .exists());
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn linux_autostart_preserves_non_utf8_legacy_as_foreign() {
        let temp = tempfile::tempdir().expect("temporary config home");
        let helper = temp.path().join("wakezilla-tray");
        std::fs::write(&helper, b"helper").expect("write helper fixture");
        let autostart = temp.path().join("autostart");
        std::fs::create_dir_all(&autostart).expect("create autostart fixture");
        let legacy = autostart.join("wakezilla-tray.desktop");
        let foreign = b"[Desktop Entry]\nType=Application\nName=Wakezilla Tray\nExec=/old/wakezilla-tray\n\xff";
        std::fs::write(&legacy, foreign).expect("write non-UTF-8 legacy entry");

        let canonical = install_linux_tray_autostart_at(temp.path(), &helper)
            .expect("install with foreign non-UTF-8 legacy");

        assert!(canonical.is_file());
        assert_eq!(
            std::fs::read(&legacy).expect("read preserved legacy"),
            foreign
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn linux_autostart_preserves_unreadable_legacy_as_foreign() {
        use std::os::unix::fs::PermissionsExt as _;

        let temp = tempfile::tempdir().expect("temporary config home");
        let helper = temp.path().join("wakezilla-tray");
        std::fs::write(&helper, b"helper").expect("write helper fixture");
        let autostart = temp.path().join("autostart");
        std::fs::create_dir_all(&autostart).expect("create autostart fixture");
        let legacy = autostart.join("wakezilla-tray.desktop");
        std::fs::write(
            &legacy,
            b"[Desktop Entry]\nType=Application\nName=Wakezilla Tray\nExec=/old/wakezilla-tray\n",
        )
        .expect("write legacy entry");
        std::fs::set_permissions(&legacy, std::fs::Permissions::from_mode(0o000))
            .expect("make legacy unreadable");
        if std::fs::read(&legacy).is_ok() {
            return;
        }

        let canonical = install_linux_tray_autostart_at(temp.path(), &helper)
            .expect("install with unreadable foreign legacy");

        assert!(canonical.is_file());
        assert!(legacy.exists());
    }
}