bootupd 0.4.1

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

use std::cell::RefCell;
use std::os::unix::io::AsRawFd;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};
use bootc_internal_mount::tempmount::TempMount;
use bootc_internal_utils::CommandRunExt;
use camino::{Utf8Path, Utf8PathBuf};
use cap_std::ambient_authority;
use cap_std::fs::Dir;
use cap_std_ext::cap_std;
use cap_std_ext::dirext::CapStdExtDirExt;
use fn_error_context::context;
use os_release::OsRelease;
use rustix::mount::MountFlags;
use rustix::path::Arg;
use rustix::{fd::AsFd, fd::BorrowedFd, fs::StatVfsMountFlags};
use walkdir::WalkDir;

use bootc_internal_blockdev::Device;

use crate::bootloader::{get_bootloader, Bootloader};
use crate::bootupd::{RootContext, Sysroot};
use crate::freezethaw::fsfreeze_thaw_cycle;
use crate::model::*;
use crate::ostreeutil;
use crate::util;
use crate::util::get_metadata_timestamp;
use crate::{component::*, packagesystem::*};
use crate::{filetree, grubconfigs};

/// Well-known paths to the ESP that may have been mounted external to us.
pub(crate) const ESP_MOUNTS: &[&str] = &["boot/efi", "efi", "boot"];

/// New efi dir under usr/lib
const EFILIB: &str = "usr/lib/efi";

/// The binary to change EFI boot ordering
const EFIBOOTMGR: &str = "efibootmgr";
#[cfg(target_arch = "aarch64")]
pub(crate) const SHIM: &str = "shimaa64.efi";

#[cfg(target_arch = "x86_64")]
pub(crate) const SHIM: &str = "shimx64.efi";

#[cfg(target_arch = "riscv64")]
pub(crate) const SHIM: &str = "shimriscv64.efi";

/// The bootloader binary, which every bootloader names grub<arch>.efi
/// because that name is baked into the shim
#[cfg(target_arch = "x86_64")]
pub(crate) const BOOTLOADER_BIN: &str = "grubx64.efi";

#[cfg(target_arch = "aarch64")]
pub(crate) const BOOTLOADER_BIN: &str = "grubaa64.efi";

#[cfg(target_arch = "riscv64")]
pub(crate) const BOOTLOADER_BIN: &str = "grubriscv64.efi";

/// The mount path for uefi
const EFIVARFS: &str = "/sys/firmware/efi/efivars";

/// Systemd boot loader info EFI variable names
const LOADER_INFO_VAR_STR: &str = "LoaderInfo-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f";
const STUB_INFO_VAR_STR: &str = "StubInfo-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f";

/// The options of cp command for installation
const OPTIONS: &[&str] = &["-rp", "--reflink=auto"];

/// Check if the given path is a mount point via statx(MOUNT_ROOT).
fn is_mount_point(path: &Path) -> Result<bool> {
    use rustix::fs::{AtFlags, StatxAttributes, StatxFlags};
    // See https://github.com/coreos/cap-std-ext/blob/5493d689/src/dirext.rs#L514
    // CWD is unused here because callers always pass absolute paths.
    let r = rustix::fs::statx(
        rustix::fs::CWD,
        path,
        AtFlags::NO_AUTOMOUNT | AtFlags::SYMLINK_NOFOLLOW,
        StatxFlags::empty(),
    )?;
    if r.stx_attributes_mask.contains(StatxAttributes::MOUNT_ROOT) {
        Ok(r.stx_attributes.contains(StatxAttributes::MOUNT_ROOT))
    } else {
        anyhow::bail!(
            "could not determine if {path:?} is a mount point (kernel too old for MOUNT_ROOT)"
        )
    }
}

/// Return `true` if the system is booted via EFI
#[context("Checking if system is EFI booted")]
pub(crate) fn is_efi_booted() -> Result<bool> {
    Path::new("/sys/firmware/efi")
        .try_exists()
        .map_err(Into::into)
}

#[derive(Default, Debug)]
pub(crate) struct Efi {
    mountpoint: RefCell<Option<PathBuf>>,
    /// Guard for ESP mounted at a temporary location
    tempmount_guard: RefCell<Option<TempMount>>,
}

/// Mount flags shared by all ESP mounts: non-executable, no setuid.
const ESP_MOUNT_FLAGS: MountFlags =
    MountFlags::from_bits_retain(MountFlags::NOEXEC.bits() | MountFlags::NOSUID.bits());

/// FAT mount options: owner-only permissions on files (0600) and dirs (0700).
const ESP_MOUNT_DATA: &std::ffi::CStr = c"fmask=0177,dmask=0077";

/// Mount the ESP from the provided device into a temporary directory.
pub(crate) fn mount_esp(device: &str) -> Result<TempMount> {
    TempMount::mount_dev(device, "vfat", ESP_MOUNT_FLAGS, Some(ESP_MOUNT_DATA))
}

impl Efi {
    #[context("Searching common ESP mountpoints")]
    fn search_common_esp_mountpoints(&self, root: &Path) -> Result<Option<PathBuf>> {
        for &mnt in ESP_MOUNTS.iter() {
            let path = root.join(mnt);
            if !path.exists() {
                continue;
            }

            let st = rustix::fs::statfs(&path)?;
            if st.f_type == libc::MSDOS_SUPER_MAGIC {
                // Verify this is actually a mount point, not just a subdirectory
                // on a vfat filesystem. Compare device IDs: a mount point has a
                // different device than its parent. Without this check, a vfat
                // subdirectory (e.g. /boot/efi on a vfat /boot) could be
                // misidentified as a mounted ESP.
                if !is_mount_point(&path)? {
                    // Same device as parent - this is a subdirectory, not a mount point
                    log::debug!("Skipping {path:?}: vfat but not a mount point");
                    continue;
                }
                util::ensure_writable_mount(&path)?;
                return Ok(Some(path));
            }
        }

        Ok(None)
    }

    /// Get mounted point for ESP
    /// NOTE: This function only searches the common ESP mountpoints and returns
    /// the path of the mountpoint, if there is one
    #[context("Getting mounted ESP")]
    pub(crate) fn get_mounted_esp(&self, root: &Path) -> Result<Option<PathBuf>> {
        let Some(mnt) = self.search_common_esp_mountpoints(root)? else {
            return Ok(None);
        };

        // Only borrow mutably if we found a mount point
        log::debug!("Reusing existing mount point {mnt:?}");
        *self.mountpoint.borrow_mut() = Some(mnt.clone());
        Ok(Some(mnt))
    }

    /// Mount the passed esp_device, return mount point
    #[context("Mounting ESP device at {}", root.display())]
    pub(crate) fn mount_esp_device(&self, root: &Path, esp_device: &Path) -> Result<PathBuf> {
        match self.search_common_esp_mountpoints(root)? {
            Some(mnt) => {
                log::debug!("Mounted at {:?}", mnt);
                *self.mountpoint.borrow_mut() = Some(mnt.clone());
                Ok(mnt)
            }
            None => {
                // If the ESP isn't already mounted at /boot, /boot/efi mount it at a temporary point
                // This is so that we don't shadow existing files in the above directories
                let esp_mount = mount_esp(
                    esp_device
                        .as_str()
                        .context("Converting esp_device path to str")?,
                )
                .context("Creating temp ESP mount")?;

                let mnt_path = esp_mount.dir.path().to_path_buf();
                *self.mountpoint.borrow_mut() = Some(mnt_path.clone());
                *self.tempmount_guard.borrow_mut() = Some(esp_mount);

                Ok(mnt_path)
            }
        }
    }

    /// Returns the ESP's mountpoint if present
    pub(crate) fn get_esp_mountpoint(&self) -> std::cell::Ref<'_, Option<PathBuf>> {
        self.mountpoint.borrow()
    }

    /// Checks if we have already mounted the ESP
    /// If not, checks if the ESP is mounted at common mountpoints, i.e. /boot, /boot/efi
    /// Else, mounts the ESP at a temp path
    #[context("Ensuring mounted ESP")]
    pub(crate) fn ensure_mounted_esp(&self, root: &Path, esp_device: &Path) -> Result<PathBuf> {
        if let Some(mountpoint) = self.mountpoint.borrow().as_deref() {
            return Ok(mountpoint.to_owned());
        }
        let destdir = if let Some(destdir) = self.get_mounted_esp(Path::new(root))? {
            destdir
        } else {
            self.mount_esp_device(root, esp_device)?
        };
        Ok(destdir)
    }

    pub(crate) fn unmount(&self) -> Result<()> {
        if let Some(tmpmount) = self.tempmount_guard.borrow_mut().take() {
            drop(tmpmount);
            log::trace!("Dropped tempmount");
        }

        *self.mountpoint.borrow_mut() = None;

        Ok(())
    }

    #[context("Updating EFI firmware variables")]
    fn update_firmware(&self, device: &Device, espdir: &Dir, vendordir: &str) -> Result<()> {
        if !is_efi_booted()? {
            log::debug!("Not booted via EFI, skipping firmware update");
            return Ok(());
        }
        let sysroot = Dir::open_ambient_dir("/", cap_std::ambient_authority())?;
        let efi = sysroot
            .open_dir(EFIVARFS.strip_prefix("/").unwrap())
            .context("Opening efivars dir")?;
        let st = rustix::fs::fstatvfs(efi.as_fd())?;
        // Do nothing if efivars is readonly or empty
        // See https://github.com/coreos/bootupd/issues/972
        if st.f_flag.contains(StatVfsMountFlags::RDONLY)
            || std::fs::read_dir(EFIVARFS)?.next().is_none()
        {
            log::info!("Skipped EFI variables update: efivars not writable or empty");
            return Ok(());
        }

        // Check shim exists and return earlier if not
        let shim_path = format!("EFI/{vendordir}/{SHIM}");
        if !espdir.exists(&shim_path) {
            anyhow::bail!("Failed to find {shim_path}");
        }
        let loader = format!("\\EFI\\{vendordir}\\{SHIM}");

        let product_name = get_product_name(&sysroot)?;
        log::debug!("Get product name: '{product_name}'");
        assert!(product_name.len() > 0);

        // Multi-device is handled by the caller: Efi::install() is called once
        // per device in the loop at bootupd.rs install(), so each device's ESP
        // gets its firmware updated individually.
        let esp_part_num = device.get_esp_partition_number()?;

        // clear all the boot entries that match the target name
        clear_efi_target(&product_name)?;
        let device_path = device.path();
        create_efi_boot_entry(&device_path, esp_part_num.trim(), &loader, &product_name)
    }

    /// Returns the [`Dir`] containing the EFI update payload.
    fn get_update_payload_dir(&self, sysroot: Sysroot<'_>) -> Result<Dir> {
        let rel_path = if payload_in_usr_lib_efi(sysroot.path)?
            && get_efi_component_from_usr(sysroot.path, EFILIB, None)?.is_some()
        {
            PathBuf::from(EFILIB)
        } else {
            // Legacy fallback
            component_updatedirname(self)
        };
        sysroot
            .dir
            .open_dir(&rel_path)
            .with_context(|| format!("opening update dir {}", rel_path.display()))
    }

    /// Errors unless the update payload in `src_root` carries `bootloader`
    /// once, which `install` checks before touching the ESP.
    #[context("Cannot install bootloader '{bootloader}'")]
    fn ensure_carried(&self, src_root: &Utf8Path, bootloader: Bootloader) -> Result<()> {
        let carried = carried_bootloaders(src_root)?;
        let Some((_, versions)) = carried.iter().find(|(b, _)| *b == bootloader) else {
            let carried = carried.iter().map(|(b, _)| *b).collect::<Vec<_>>();
            let carried = if carried.is_empty() {
                "no bootloader".to_string()
            } else {
                format!("only {}", bootloader_names(&carried))
            };
            if payload_in_usr_lib_efi(src_root)? {
                anyhow::bail!(
                    "{EFILIB} has no '{}' component holding {BOOTLOADER_BIN}; the update payload carries {carried}",
                    bootloader.efi_component_name()
                );
            }
            // `install` would copy the legacy update directory as a whole,
            // whichever bootloader was requested, but it only carries GRUB.
            anyhow::bail!(
                "the update payload in {} carries {carried}",
                payload_location(src_root)?.display()
            );
        };
        ensure_one_version(bootloader, versions)
    }

    /// Errors unless the update payload in `src_root` has exactly one shim
    /// binary. After copying the payload, `install` takes the EFI vendor
    /// directory from it, so it checks this before touching the ESP.
    ///
    /// Unlike the later vendor lookups, this fails on a payload directory that
    /// cannot be read, since one could hide a shim.
    fn ensure_shim(&self, src_root: &Utf8Path) -> Result<()> {
        ensure_single_shim(self.find_shims(src_root.as_std_path(), false)?)?;
        Ok(())
    }

    /// The shim binaries in the EFI update payload under `sysroot`, in
    /// `usr/lib/efi`, or else in the legacy update directory, or else, as a
    /// last resort, anywhere in `sysroot`. A directory that cannot be read
    /// fails this, unless `skip_unreadable`. See [`ensure_single_shim`].
    #[context("Looking for {SHIM} in {}", sysroot.display())]
    fn find_shims(&self, sysroot: &Path, skip_unreadable: bool) -> Result<Vec<PathBuf>> {
        let efi_lib = sysroot.join(EFILIB);
        let updates = sysroot.join(component_updatedirname(self));

        let paths: [&Path; 3] = [&efi_lib, &updates, sysroot];
        let target = paths
            .into_iter()
            .find(|p| p.exists())
            .ok_or_else(|| anyhow::anyhow!("Failed to find valid target path"))?;
        find_file_recursive(target, SHIM, skip_unreadable)
    }
}

/// Errors when more than one of the `versions` of `bootloader`'s component in
/// `usr/lib/efi` holds its binary, as [`carried_bootloaders`] lists them:
/// `install` would copy them over one another, in no particular order.
fn ensure_one_version(bootloader: Bootloader, versions: &[String]) -> Result<()> {
    if versions.len() > 1 {
        let mut versions = versions.to_vec();
        versions.sort();
        anyhow::bail!(
            "{EFILIB} has several versions of its '{}' component: {}",
            bootloader.efi_component_name(),
            versions.join(", ")
        );
    }
    Ok(())
}

/// The one shim binary in `shims`, as [`Efi::find_shims`] finds them.
/// Errors without exactly one, naming those it found.
fn ensure_single_shim(mut shims: Vec<PathBuf>) -> Result<PathBuf> {
    // Does not support multiple shim for efi
    if shims.len() > 1 {
        shims.sort();
        let found = shims
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join(", ");
        anyhow::bail!("Found multiple {SHIM} in the image: {found}");
    }
    shims
        .pop()
        .ok_or_else(|| anyhow::anyhow!("Failed to find {SHIM} in the image"))
}

/// The EFI vendor directory of `shim`, the directory it is in
fn efi_vendor(shim: &Path) -> Result<String> {
    let vendor = shim
        .parent()
        .and_then(Path::file_name)
        .ok_or_else(|| anyhow::anyhow!("No file name found"))?;
    Ok(vendor.to_string_lossy().into_owned())
}

/// Helper function to remove ".release.*" from the contents of etc/system-release, leaving just the name
fn get_system_name(contents: impl AsRef<str>) -> String {
    let contents = contents.as_ref();
    match contents.find("release") {
        Some(index) => contents[..index].trim().to_owned(),
        None => contents.trim().to_owned(),
    }
}

#[context("Get product name")]
fn get_product_name(sysroot: &Dir) -> Result<String> {
    let release_path = "etc/system-release";
    if sysroot.exists(release_path) {
        let contents = sysroot.read_to_string(release_path)?;
        return Ok(get_system_name(contents));
    }
    // Read /etc/os-release
    let release: OsRelease = OsRelease::new()?;
    Ok(release.name)
}

/// Convert a nul-terminated UTF-16 byte array to a String.
fn string_from_utf16_bytes(slice: &[u8]) -> String {
    // For some reason, systemd appends 3 nul bytes after the string.
    // Drop the last byte if there's an odd number.
    let size = slice.len() / 2;
    let v: Vec<u16> = (0..size)
        .map(|i| u16::from_ne_bytes([slice[2 * i], slice[2 * i + 1]]))
        .collect();
    let end = v.iter().position(|&c| c == 0).unwrap_or(v.len());
    String::from_utf16_lossy(&v[..end])
}

/// Read a nul-terminated UTF-16 string from an EFI variable.
fn read_efi_var_utf16_string(name: &str) -> Option<String> {
    let efivars = Path::new(EFIVARFS);
    if !efivars.exists() {
        log::trace!("No efivars mount at {:?}", efivars);
        return None;
    }
    let path = efivars.join(name);
    if !path.exists() {
        log::trace!("No EFI variable {name}");
        return None;
    }
    match std::fs::read(&path) {
        Ok(buf) => {
            // Skip the first 4 bytes, those are the EFI variable attributes.
            if buf.len() < 4 {
                log::warn!("Read less than 4 bytes from {:?}", path);
                return None;
            }
            Some(string_from_utf16_bytes(&buf[4..]))
        }
        Err(reason) => {
            log::warn!("Failed reading {:?}: {reason}", path);
            None
        }
    }
}

/// Read the LoaderInfo EFI variable if it exists.
pub(crate) fn get_loader_info() -> Option<String> {
    read_efi_var_utf16_string(LOADER_INFO_VAR_STR)
}

/// Read the StubInfo EFI variable if it exists.
fn get_stub_info() -> Option<String> {
    read_efi_var_utf16_string(STUB_INFO_VAR_STR)
}

/// Whether to skip adoption if a systemd bootloader is found.
fn skip_systemd_bootloaders() -> bool {
    if let Some(loader_info) = get_loader_info() {
        if loader_info.starts_with("systemd") {
            log::trace!("Skipping adoption for {:?}", loader_info);
            return true;
        }
    }
    if let Some(stub_info) = get_stub_info() {
        log::trace!("Skipping adoption for {:?}", stub_info);
        return true;
    }
    false
}

impl Component for Efi {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn name(&self) -> &'static str {
        self.component_type().into()
    }

    fn component_type(&self) -> ComponentType {
        ComponentType::Efi
    }

    fn is_bootloader_supported(&self, bootloader: Bootloader) -> bool {
        #[cfg(not(efi_arch))]
        return matches!(bootloader, Bootloader::Grub);

        #[cfg(efi_arch)]
        matches!(
            bootloader,
            Bootloader::Grub | Bootloader::GrubCC | Bootloader::Systemd
        )
    }

    fn query_adopt(&self, devices: &Option<Vec<Device>>) -> Result<Option<Adoptable>> {
        if devices.is_none() {
            log::trace!("No ESP detected");
            return Ok(None);
        };

        // Don't adopt if the system is booted with systemd-boot or
        // systemd-stub since those will be managed with bootctl.
        if skip_systemd_bootloaders() {
            return Ok(None);
        }
        crate::component::query_adopt_state()
    }

    // Backup "/boot/efi/EFI/{vendor}/grub.cfg" to "/boot/efi/EFI/{vendor}/grub.cfg.bak"
    // Replace "/boot/efi/EFI/{vendor}/grub.cfg" with new static "grub.cfg"
    fn migrate_static_grub_config(&self, sysroot_path: &str, dest_efi_dir: &Dir) -> Result<()> {
        let sysroot = Dir::open_ambient_dir(sysroot_path, ambient_authority())
            .with_context(|| format!("Opening {sysroot_path}"))?;
        let Some(vendor) = self.get_efi_vendor(&Path::new(sysroot_path))? else {
            anyhow::bail!("Failed to find efi vendor");
        };

        // destdir is /boot/efi/EFI
        let efidir = dest_efi_dir
            .open_dir(&vendor)
            .with_context(|| format!("Opening EFI/{}", vendor))?;

        if !efidir.exists(grubconfigs::GRUBCONFIG_BACKUP) {
            println!("Creating a backup of the current GRUB config on EFI");
            efidir
                .copy(
                    grubconfigs::GRUBCONFIG,
                    &efidir,
                    grubconfigs::GRUBCONFIG_BACKUP,
                )
                .context("Failed to backup GRUB config")?;
        }

        grubconfigs::install(&sysroot, None, Some(&vendor), true, Some(&efidir))?;
        // Synchronize the filesystem containing /boot/efi/EFI/{vendor} to disk.
        fsfreeze_thaw_cycle(efidir.reopen_as_ownedfd()?)?;

        Ok(())
    }

    /// Given an adoptable system and an update, perform the update.
    fn adopt_update(
        &self,
        rootcxt: &RootContext,
        updatemeta: &ContentMetadata,
        with_static_config: bool,
        bootloader: Bootloader,
    ) -> Result<Option<InstalledContent>> {
        let esp_devices = rootcxt.device.find_colocated_esps()?;
        let Some(meta) = self.query_adopt(&esp_devices)? else {
            return Ok(None);
        };

        ensure_boot_components(&rootcxt.path, bootloader, false)?;

        let updated = self.get_update_payload_dir(rootcxt.as_sysroot())?;
        let updatef = filetree::FileTree::new_from_dir(&updated, Some(bootloader.dirs_to_skip()))
            .context("reading update dir")?;

        let esp_devices = esp_devices.unwrap_or_default();
        for esp in esp_devices {
            let destpath =
                &self.ensure_mounted_esp(rootcxt.path.as_ref(), Path::new(&esp.path()))?;

            let efidir = Dir::open_ambient_dir(&destpath.join("EFI"), ambient_authority())
                .context("opening EFI dir")?;
            validate_esp_fstype(&efidir)?;

            // For adoption, we should only touch files that we know about.
            let diff = updatef.relative_diff_to(&efidir)?;
            log::trace!("applying adoption diff: {}", &diff);
            filetree::apply_diff(&updated, &efidir, &diff, None)
                .context("applying filesystem changes")?;

            // Backup current config and install static config
            if with_static_config {
                // Install the static config if the OSTree bootloader is not set.
                if let Some(bootloader) = crate::ostreeutil::get_ostree_bootloader()? {
                    println!(
                        "ostree repo 'sysroot.bootloader' config option is currently set to: '{bootloader}'",
                    );
                } else {
                    println!("ostree repo 'sysroot.bootloader' config option is not set yet");
                    self.migrate_static_grub_config(rootcxt.path.as_str(), &efidir)?;
                };
            }

            // Do the sync before unmount
            fsfreeze_thaw_cycle(efidir.reopen_as_ownedfd()?)?;
            drop(efidir);
            self.unmount().context("unmount after adopt")?;
        }
        Ok(Some(InstalledContent {
            meta: updatemeta.clone(),
            filetree: Some(updatef),
            adopted_from: Some(meta.version),
        }))
    }

    /// Refuses a payload without the bootloader, or without exactly one shim.
    fn check_payload(&self, src_root: &str, bootloader: Bootloader) -> Result<()> {
        let src_root = Utf8Path::new(src_root);
        self.ensure_carried(src_root, bootloader)?;
        self.ensure_shim(src_root)
    }

    fn install(
        &self,
        src_root: &str,
        dest_root: &str,
        device: Option<&Device>,
        update_firmware: bool,
        bootloader: Bootloader,
    ) -> Result<InstalledContent> {
        let src_dir = Dir::open_ambient_dir(src_root, ambient_authority())
            .with_context(|| format!("opening source directory {src_root}"))?;
        let Some(meta) = self.get_component_update(&src_dir, Some(bootloader))? else {
            anyhow::bail!("No update metadata for component {} found", self.name());
        };
        log::debug!("Found metadata {}", meta.version);

        // `install` checked this before installing any component, but this
        // can be called directly too.
        self.check_payload(src_root, bootloader)?;

        // Determine the destination path for the ESP.
        // If a device is provided, find and mount its ESP partition (unmounting
        // any previously mounted ESP first to target the correct device).
        // If no device is provided, fall back to an already-mounted ESP.
        let destpath = if let Some(dev) = device {
            // Unmount any previously mounted ESP to ensure we install to the
            // correct device. This is important for multi-device installs where
            // each device has its own ESP.
            self.unmount()?;

            let esp_device = dev
                .find_partition_of_esp()
                .with_context(|| format!("Failed to find ESP device on {}", dev.path()))?;
            self.mount_esp_device(Path::new(dest_root), Path::new(&esp_device.path()))?
        } else if let Some(destdir) = self.get_mounted_esp(Path::new(dest_root))? {
            destdir
        } else {
            anyhow::bail!("No device specified and no mounted ESP found");
        };

        let destd = &Dir::open_ambient_dir(&destpath, ambient_authority())
            .with_context(|| format!("opening dest dir {}", destpath.display()))?;
        validate_esp_fstype(destd)?;

        let src_path = Utf8Path::new(src_root);
        let efi_comps = if payload_in_usr_lib_efi(src_path)? {
            get_efi_component_from_usr(src_path, EFILIB, Some(bootloader))?
        } else {
            None
        };
        let dest = destpath.to_str().with_context(|| {
            format!(
                "Include invalid UTF-8 characters in dest {}",
                destpath.display()
            )
        })?;

        let efi_path = if let Some(efi_components) = efi_comps {
            for efi in efi_components {
                filetree::copy_dir_with_args(&src_dir, efi.path.as_str(), dest, OPTIONS)?;
            }
            EFILIB
        } else {
            let updates = component_updatedirname(self);
            let src = updates
                .to_str()
                .context("Include invalid UTF-8 characters in path")?;
            filetree::copy_dir_with_args(&src_dir, src, dest, OPTIONS)?;
            &src.to_owned()
        };

        // Now that we have multiple bootloaders (all named grubx64.efi/grubaa64.efi
        // due to that name being baked into the shim), we can't blindly use the key
        // "fedora/grubx64.efi" to refer to the installed bootloader, hence we ask for
        // any extra bootloaders to not be included in the FileTree
        let dirs_to_skip = bootloader.dirs_to_skip();

        // Get filetree from efi path
        let ft = crate::filetree::FileTree::new_from_dir(
            &src_dir.open_dir(efi_path)?,
            Some(dirs_to_skip),
        )?;

        if update_firmware {
            if let Some(dev) = device {
                if let Some(vendordir) =
                    self.get_efi_vendor(src_path.join(efi_path).as_std_path())?
                {
                    self.update_firmware(dev, destd, &vendordir)?
                }
            }
        }
        Ok(InstalledContent {
            meta,
            filetree: Some(ft),
            adopted_from: None,
        })
    }

    fn run_update(
        &self,
        rootcxt: &RootContext,
        current: &InstalledContent,
    ) -> Result<InstalledContent> {
        let bootloader = get_bootloader()?;

        let currentf = current
            .filetree
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("No filetree for installed EFI found!"))?;

        // Whether the installed content includes the shim binary.
        let boots_via_shim = currentf
            .children
            .keys()
            .any(|p| Utf8Path::new(p).file_name() == Some(SHIM));

        // Refuse a payload which does not carry the components the system
        // boots from, since it cannot re-provide them.
        ensure_boot_components(&rootcxt.path, bootloader, boots_via_shim)?;

        let sysroot_dir = &rootcxt.sysroot;
        let updatemeta = self
            .query_update(sysroot_dir, bootloader)?
            .expect("update available");
        let updated = self.get_update_payload_dir(rootcxt.as_sysroot())?;

        let dirs_to_skip = bootloader.dirs_to_skip();

        let updatef = filetree::FileTree::new_from_dir(&updated, Some(dirs_to_skip))
            .context("reading update dir")?;
        let diff = currentf.diff(&updatef)?;

        ensure_boot_binaries(currentf, &updatef, boots_via_shim)?;

        let Some(esp_devices) = rootcxt.device.find_colocated_esps()? else {
            anyhow::bail!("Failed to find all esp devices");
        };

        for esp in esp_devices {
            let destpath =
                &self.ensure_mounted_esp(rootcxt.path.as_ref(), Path::new(&esp.path()))?;
            let destdir = Dir::open_ambient_dir(&destpath.join("EFI"), ambient_authority())
                .context("opening EFI dir")?;
            validate_esp_fstype(&destdir)?;
            log::trace!("applying diff: {}", &diff);
            filetree::apply_diff(&updated, &destdir, &diff, None)
                .context("applying filesystem changes")?;

            // Do the sync before unmount
            fsfreeze_thaw_cycle(destdir.reopen_as_ownedfd()?)?;
            drop(destdir);
            self.unmount().context("unmount after update")?;
        }

        let adopted_from = None;
        Ok(InstalledContent {
            meta: updatemeta,
            filetree: Some(updatef),
            adopted_from,
        })
    }

    fn generate_update_metadata(&self, sysroot: &str) -> Result<Option<ContentMetadata>> {
        let sysroot_path = Utf8Path::new(sysroot);
        let sysroot_dir = Dir::open_ambient_dir(sysroot_path, cap_std::ambient_authority())?;

        let ostreeboot = sysroot_dir
            .open_dir_optional(ostreeutil::BOOT_PREFIX)
            .context("Opening usr/lib/ostree-boot")?;

        // Newer images >= F44 have boot entries in /usr/lib/efi, but older images
        // have them in /usr/lib/ostree-boot, which we move to /usr/lib/bootupd/updates/EFI
        let metadata = if payload_in_usr_lib_efi(sysroot_path)? {
            println!("Generating metadata from {EFILIB}");
            generate_meta_from_usr_efi(sysroot_path)?
        } else {
            match &ostreeboot {
                Some(..) => {
                    println!(
                        "Moving {}/efi/EFI to {BOOTUPD_UPDATES_DIR}/EFI",
                        ostreeutil::BOOT_PREFIX
                    );
                    // Transfer usr/lib/ostree-boot/EFI files to usr/lib/bootupd/updates/EFI
                    transfer_ostree_boot_to_bootupd_updates(sysroot_path, self)?
                }

                // If /usr/lib/ostree-boot doesn't exist, assume /usr/lib/efi will
                None => anyhow::bail!("/usr/lib/ostree-boot and /usr/lib/efi not found"),
            }
        };

        if let Some(ostreeboot) = ostreeboot {
            let cruft = ["loader", "grub2"];
            for p in cruft.iter() {
                println!("Removing {p} from {}", ostreeutil::BOOT_PREFIX);
                ostreeboot.remove_all_optional(p)?;
            }

            println!("Removing efi/EFI from {}", ostreeutil::BOOT_PREFIX);
            // Remove usr/lib/ostree-boot/efi/EFI dir (after transfer) or if it is empty
            ostreeboot.remove_all_optional("efi/EFI")?;
        };

        write_update_metadata(
            sysroot_path.as_str(),
            self.component_update_data_name(),
            &metadata,
        )?;

        Ok(Some(metadata))
    }

    fn query_update(
        &self,
        sysroot: &Dir,
        bootloader: Bootloader,
    ) -> Result<Option<ContentMetadata>> {
        self.get_component_update(sysroot, Some(bootloader))
    }

    fn query_requires_update(&self, _sysroot: &Dir) -> Result<()> {
        // Failed as expected if booted with EFI and no update metadata
        if is_efi_booted()? {
            anyhow::bail!("Failed to find EFI update metadata");
        }
        Ok(())
    }

    fn validate(&self, current: &InstalledContent, device: &Device) -> Result<ValidationResult> {
        let esp_devices = device.find_colocated_esps()?;
        if !is_efi_booted()? && esp_devices.is_none() {
            return Ok(ValidationResult::Skip);
        }
        let currentf = current
            .filetree
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("No filetree for installed EFI found!"))?;

        let mut errs = Vec::new();
        let esp_devices = esp_devices.unwrap_or_default();
        for esp in esp_devices.iter() {
            let destpath = &self.ensure_mounted_esp(Path::new("/"), Path::new(&esp.path()))?;

            let efidir = Dir::open_ambient_dir(&destpath.join("EFI"), ambient_authority())
                .with_context(|| format!("opening EFI dir {}", destpath.display()))?;
            let diff = currentf.relative_diff_to(&efidir)?;

            for f in diff.changes.iter() {
                errs.push(format!("Changed: {}", f));
            }
            for f in diff.removals.iter() {
                errs.push(format!("Removed: {}", f));
            }
            assert_eq!(diff.additions.len(), 0);
            drop(efidir);
            self.unmount().context("unmount after validate")?;
        }

        if !errs.is_empty() {
            Ok(ValidationResult::Errors(errs))
        } else {
            Ok(ValidationResult::Valid)
        }
    }

    fn get_efi_vendor(&self, sysroot: &Path) -> Result<Option<String>> {
        // Callers look the vendor up after writing to the ESP, so keep
        // skipping unreadable directories as before. Efi::ensure_shim checks
        // them up front.
        let shims = self.find_shims(sysroot, true)?;
        let shim = ensure_single_shim(shims)?;
        efi_vendor(&shim).map(Some)
    }

    fn has_changed_content(
        &self,
        sysroot: Sysroot<'_>,
        current: &InstalledContent,
        bootloader: Bootloader,
    ) -> Result<bool> {
        let update_dir = self.get_update_payload_dir(sysroot)?;
        let dirs_to_skip = bootloader.dirs_to_skip();
        let updated = filetree::FileTree::new_from_dir(&update_dir, Some(dirs_to_skip))
            .context("reading update dir")?;

        // Every EFI install records a filetree, so a missing one means the
        // saved state is corrupt. Error here rather than promising an update
        // that run_update() cannot perform without a filetree to diff against.
        let currentf = current
            .filetree
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("No filetree for installed EFI found!"))?;
        Ok(!currentf.is_content_eq(&updated))
    }
}

impl Drop for Efi {
    fn drop(&mut self) {
        log::debug!("Unmounting {:?}", self.mountpoint);
        let _ = self.unmount();
    }
}

fn validate_esp_fstype(dir: &Dir) -> Result<()> {
    let dir = unsafe { BorrowedFd::borrow_raw(dir.as_raw_fd()) };
    let stat = rustix::fs::fstatfs(&dir)?;
    if stat.f_type != libc::MSDOS_SUPER_MAGIC {
        bail!(
            "EFI mount is not a msdos filesystem, but is {:?}",
            stat.f_type
        );
    };
    Ok(())
}

#[derive(Debug, PartialEq)]
struct BootEntry {
    id: String,
    name: String,
}

/// Parse boot entries from efibootmgr output
fn parse_boot_entries(output: &str) -> Vec<BootEntry> {
    let mut entries = Vec::new();

    for line in output.lines().filter_map(|line| line.strip_prefix("Boot")) {
        // Need to consider if output only has "Boot0000* UiApp", without additional info
        if line.starts_with('0') {
            let parts = if let Some((parts, _)) = line.split_once('\t') {
                parts
            } else {
                line
            };
            if let Some((id, name)) = parts.split_once(' ') {
                let id = id.trim_end_matches('*').to_string();
                let name = name.trim().to_string();
                entries.push(BootEntry { id, name });
            }
        }
    }
    entries
}

#[context("Clearing EFI boot entries that match target {target}")]
pub(crate) fn clear_efi_target(target: &str) -> Result<()> {
    let target = target.to_lowercase();
    let output = Command::new(EFIBOOTMGR).output()?;
    if !output.status.success() {
        anyhow::bail!("Failed to invoke {EFIBOOTMGR}")
    }

    let output = String::from_utf8(output.stdout)?;
    let boot_entries = parse_boot_entries(&output);
    for entry in boot_entries {
        if entry.name.to_lowercase() == target {
            log::debug!("Deleting matched target {:?}", entry);
            let mut cmd = Command::new(EFIBOOTMGR);
            cmd.args(["-b", entry.id.as_str(), "-B"]);
            println!("Executing: {cmd:?}");
            cmd.run_inherited_with_cmd_context()?;
        }
    }

    anyhow::Ok(())
}

#[context("Adding new EFI boot entry")]
pub(crate) fn create_efi_boot_entry(
    device: &str,
    esp_partition_number: &str,
    loader: &str,
    target: &str,
) -> Result<()> {
    log::debug!("Creating new EFI boot entry using '{target}'");
    let mut cmd = Command::new(EFIBOOTMGR);
    cmd.args([
        "--create",
        "--disk",
        device,
        "--part",
        esp_partition_number,
        "--loader",
        loader,
        "--label",
        target,
    ]);
    println!("Executing: {cmd:?}");
    cmd.run_inherited_with_cmd_context()
}

/// Whether `dir`, or a directory below it, holds a file named `name`. A
/// directory that cannot be read fails this, while a missing `dir` holds
/// nothing.
#[context("Looking for {name} in {}", dir.display())]
fn holds_file(dir: &Path, name: &str) -> Result<bool> {
    for entry in WalkDir::new(dir) {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) if is_missing_root(&e) => return Ok(false),
            Err(e) => return Err(walk_error(e, dir)),
        };
        if entry.file_type().is_file() && entry.file_name() == name {
            return Ok(true);
        }
    }
    Ok(false)
}

/// The files named `target_file` in `dir` and the directories below it. A
/// directory that cannot be read fails this, unless `skip_unreadable`.
#[context("Find target file recursively")]
fn find_file_recursive<P: AsRef<Path>>(
    dir: P,
    target_file: &str,
    skip_unreadable: bool,
) -> Result<Vec<PathBuf>> {
    let dir = dir.as_ref();
    let mut result = Vec::new();

    for entry in WalkDir::new(dir) {
        let entry = match entry {
            Ok(entry) => entry,
            Err(_) if skip_unreadable => continue,
            Err(e) => return Err(walk_error(e, dir)),
        };
        if entry.file_type().is_file() {
            if let Some(file_name) = entry.file_name().to_str() {
                if file_name == target_file {
                    if let Some(path) = entry.path().to_str() {
                        result.push(path.into());
                    }
                }
            }
        }
    }

    Ok(result)
}

#[context("Generating metadata from usr/lib/efi")]
fn generate_meta_from_usr_efi(sysroot_path: &Utf8Path) -> Result<ContentMetadata> {
    // We DO NOT want to filter while generating metadata
    // We want to have metadata for multiple bootloaders
    // Later on, while installing, we'll filter out the stuff we don't need
    let Some(efi_components) = get_efi_component_from_usr(sysroot_path, EFILIB, None)? else {
        anyhow::bail!("Failed to find EFI components");
    };

    let mut packages = Vec::new();
    let mut modules_vec: Vec<Module> = vec![];
    for efi in efi_components {
        packages.push(format!("{} {}", efi.name, efi.version));
        modules_vec.push(Module {
            name: efi.name,
            evr: efi.version,
        });
    }
    modules_vec.sort_unstable();

    let meta = ContentMetadata {
        timestamp: get_metadata_timestamp()?,
        version: packages.join(","),
        versions: Some(modules_vec),
        #[cfg(efi_arch)]
        default_bootloader: None,
    };

    Ok(meta)
}

/// Whether a walk failed because the directory it started from is missing.
fn is_missing_root(error: &walkdir::Error) -> bool {
    error.depth() == 0
        && error
            .io_error()
            .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound)
}

/// Turns a walkdir error into one naming the directory that could not be read.
/// walkdir's message names it, except when reading a directory's entries
/// fails; then this can only say it is below `start`. The message already
/// includes the cause, so the cause is not kept as a separate source.
fn walk_error(error: walkdir::Error, start: &Path) -> anyhow::Error {
    if error.path().is_some() {
        anyhow::anyhow!("{error}")
    } else {
        anyhow::anyhow!("Reading a directory below {}: {error}", start.display())
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct EFIComponent {
    pub name: String,
    pub version: String,
    path: Utf8PathBuf,
}

/// Get EFIComponents from e.g. usr/lib/efi, like "usr/lib/efi/<name>/<version>/EFI"
/// Filter the components by Bootloader, if Bootloader is None, no filtering is performed
///
/// Errors if a Bootloader is requested but no component provides it. Install
/// refuses such a payload before touching the ESP already, in `Efi::ensure_carried`.
fn get_efi_component_from_usr<'a>(
    sysroot: &'a Utf8Path,
    usr_path: &'a str,
    bootloader: Option<Bootloader>,
) -> Result<Option<Vec<EFIComponent>>> {
    let efilib_path = sysroot.join(usr_path);
    let skip_count = Utf8Path::new(usr_path).components().count();

    let mut components = WalkDir::new(&efilib_path)
        .min_depth(3) // <name>/<version>/EFI: so 3 levels down
        .max_depth(3)
        .into_iter()
        .filter_map(|entry| {
            let entry = match entry {
                Ok(entry) => entry,
                // Without usr/lib/efi, there are no components.
                Err(e) if is_missing_root(&e) => return None,
                // Skipping a directory that cannot be read would make the
                // components in it look absent.
                Err(e) => return Some(Err(walk_error(e, efilib_path.as_std_path()))),
            };
            if !entry.file_type().is_dir() || entry.file_name() != "EFI" {
                return None;
            }

            let abs_path = entry.path();
            let rel_path = abs_path.strip_prefix(sysroot).ok()?;
            let utf8_rel_path = Utf8PathBuf::from_path_buf(rel_path.to_path_buf()).ok()?;

            let mut components = utf8_rel_path.components();

            let name = components.nth(skip_count)?.to_string();
            let version = components.next()?.to_string();

            Some(Ok(EFIComponent {
                name,
                version,
                path: utf8_rel_path,
            }))
        })
        .collect::<Result<Vec<_>>>()?;

    components.sort_by(|a, b| a.name.cmp(&b.name));

    let Some(bootloader) = bootloader else {
        // Unfiltered discovery: an empty result is how callers learn that the
        // new layout is not in use, so that they can fall back to the legacy
        // update directory. A filtered request cannot fall back that way --
        // the legacy directory is copied wholesale, with no way to honour a
        // bootloader selection -- so it goes on to the check below instead.
        return Ok((!components.is_empty()).then_some(components));
    };

    // Remove all EFI Components not associated with the bootloader
    let to_remove = Bootloader::iter()
        .filter(|b| *b != bootloader)
        .map(|b| b.efi_component_name())
        .collect::<Vec<_>>();

    let found = if components.is_empty() {
        "none".to_string()
    } else {
        components
            .iter()
            .map(|comp| comp.name.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    };

    let efi_comps = components
        .into_iter()
        .filter(|comp| !to_remove.contains(&comp.name.as_str()))
        .collect::<Vec<_>>();

    // Components that belong to no bootloader such as shim are never
    // filtered out, so a non-empty efi_comps therefore does not mean
    // the requested bootloader was found. Check explicitly.
    let wanted = bootloader.efi_component_name();
    if !efi_comps.iter().any(|comp| comp.name == wanted) {
        anyhow::bail!(
            "Bootloader '{bootloader}' was requested, but no '{wanted}' component was found \
             in {usr_path}; expected {usr_path}/{wanted}/<version>/EFI (found: {found})"
        );
    }

    Ok(Some(efi_comps))
}

/// Whether `usr/lib/efi` exists in `sysroot`, even if empty. If it does,
/// `install` and generate-update-metadata take the EFI update payload from
/// there instead of the legacy update directory; update and status also need a
/// component in it. An error checking for it is returned, not treated as
/// missing, and so is a symbolic link there that leads nowhere.
#[context("Checking for {EFILIB} in {sysroot}")]
fn payload_in_usr_lib_efi(sysroot: &Utf8Path) -> Result<bool> {
    let efilib = sysroot.join(EFILIB);
    match efilib.symlink_metadata() {
        Ok(meta) if meta.is_symlink() => match efilib.metadata() {
            Ok(_) => Ok(true),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                anyhow::bail!("a symbolic link to nothing")
            }
            Err(e) => Err(e.into()),
        },
        Ok(_) => Ok(true),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(e.into()),
    }
}

/// Where `install` takes the EFI update payload in `src_root` from, see
/// [`payload_in_usr_lib_efi`].
pub(crate) fn payload_location(src_root: &Utf8Path) -> Result<PathBuf> {
    Ok(if payload_in_usr_lib_efi(src_root)? {
        PathBuf::from(EFILIB)
    } else {
        let name: &str = ComponentType::Efi.into();
        Path::new(BOOTUPD_UPDATES_DIR).join(name)
    })
}

/// The bootloaders the EFI update payload in `src_root` carries, as `install`
/// copies it, each with the versions of its `usr/lib/efi` component that
/// hold the bootloader binary.
///
/// With `usr/lib/efi`, a bootloader needs a component of its own there. Only
/// versions holding the binary count, as an upgrade can leave the empty
/// directory of an older version behind. Without `usr/lib/efi`, the legacy
/// update directory, which `install` copies as a whole, can only carry GRUB,
/// if the binary is there. A payload directory that cannot be read fails
/// this instead of hiding a bootloader.
#[context("Listing the bootloaders in the EFI update payload")]
fn carried_bootloaders(src_root: &Utf8Path) -> Result<Vec<(Bootloader, Vec<String>)>> {
    if !payload_in_usr_lib_efi(src_root)? {
        let legacy = src_root.as_std_path().join(payload_location(src_root)?);
        return Ok(if holds_file(&legacy, BOOTLOADER_BIN)? {
            vec![(Bootloader::Grub, Vec::new())]
        } else {
            Vec::new()
        });
    }
    let components = get_efi_component_from_usr(src_root, EFILIB, None)?.unwrap_or_default();
    let mut carried = Vec::new();
    for bootloader in Bootloader::iter() {
        let mut versions = Vec::new();
        for component in &components {
            if component.name == bootloader.efi_component_name()
                && holds_file(src_root.join(&component.path).as_std_path(), BOOTLOADER_BIN)?
            {
                versions.push(component.version.clone());
            }
        }
        if !versions.is_empty() {
            carried.push((bootloader, versions));
        }
    }
    Ok(carried)
}

/// The bootloaders the EFI update payload in `src_root` carries, see
/// [`carried_bootloaders`].
///
/// Unlike the component names in the update metadata, this also works for an
/// image without `usr/lib/efi` whose metadata bootupd 0.4.0 or newer
/// generated, as that names packages.
pub(crate) fn bootloaders_in_payload(src_root: &Utf8Path) -> Result<Vec<Bootloader>> {
    Ok(carried_bootloaders(src_root)?
        .into_iter()
        .map(|(bootloader, _)| bootloader)
        .collect())
}

/// The names of `bootloaders`, as `--bootloader` takes them, for messages.
pub(crate) fn bootloader_names(bootloaders: &[Bootloader]) -> String {
    let names = bootloaders
        .iter()
        .map(|b| b.to_string())
        .collect::<Vec<_>>();
    names.join(", ")
}

/// Errors when the update payload uses the `usr/lib/efi` layout but does
/// not carry the component for `bootloader`, or shim when `boots_via_shim`
/// is true.
///
/// The legacy update directory has no per-bootloader components, so it is not checked.
fn ensure_boot_components(
    root: &Utf8Path,
    bootloader: Bootloader,
    boots_via_shim: bool,
) -> Result<()> {
    let Some(components) = get_efi_component_from_usr(root, EFILIB, None)? else {
        // Legacy payload layout, no components to check
        return Ok(());
    };
    let bootloader = bootloader.efi_component_name();
    let required_components = if boots_via_shim {
        vec![bootloader, "shim"]
    } else {
        vec![bootloader]
    };
    for component in required_components {
        if !components.iter().any(|c| c.name == component) {
            let found = components
                .iter()
                .map(|c| c.name.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            anyhow::bail!(
                "Update payload has no '{component}' component. Expected \
                 {EFILIB}/{component}/<version>/EFI (found: {found})"
            );
        }
    }
    Ok(())
}

/// Errors when the update payload does not carry the binaries the current
/// system boots from.
///
/// Unlike [`ensure_boot_components`] this inspects the payload file trees,
/// so it also covers the legacy update directory layout.
fn ensure_boot_binaries(
    currentf: &filetree::FileTree,
    updatef: &filetree::FileTree,
    boots_via_shim: bool,
) -> Result<()> {
    let required_binaries = if boots_via_shim {
        vec![BOOTLOADER_BIN, SHIM]
    } else {
        vec![BOOTLOADER_BIN]
    };
    for path in currentf.children.keys() {
        // What is currently installed must remain provided by the
        // payload, since nothing else can re-provide it.
        // The path must match too since shim and the firmware boot entry
        // resolve the binaries by their installed path, so a payload which moves
        // the binary would break the boot chain too.
        let name = Utf8Path::new(path)
            .file_name()
            .ok_or_else(|| anyhow::anyhow!("Invalid filetree key: {path:?}"))?;
        if required_binaries.contains(&name) && !updatef.children.contains_key(path) {
            anyhow::bail!(
                "The update payload does not include '{name}' at '{path}', refusing to remove it from the ESP"
            );
        }
    }
    Ok(())
}

/// Copies usr/lib/ostree-boot/EFI to usr/lib/bootupd/updates
fn transfer_ostree_boot_to_bootupd_updates(
    sysroot: &Utf8Path,
    component: &Efi,
) -> Result<ContentMetadata> {
    let ostreebootdir = sysroot.join(ostreeutil::BOOT_PREFIX);

    // move EFI files to updates dir from /usr/lib/ostree-boot
    if !ostreebootdir.exists() {
        anyhow::bail!("Failed to find {ostreebootdir}");
    }

    let efisrc = ostreebootdir.join("efi/EFI");
    if !efisrc.exists() {
        bail!("Failed to find {:?}", &efisrc);
    }

    let dest_efidir = component_updatedir(sysroot.as_str(), component);
    let dest_efidir = Utf8PathBuf::from_path_buf(dest_efidir).expect("Path is invalid UTF-8");

    // Fork off mv() because on overlayfs one can't rename() a lower level
    // directory today, and this will handle the copy fallback.
    Command::new("mv")
        .args([&efisrc, &dest_efidir])
        .run_capture_stderr()?;

    let efidir = Dir::open_ambient_dir(dest_efidir.as_std_path(), ambient_authority())
        .with_context(|| format!("Opening {}", dest_efidir))?;

    let files = crate::util::filenames(&efidir)?.into_iter().map(|mut f| {
        f.insert_str(0, "/boot/efi/EFI");
        f
    });

    let files = files.collect::<Vec<_>>();

    query_files(sysroot.as_str(), files)
}

#[cfg(test)]
mod tests {
    use cap_std_ext::dirext::CapStdExtDirExt;

    use super::*;

    /// ContentMetadata whose only consumer is display code now that updates
    /// are decided by content, so one version string doubles as module EVR.
    fn create_test_meta(version: &str) -> ContentMetadata {
        ContentMetadata {
            timestamp: chrono::Utc::now(),
            version: version.into(),
            versions: Some(vec![Module {
                name: "shim".into(),
                evr: version.into(),
            }]),
            default_bootloader: None,
        }
    }

    #[test]
    fn test_parse_boot_entries() -> Result<()> {
        let output = r"
BootCurrent: 0003
Timeout: 0 seconds
BootOrder: 0003,0001,0000,0002
Boot0000* UiApp	FvVol(7cb8bdc9-f8eb-4f34-aaea-3ee4af6516a1)/FvFile(462caa21-7614-4503-836e-8ab6f4662331)
Boot0001* UEFI Misc Device	PciRoot(0x0)/Pci(0x3,0x0){auto_created_boot_option}
Boot0002* EFI Internal Shell	FvVol(7cb8bdc9-f8eb-4f34-aaea-3ee4af6516a1)/FvFile(7c04a583-9e3e-4f1c-ad65-e05268d0b4d1)
Boot0003* Fedora	HD(2,GPT,94ff4025-5276-4bec-adea-e98da271b64c,0x1000,0x3f800)/\EFI\fedora\shimx64.efi";
        let entries = parse_boot_entries(output);
        assert_eq!(
            entries,
            [
                BootEntry {
                    id: "0000".to_string(),
                    name: "UiApp".to_string()
                },
                BootEntry {
                    id: "0001".to_string(),
                    name: "UEFI Misc Device".to_string()
                },
                BootEntry {
                    id: "0002".to_string(),
                    name: "EFI Internal Shell".to_string()
                },
                BootEntry {
                    id: "0003".to_string(),
                    name: "Fedora".to_string()
                }
            ]
        );
        let output = r"
BootCurrent: 0003
Timeout: 0 seconds
BootOrder: 0003,0001,0000,0002";
        let entries = parse_boot_entries(output);
        assert_eq!(entries, []);

        let output = r"
BootCurrent: 0003
Timeout: 0 seconds
BootOrder: 0003,0001,0000,0002
Boot0000* UiApp
Boot0001* UEFI Misc Device
Boot0002* EFI Internal Shell
Boot0003* test";
        let entries = parse_boot_entries(output);
        assert_eq!(
            entries,
            [
                BootEntry {
                    id: "0000".to_string(),
                    name: "UiApp".to_string()
                },
                BootEntry {
                    id: "0001".to_string(),
                    name: "UEFI Misc Device".to_string()
                },
                BootEntry {
                    id: "0002".to_string(),
                    name: "EFI Internal Shell".to_string()
                },
                BootEntry {
                    id: "0003".to_string(),
                    name: "test".to_string()
                }
            ]
        );
        Ok(())
    }
    #[cfg(test)]
    fn fixture() -> Result<cap_std_ext::cap_tempfile::TempDir> {
        let tempdir = cap_std_ext::cap_tempfile::tempdir(cap_std::ambient_authority())?;
        tempdir.create_dir("etc")?;
        Ok(tempdir)
    }
    #[test]
    fn test_get_product_name() -> Result<()> {
        let tmpd = fixture()?;
        {
            tmpd.atomic_write("etc/system-release", "Fedora release 40 (Forty)")?;
            let name = get_product_name(&tmpd)?;
            assert_eq!("Fedora", name);
        }
        {
            tmpd.atomic_write("etc/system-release", "CentOS Stream release 9")?;
            let name = get_product_name(&tmpd)?;
            assert_eq!("CentOS Stream", name);
        }
        {
            tmpd.atomic_write(
                "etc/system-release",
                "Red Hat Enterprise Linux CoreOS release 4",
            )?;
            let name = get_product_name(&tmpd)?;
            assert_eq!("Red Hat Enterprise Linux CoreOS", name);
        }
        {
            tmpd.atomic_write(
                "etc/system-release",
                "Red Hat Enterprise Linux CoreOS release 4
                ",
            )?;
            let name = get_product_name(&tmpd)?;
            assert_eq!("Red Hat Enterprise Linux CoreOS", name);
        }
        {
            tmpd.remove_file("etc/system-release")?;
            let name = get_product_name(&tmpd)?;
            assert!(name.len() > 0);
        }
        Ok(())
    }

    #[test]
    #[cfg(efi_arch)]
    fn test_get_efi_component_from_usr() -> Result<()> {
        let tmpdir: &tempfile::TempDir = &tempfile::tempdir()?;
        let tpath = tmpdir.path();
        let efi_path = tpath.join("usr/lib/efi");

        // Create realistic directory structure for both bootloaders
        // grub-cc structure
        std::fs::create_dir_all(efi_path.join("grub-cc/1:2.12-59.fc45/EFI/fedora"))?;
        std::fs::File::create(efi_path.join("grub-cc/1:2.12-59.fc45/EFI/fedora/grubx64-cc.efi"))?;

        // grub2 structure
        std::fs::create_dir_all(efi_path.join("grub2/1:2.12-58.fc44/EFI/fedora"))?;
        std::fs::File::create(efi_path.join("grub2/1:2.12-58.fc44/EFI/fedora/grubx64.efi"))?;

        // shim structure
        std::fs::create_dir_all(efi_path.join("shim/16.1-5/EFI/BOOT"))?;
        std::fs::create_dir_all(efi_path.join("shim/16.1-5/EFI/fedora"))?;
        std::fs::File::create(efi_path.join("shim/16.1-5/EFI/BOOT/BOOTX64.EFI"))?;
        std::fs::File::create(efi_path.join("shim/16.1-5/EFI/BOOT/fbx64.efi"))?;
        std::fs::File::create(efi_path.join("shim/16.1-5/EFI/fedora/BOOTX64.CSV"))?;
        std::fs::File::create(efi_path.join("shim/16.1-5/EFI/fedora/mmx64.efi"))?;
        std::fs::File::create(efi_path.join("shim/16.1-5/EFI/fedora/shim.efi"))?;
        std::fs::File::create(efi_path.join("shim/16.1-5/EFI/fedora/shimx64.efi"))?;

        let utf8_tpath =
            Utf8Path::from_path(tpath).ok_or_else(|| anyhow::anyhow!("Path is not valid UTF-8"))?;

        // Test with no filtering - should return all EFI components
        let efi_comps = get_efi_component_from_usr(utf8_tpath, EFILIB, None)?;
        assert_eq!(
            efi_comps,
            Some(vec![
                EFIComponent {
                    name: "grub-cc".to_string(),
                    version: "1:2.12-59.fc45".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/grub-cc/1:2.12-59.fc45/EFI"),
                },
                EFIComponent {
                    name: "grub2".to_string(),
                    version: "1:2.12-58.fc44".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/grub2/1:2.12-58.fc44/EFI"),
                },
                EFIComponent {
                    name: "shim".to_string(),
                    version: "16.1-5".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/shim/16.1-5/EFI"),
                },
            ])
        );

        // Test with filtering for Grub - should only return grub2 and shim
        let efi_comps = get_efi_component_from_usr(utf8_tpath, EFILIB, Some(Bootloader::Grub))?;
        assert_eq!(
            efi_comps,
            Some(vec![
                EFIComponent {
                    name: "grub2".to_string(),
                    version: "1:2.12-58.fc44".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/grub2/1:2.12-58.fc44/EFI"),
                },
                EFIComponent {
                    name: "shim".to_string(),
                    version: "16.1-5".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/shim/16.1-5/EFI"),
                },
            ])
        );

        // Test with filtering for GrubCC - should only return grub-cc and shim
        let efi_comps = get_efi_component_from_usr(utf8_tpath, EFILIB, Some(Bootloader::GrubCC))?;
        assert_eq!(
            efi_comps,
            Some(vec![
                EFIComponent {
                    name: "grub-cc".to_string(),
                    version: "1:2.12-59.fc45".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/grub-cc/1:2.12-59.fc45/EFI"),
                },
                EFIComponent {
                    name: "shim".to_string(),
                    version: "16.1-5".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/shim/16.1-5/EFI"),
                },
            ])
        );

        // Test with filtering for Systemd while no systemd-boot component exists - should
        // error rather than quietly returning shim on its own, which would install a first
        // stage with no second stage behind it.
        let err = get_efi_component_from_usr(utf8_tpath, EFILIB, Some(Bootloader::Systemd))
            .expect_err("missing systemd-boot component should be an error");
        let err = err.to_string();
        assert!(
            err.contains("no 'systemd-boot' component")
                && err.contains("found: grub-cc, grub2, shim"),
            "unexpected error: {err}"
        );

        // systemd-boot structure. Note the binary is named grubx64.efi: that is the second
        // stage filename baked into shim.
        std::fs::create_dir_all(efi_path.join("systemd-boot/261.2-4.fc45/EFI/fedora"))?;
        std::fs::File::create(efi_path.join("systemd-boot/261.2-4.fc45/EFI/fedora/grubx64.efi"))?;

        // Test with filtering for Systemd - should only return shim and systemd-boot
        let efi_comps = get_efi_component_from_usr(utf8_tpath, EFILIB, Some(Bootloader::Systemd))?;
        assert_eq!(
            efi_comps,
            Some(vec![
                EFIComponent {
                    name: "shim".to_string(),
                    version: "16.1-5".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/shim/16.1-5/EFI"),
                },
                EFIComponent {
                    name: "systemd-boot".to_string(),
                    version: "261.2-4.fc45".to_string(),
                    path: Utf8PathBuf::from("usr/lib/efi/systemd-boot/261.2-4.fc45/EFI"),
                },
            ])
        );

        // Test with empty directory - unfiltered discovery returns None, which is
        // how the caller learns to fall back to the legacy update directory.
        std::fs::remove_dir_all(&efi_path)?;
        std::fs::create_dir_all(&efi_path)?;
        let efi_comps = get_efi_component_from_usr(utf8_tpath, EFILIB, None)?;
        assert_eq!(efi_comps, None);

        // ...but a request for a specific bootloader still errors, rather than
        // falling back to a directory that is copied wholesale and so cannot
        // honour the request.
        let err = get_efi_component_from_usr(utf8_tpath, EFILIB, Some(Bootloader::Systemd))
            .expect_err("missing systemd-boot component should be an error");
        let err = err.to_string();
        assert!(
            err.contains("no 'systemd-boot' component") && err.contains("found: none"),
            "unexpected error: {err}"
        );
        Ok(())
    }

    /// The C library's text for `errno`, as error messages include it.
    fn os_error_text(errno: i32) -> String {
        std::io::Error::from_raw_os_error(errno).to_string()
    }

    /// `dir`, padded with "/." to almost PATH_MAX, and a name too long to be
    /// read below it: such a path is longer than PATH_MAX, so reading it fails
    /// with ENAMETOOLONG, for root as well, unlike a file mode.
    fn unreadable_below(dir: &Utf8Path) -> (Utf8PathBuf, String) {
        let mut padded = dir.to_string();
        while padded.len() < 3900 {
            padded.push_str("/.");
        }
        (Utf8PathBuf::from(padded), "x".repeat(255))
    }

    #[test]
    fn test_get_efi_component_from_usr_unreadable() -> Result<()> {
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        // Without usr/lib/efi, there are no components.
        assert_eq!(get_efi_component_from_usr(root, EFILIB, None)?, None);

        // A component directory that cannot be read
        let (padded, long) = unreadable_below(root);
        std::fs::create_dir_all(root.join(EFILIB).join(&long).join("1.0-1/EFI"))?;
        let err = get_efi_component_from_usr(&padded, EFILIB, None)
            .expect_err("an unreadable component must not look absent");
        let enametoolong = os_error_text(libc::ENAMETOOLONG);
        assert!(format!("{err:#}").contains(&enametoolong), "{err:#}");
        Ok(())
    }

    /// A symlink loop fails a walk even for root, which file modes do not.
    #[test]
    fn test_payload_walks_fail_on_symlink_loop() -> Result<()> {
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        let efilib = root.join(EFILIB);
        std::fs::create_dir_all(efilib.parent().unwrap())?;
        std::os::unix::fs::symlink("efi", &efilib)?;
        let err = get_efi_component_from_usr(root, EFILIB, None).unwrap_err();
        assert!(
            format!("{err:#}").contains(&os_error_text(libc::ELOOP)),
            "{err:#}"
        );
        Ok(())
    }

    #[test]
    fn test_holds_file() -> Result<()> {
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        let vendor = root.join("EFI/fedora");
        assert!(!holds_file(vendor.as_std_path(), BOOTLOADER_BIN)?);
        std::fs::create_dir_all(&vendor)?;
        assert!(!holds_file(root.as_std_path(), BOOTLOADER_BIN)?);
        std::fs::write(vendor.join(BOOTLOADER_BIN), "grub")?;
        assert!(holds_file(root.as_std_path(), BOOTLOADER_BIN)?);

        // A symlink loop fails this even for root.
        let looped = root.join("looped");
        std::os::unix::fs::symlink("looped", &looped)?;
        let err = holds_file(looped.as_std_path(), BOOTLOADER_BIN).unwrap_err();
        assert!(
            format!("{err:#}").contains(&os_error_text(libc::ELOOP)),
            "{err:#}"
        );

        // A directory that cannot be read, here with the binary in it
        let (padded, long) = unreadable_below(root);
        let hidden = root.join("hidden").join(&long);
        std::fs::create_dir_all(&hidden)?;
        std::fs::write(hidden.join(BOOTLOADER_BIN), "grub")?;
        let err = holds_file(padded.join("hidden").as_std_path(), BOOTLOADER_BIN)
            .expect_err("an unreadable directory must not hide the binary");
        let enametoolong = os_error_text(libc::ENAMETOOLONG);
        assert!(format!("{err:#}").contains(&enametoolong), "{err:#}");
        Ok(())
    }

    #[test]
    fn test_payload_in_usr_lib_efi() -> Result<()> {
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        assert!(!payload_in_usr_lib_efi(root)?);
        std::fs::create_dir_all(root.join(EFILIB))?;
        assert!(payload_in_usr_lib_efi(root)?);
        // One that cannot be checked does not count as missing,
        std::fs::remove_dir(root.join(EFILIB))?;
        std::os::unix::fs::symlink("efi", root.join(EFILIB))?;
        let err = payload_in_usr_lib_efi(root).unwrap_err();
        assert!(
            format!("{err:#}").contains(&os_error_text(libc::ELOOP)),
            "{err:#}"
        );
        // nor does a symbolic link to nothing, while one to a directory
        // counts.
        std::fs::remove_file(root.join(EFILIB))?;
        std::os::unix::fs::symlink("missing", root.join(EFILIB))?;
        let err = payload_in_usr_lib_efi(root).unwrap_err();
        assert_eq!(
            format!("{err:#}"),
            format!("Checking for {EFILIB} in {root}: a symbolic link to nothing")
        );
        std::fs::create_dir(root.join("usr/lib/missing"))?;
        assert!(payload_in_usr_lib_efi(root)?);
        Ok(())
    }

    #[test]
    fn test_bootloaders_in_payload() -> Result<()> {
        use Bootloader::{Grub, GrubCC, Systemd};
        #[derive(Debug)]
        struct Case {
            /// The components in usr/lib/efi, `None` without that directory.
            /// Each holds the bootloader binary, but shim holds shim.
            usr_lib_efi: Option<&'static [&'static str]>,
            /// Components there, of another version, without any binary
            empty: &'static [&'static str],
            /// A legacy update directory with shim, and whether it has the
            /// GRUB binary as well; `None` without that directory
            legacy_grub: Option<bool>,
            expected: &'static [Bootloader],
        }
        let cases = [
            Case {
                usr_lib_efi: Some(&["grub2", "shim"]),
                empty: &[],
                legacy_grub: None,
                expected: &[Grub],
            },
            Case {
                usr_lib_efi: Some(&["grub2", "shim", "systemd-boot"]),
                empty: &[],
                legacy_grub: None,
                expected: &[Grub, Systemd],
            },
            Case {
                usr_lib_efi: Some(&["grub-cc", "shim"]),
                empty: &[],
                legacy_grub: None,
                expected: &[GrubCC],
            },
            Case {
                usr_lib_efi: Some(&["shim"]),
                empty: &[],
                legacy_grub: None,
                expected: &[],
            },
            // A component without the binary does not count,
            Case {
                usr_lib_efi: Some(&["grub2", "shim"]),
                empty: &["systemd-boot"],
                legacy_grub: None,
                expected: &[Grub],
            },
            // nor does an empty version that an upgrade left behind.
            Case {
                usr_lib_efi: Some(&["grub2", "shim"]),
                empty: &["grub2"],
                legacy_grub: None,
                expected: &[Grub],
            },
            Case {
                usr_lib_efi: Some(&["shim"]),
                empty: &["grub2"],
                legacy_grub: None,
                expected: &[],
            },
            // `install` refuses every bootloader with an empty usr/lib/efi,
            // even next to the legacy update directory.
            Case {
                usr_lib_efi: Some(&[]),
                empty: &[],
                legacy_grub: Some(true),
                expected: &[],
            },
            Case {
                usr_lib_efi: None,
                empty: &[],
                legacy_grub: Some(true),
                expected: &[Grub],
            },
            Case {
                usr_lib_efi: None,
                empty: &[],
                legacy_grub: Some(false),
                expected: &[],
            },
            Case {
                usr_lib_efi: None,
                empty: &[],
                legacy_grub: None,
                expected: &[],
            },
        ];
        for case in &cases {
            let td = tempfile::tempdir()?;
            let root = Utf8Path::from_path(td.path()).unwrap();
            if let Some(components) = case.usr_lib_efi {
                std::fs::create_dir_all(root.join(EFILIB))?;
                for name in components {
                    let vendor = root.join(EFILIB).join(name).join("1.0-1/EFI/fedora");
                    std::fs::create_dir_all(&vendor)?;
                    let binary = if *name == "shim" {
                        SHIM
                    } else {
                        BOOTLOADER_BIN
                    };
                    std::fs::write(vendor.join(binary), "")?;
                }
            }
            for name in case.empty {
                std::fs::create_dir_all(root.join(EFILIB).join(name).join("0.9-1/EFI"))?;
            }
            if let Some(with_grub) = case.legacy_grub {
                let vendor = root.join(BOOTUPD_UPDATES_DIR).join("EFI/centos");
                std::fs::create_dir_all(&vendor)?;
                std::fs::write(vendor.join(SHIM), "shim")?;
                if with_grub {
                    std::fs::write(vendor.join(BOOTLOADER_BIN), "grub")?;
                }
            }
            assert_eq!(bootloaders_in_payload(root)?, case.expected, "{case:?}");
        }

        // A component holding only a binary shim does not load does not
        // count either.
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        for (name, binary) in [
            ("grub2", BOOTLOADER_BIN),
            ("shim", SHIM),
            ("systemd-boot", "systemd-bootx64.efi"),
        ] {
            let vendor = root.join(EFILIB).join(name).join("1.0-1/EFI/fedora");
            std::fs::create_dir_all(&vendor)?;
            std::fs::write(vendor.join(binary), "")?;
        }
        assert_eq!(bootloaders_in_payload(root)?, [Grub]);
        Ok(())
    }

    #[test]
    fn test_get_system_name() {
        assert_eq!("Fedora", &get_system_name("Fedora release 44 (Forty Four)"));
        assert_eq!("CentOS Stream", &get_system_name("CentOS Stream release 9"));
        assert_eq!(
            "Red Hat Enterprise Linux",
            &get_system_name("Red Hat Enterprise Linux release 10.2 (Coughlan)")
        );
        assert_eq!("no_change", &get_system_name("no_change"));
        assert_eq!("", &get_system_name(""));
    }

    #[test]
    fn test_string_from_utf16_bytes() {
        assert_eq!(
            "hello",
            string_from_utf16_bytes(&[b'h', 0, b'e', 0, b'l', 0, b'l', 0, b'o', 0]),
        );
        assert_eq!(
            "nul",
            string_from_utf16_bytes(&[b'n', 0, b'u', 0, b'l', 0, 0, 0, b'l', b'0']),
        );
        assert_eq!(
            "SYS",
            string_from_utf16_bytes(&[b'S', 0, b'Y', 0, b'S', 0, 0, 0, 0,]),
        );
        assert_eq!("", string_from_utf16_bytes(&[]));
        assert_eq!("", string_from_utf16_bytes(&[0, 0]));
    }

    #[test]
    fn test_query_updatable_new_content_wins() -> Result<()> {
        use crate::filetree::FileTree;
        use chrono::Utc;

        let sysroot = tempfile::tempdir()?;
        let sysroot_path = sysroot.path();
        let utf8_sysroot = Utf8Path::from_path(sysroot_path)
            .ok_or_else(|| anyhow::anyhow!("Path is not valid UTF-8"))?;

        // The update payload from the target image, with a lower EVR (legacy layout)
        let update_payload = "usr/lib/bootupd/updates/EFI";
        let update_payload_dir = sysroot_path.join(update_payload);
        std::fs::create_dir_all(update_payload_dir.join("fedora"))?;
        std::fs::write(
            update_payload_dir.join("fedora/shimx64.efi"),
            "shim data new",
        )?;

        let update_meta = ContentMetadata {
            timestamp: Utc::now(),
            version: "shim-16.1-7.el9".into(),
            versions: Some(vec![Module {
                name: "shim".into(),
                evr: "16.1-7.el9".into(),
            }]),
            default_bootloader: None,
        };
        write_update_metadata(
            utf8_sysroot.as_str(),
            PathBuf::from("EFI.json"),
            &update_meta,
        )?;

        // The installed shim has a higher EVR than the update
        let installed_meta = ContentMetadata {
            timestamp: Utc::now(),
            version: "shim-16.1-8.el9_6".into(),
            versions: Some(vec![Module {
                name: "shim".into(),
                evr: "16.1-8.el9_6".into(),
            }]),
            default_bootloader: None,
        };

        // Old payload with the content that is currently installed
        let old_payload = tempfile::tempdir()?;
        std::fs::create_dir_all(old_payload.path().join("fedora"))?;
        std::fs::write(
            old_payload.path().join("fedora/shimx64.efi"),
            "shim data old",
        )?;

        let sysroot_dir = Dir::open_ambient_dir(sysroot_path, ambient_authority())?;
        let old_payload_dir = Dir::open_ambient_dir(old_payload.path(), ambient_authority())?;
        let sysroot = Sysroot {
            dir: &sysroot_dir,
            path: utf8_sysroot,
        };
        let dirs_to_skip = Bootloader::Grub.dirs_to_skip();
        let efi = Efi::default();

        let installed = |filetree| InstalledContent {
            meta: installed_meta.clone(),
            filetree,
            adopted_from: None,
        };

        // Content differs, so the update is applied despite the lower EVR
        let inst = installed(Some(FileTree::new_from_dir(
            &old_payload_dir,
            Some(dirs_to_skip.clone()),
        )?));
        let (update, updatable) = efi.query_updatable(sysroot, &inst, Bootloader::Grub)?;
        assert!(update.is_some());
        assert!(matches!(updatable, ComponentUpdatable::Upgradable));

        // Content is identical, so there is no update even though the
        // version strings differ
        let payload_dir = sysroot.dir.open_dir(update_payload)?;
        let inst = installed(Some(FileTree::new_from_dir(
            &payload_dir,
            Some(dirs_to_skip.clone()),
        )?));
        let (update, updatable) = efi.query_updatable(sysroot, &inst, Bootloader::Grub)?;
        assert!(update.is_some());
        assert!(matches!(updatable, ComponentUpdatable::AtLatestVersion));

        // A missing installed filetree is not a valid EFI state
        let inst = installed(None);
        let err = efi
            .query_updatable(sysroot, &inst, Bootloader::Grub)
            .expect_err("missing installed filetree must be an error");
        assert!(err.to_string().contains("No filetree"));

        // No update metadata means no update available
        let empty = tempfile::tempdir()?;
        let empty_dir = Dir::open_ambient_dir(empty.path(), ambient_authority())?;
        let utf8_empty = Utf8Path::from_path(empty.path())
            .ok_or_else(|| anyhow::anyhow!("Path is not valid UTF-8"))?;
        let empty_sysroot = Sysroot {
            dir: &empty_dir,
            path: utf8_empty,
        };
        let (update, updatable) = efi.query_updatable(empty_sysroot, &inst, Bootloader::Grub)?;
        assert!(update.is_none());
        assert!(matches!(updatable, ComponentUpdatable::NoUpdateAvailable));

        Ok(())
    }

    #[test]
    fn test_query_updatable_content_wins_usr_lib_efi() -> Result<()> {
        use crate::filetree::FileTree;

        let sysroot = tempfile::tempdir()?;
        let sysroot_path = sysroot.path();
        let utf8_sysroot = Utf8Path::from_path(sysroot_path)
            .ok_or_else(|| anyhow::anyhow!("Path is not valid UTF-8"))?;

        // The update payload in the new layout, with a lower EVR than the
        // installed shim
        let payload_files = [
            ("shim/16.1-7.el9/EFI/fedora/shimx64.efi", "shim data new"),
            ("grub2/2.12-7.el9/EFI/fedora/grubx64.efi", "grub2 payload"),
            // Same file name as grub2's bootloader, shipped by another bootloader
            (
                "systemd-boot/261.2-4/EFI/fedora/grubx64.efi",
                "systemd-boot payload",
            ),
        ];
        for (path, contents) in payload_files {
            let path = sysroot_path.join("usr/lib/efi").join(path);
            std::fs::create_dir_all(path.parent().unwrap())?;
            std::fs::write(path, contents)?;
        }

        std::fs::create_dir_all(utf8_sysroot.join(BOOTUPD_UPDATES_DIR))?;
        write_update_metadata(
            utf8_sysroot.as_str(),
            PathBuf::from("EFI.json"),
            &create_test_meta("shim-16.1-7.el9"),
        )?;

        // A payload with the content that is currently installed
        let old_payload = tempfile::tempdir()?;
        let old_files = [
            ("shim/16.1-8.el9_6/EFI/fedora/shimx64.efi", "shim data old"),
            ("grub2/2.12-8.el9_6/EFI/fedora/grubx64.efi", "grub2 payload"),
        ];
        for (path, contents) in old_files {
            std::fs::create_dir_all(old_payload.path().join(path).parent().unwrap())?;
            std::fs::write(old_payload.path().join(path), contents)?;
        }

        let sysroot_dir = Dir::open_ambient_dir(sysroot_path, ambient_authority())?;
        let old_payload_dir = Dir::open_ambient_dir(old_payload.path(), ambient_authority())?;
        let sysroot = Sysroot {
            dir: &sysroot_dir,
            path: utf8_sysroot,
        };
        let dirs_to_skip = Bootloader::Grub.dirs_to_skip();
        let efi = Efi::default();

        // Changed content wins even though the EVR is lower
        let inst = InstalledContent {
            meta: create_test_meta("shim-16.1-8.el9_6"),
            filetree: Some(FileTree::new_from_dir(
                &old_payload_dir,
                Some(dirs_to_skip.clone()),
            )?),
            adopted_from: None,
        };
        let (update, updatable) = efi.query_updatable(sysroot, &inst, Bootloader::Grub)?;
        assert!(update.is_some());
        assert!(matches!(updatable, ComponentUpdatable::Upgradable));

        // A repackaged shim under a different version directory, but with
        // identical file content, is not an update
        std::fs::write(
            old_payload
                .path()
                .join("shim/16.1-8.el9_6/EFI/fedora/shimx64.efi"),
            "shim data new",
        )?;
        let inst = InstalledContent {
            meta: create_test_meta("shim-16.1-8.el9_6"),
            filetree: Some(FileTree::new_from_dir(
                &old_payload_dir,
                Some(dirs_to_skip),
            )?),
            adopted_from: None,
        };
        let (update, updatable) = efi.query_updatable(sysroot, &inst, Bootloader::Grub)?;
        assert!(update.is_some());
        assert!(matches!(updatable, ComponentUpdatable::AtLatestVersion));

        Ok(())
    }

    #[test]
    fn test_query_updatable_cross_layout() -> Result<()> {
        use crate::filetree::FileTree;

        let sysroot = tempfile::tempdir()?;
        let sysroot_path = sysroot.path();
        let utf8_sysroot = Utf8Path::from_path(sysroot_path)
            .ok_or_else(|| anyhow::anyhow!("Path is not valid UTF-8"))?;

        // The update payload uses the usr/lib/efi layout
        let new_shim = "shim/16.1-7.el9/EFI/fedora/shimx64.efi";
        std::fs::create_dir_all(
            sysroot_path
                .join("usr/lib/efi")
                .join("shim/16.1-7.el9/EFI/fedora"),
        )?;
        std::fs::write(sysroot_path.join("usr/lib/efi").join(new_shim), "shim data")?;

        std::fs::create_dir_all(utf8_sysroot.join(BOOTUPD_UPDATES_DIR))?;
        write_update_metadata(
            utf8_sysroot.as_str(),
            PathBuf::from("EFI.json"),
            &create_test_meta("shim-16.1-7.el9"),
        )?;

        // The installed filetree was recorded from the legacy layout, which
        // holds the ESP contents directly without versioned directories
        let old_payload = tempfile::tempdir()?;
        std::fs::create_dir_all(old_payload.path().join("fedora"))?;
        std::fs::write(
            old_payload.path().join("fedora/shimx64.efi"),
            "shim data old",
        )?;

        let sysroot_dir = Dir::open_ambient_dir(sysroot_path, ambient_authority())?;
        let old_payload_dir = Dir::open_ambient_dir(old_payload.path(), ambient_authority())?;
        let sysroot = Sysroot {
            dir: &sysroot_dir,
            path: utf8_sysroot,
        };
        let dirs_to_skip = Bootloader::Grub.dirs_to_skip();
        let efi = Efi::default();

        // Changed content is an update even across layouts. Both trees are
        // keyed by ESP destination path, so they are comparable
        let inst = InstalledContent {
            meta: create_test_meta("shim-15.8-4"),
            filetree: Some(FileTree::new_from_dir(
                &old_payload_dir,
                Some(dirs_to_skip.clone()),
            )?),
            adopted_from: None,
        };
        let (update, updatable) = efi.query_updatable(sysroot, &inst, Bootloader::Grub)?;
        assert!(update.is_some());
        assert!(matches!(updatable, ComponentUpdatable::Upgradable));

        // Identical content across layouts is not an update
        std::fs::write(old_payload.path().join("fedora/shimx64.efi"), "shim data")?;
        let inst = InstalledContent {
            meta: create_test_meta("shim-15.8-4"),
            filetree: Some(FileTree::new_from_dir(
                &old_payload_dir,
                Some(dirs_to_skip),
            )?),
            adopted_from: None,
        };
        let (update, updatable) = efi.query_updatable(sysroot, &inst, Bootloader::Grub)?;
        assert!(update.is_some());
        assert!(matches!(updatable, ComponentUpdatable::AtLatestVersion));

        Ok(())
    }

    #[test]
    fn test_get_update_payload_dir() -> Result<()> {
        let tmp_sysroot = tempfile::tempdir()?;
        let utf8_sysroot = Utf8Path::from_path(tmp_sysroot.path()).expect("UTF-8");
        let sysroot_dir = Dir::open_ambient_dir(utf8_sysroot, ambient_authority())?;
        let sysroot = Sysroot {
            dir: &sysroot_dir,
            path: utf8_sysroot,
        };
        let efi = Efi::default();

        // An empty usr/lib/efi falls back to the legacy layout
        std::fs::create_dir_all(utf8_sysroot.join(EFILIB))?;
        let legacy = utf8_sysroot.join(BOOTUPD_UPDATES_DIR).join("EFI");
        std::fs::create_dir_all(&legacy)?;
        std::fs::write(legacy.join("marker"), "legacy")?;
        let payload_dir = efi.get_update_payload_dir(sysroot)?;
        assert!(payload_dir.exists("marker"));

        // A component in usr/lib/efi wins over the legacy layout
        std::fs::create_dir_all(utf8_sysroot.join(EFILIB).join("shim/16.1-7.el9/EFI/fedora"))?;
        std::fs::write(
            utf8_sysroot
                .join(EFILIB)
                .join("shim/16.1-7.el9/EFI/fedora/shimx64.efi"),
            "shim",
        )?;
        let payload_dir = efi.get_update_payload_dir(sysroot)?;
        assert!(payload_dir.exists("shim/16.1-7.el9/EFI/fedora/shimx64.efi"));

        // A usr/lib/efi that cannot be checked does not fall back either
        std::fs::remove_dir_all(utf8_sysroot.join(EFILIB))?;
        std::os::unix::fs::symlink("efi", utf8_sysroot.join(EFILIB))?;
        let err = efi.get_update_payload_dir(sysroot).unwrap_err();
        assert!(
            format!("{err:#}").contains(&os_error_text(libc::ELOOP)),
            "{err:#}"
        );

        Ok(())
    }

    #[test]
    fn test_generate_update_metadata_unreadable_usr_lib_efi() -> Result<()> {
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        let legacy = root.join(ostreeutil::BOOT_PREFIX).join("efi/EFI/fedora");
        std::fs::create_dir_all(&legacy)?;
        std::fs::write(legacy.join("shimx64.efi"), "shim")?;
        std::os::unix::fs::symlink("efi", root.join(EFILIB))?;
        let err = Efi::default()
            .generate_update_metadata(root.as_str())
            .unwrap_err();
        assert!(
            format!("{err:#}").contains(&os_error_text(libc::ELOOP)),
            "{err:#}"
        );
        // The legacy payload stays where it is.
        assert!(legacy.join("shimx64.efi").exists());
        Ok(())
    }

    #[test]
    fn test_ensure_boot_components() -> Result<()> {
        let sysroot = tempfile::tempdir()?;
        let utf8_sysroot = Utf8Path::from_path(sysroot.path()).expect("UTF-8");

        // No usr/lib/efi at all
        ensure_boot_components(utf8_sysroot, Bootloader::Grub, true)?;

        // A payload with only the grub2 component, missing shim
        let grub2 = utf8_sysroot
            .join(EFILIB)
            .join("grub2/2.12-7.el9/EFI/fedora");
        std::fs::create_dir_all(&grub2)?;
        std::fs::write(grub2.join("grubx64.efi"), "grub")?;

        ensure_boot_components(utf8_sysroot, Bootloader::Grub, false)?;
        let err = ensure_boot_components(utf8_sysroot, Bootloader::Grub, true)
            .expect_err("missing shim component must be an error");
        assert!(err.to_string().contains("no 'shim' component"));

        // With shim
        let shim = utf8_sysroot.join(EFILIB).join("shim/16.1-7.el9/EFI/fedora");
        std::fs::create_dir_all(&shim)?;
        std::fs::write(shim.join("shimx64.efi"), "shim")?;
        ensure_boot_components(utf8_sysroot, Bootloader::Grub, true)?;

        // The same payload has no systemd-boot component
        let err = ensure_boot_components(utf8_sysroot, Bootloader::Systemd, true)
            .expect_err("missing component must be an error");
        assert!(err.to_string().contains("no 'systemd-boot' component"));

        Ok(())
    }

    #[test]
    fn test_ensure_boot_binaries() -> Result<()> {
        use crate::filetree::FileTree;

        let tree_from = |files: &[&str]| -> Result<FileTree> {
            let payload = tempfile::tempdir()?;
            for f in files {
                let p = payload.path().join(f);
                std::fs::create_dir_all(p.parent().unwrap())?;
                std::fs::write(&p, f)?;
            }
            FileTree::new_from_dir(
                &Dir::open_ambient_dir(payload.path(), ambient_authority())?,
                None,
            )
        };

        let current = tree_from(&[
            &format!("fedora/{SHIM}"),
            &format!("fedora/{BOOTLOADER_BIN}"),
        ])?;

        // A payload which keeps both binaries is accepted
        let update = tree_from(&[
            &format!("fedora/{SHIM}"),
            &format!("fedora/{BOOTLOADER_BIN}"),
        ])?;
        ensure_boot_binaries(&current, &update, true)?;

        // A payload which drops the shim is refused while booting via shim
        let update = tree_from(&[&format!("fedora/{BOOTLOADER_BIN}")])?;
        let err = ensure_boot_binaries(&current, &update, true)
            .expect_err("dropping the shim must be refused");
        assert!(err.to_string().contains(SHIM));

        // The shim is not required when the system does not boot via it
        ensure_boot_binaries(&current, &update, false)?;

        // A payload which drops the bootloader is always refused
        let update = tree_from(&[&format!("fedora/{SHIM}")])?;
        let err = ensure_boot_binaries(&current, &update, true)
            .expect_err("dropping the bootloader must be refused");
        assert!(err.to_string().contains(BOOTLOADER_BIN));

        // A payload which moves the bootloader to another path is
        // refused, since the firmware and shim resolve it by path
        let update = tree_from(&[
            &format!("fedora/{SHIM}"),
            &format!("redhat/{BOOTLOADER_BIN}"),
        ])?;
        let err = ensure_boot_binaries(&current, &update, true)
            .expect_err("moving the bootloader must be refused");
        assert!(err.to_string().contains(BOOTLOADER_BIN));

        Ok(())
    }

    #[test]
    fn test_install_refuses_payload_missing_bootloader() -> Result<()> {
        let sysroot = tempfile::tempdir()?;
        let utf8_sysroot = Utf8Path::from_path(sysroot.path()).expect("UTF-8");

        // A payload with only the shim component, missing grub2
        let shim = utf8_sysroot.join(EFILIB).join("shim/16.1/EFI/fedora");
        std::fs::create_dir_all(&shim)?;
        std::fs::write(shim.join("shimx64.efi"), "shim")?;
        std::fs::create_dir_all(utf8_sysroot.join(BOOTUPD_UPDATES_DIR))?;
        write_update_metadata(
            utf8_sysroot.as_str(),
            PathBuf::from("EFI.json"),
            &create_test_meta("shim 16.1"),
        )?;

        let dest = tempfile::tempdir()?;
        let err = Efi::default()
            .install(
                sysroot.path().to_str().unwrap(),
                dest.path().to_str().unwrap(),
                None,
                false,
                Bootloader::Grub,
            )
            .expect_err("install must refuse a payload missing the bootloader");
        assert_eq!(
            format!("{err:#}"),
            format!(
                "Cannot install bootloader 'grub': {EFILIB} has no 'grub2' component holding {BOOTLOADER_BIN}; the update payload carries no bootloader"
            )
        );

        Ok(())
    }

    /// Run `install` from `src_root` to a fresh destination without an ESP, so
    /// that it fails at the latest when looking for the ESP.
    fn install_without_esp(src_root: &Utf8Path, bootloader: Bootloader) -> Result<()> {
        let dest = tempfile::tempdir()?;
        let dest = Utf8Path::from_path(dest.path()).expect("UTF-8");
        Efi::default().install(src_root.as_str(), dest.as_str(), None, false, bootloader)?;
        Ok(())
    }

    #[test]
    fn test_install_refuses_bootloader_not_in_payload() -> Result<()> {
        // The legacy update directory, which only carries GRUB
        let sysroot = tempfile::tempdir()?;
        let utf8_sysroot = Utf8Path::from_path(sysroot.path()).expect("UTF-8");
        let vendor = utf8_sysroot.join(BOOTUPD_UPDATES_DIR).join("EFI/centos");
        std::fs::create_dir_all(&vendor)?;
        std::fs::write(vendor.join(SHIM), "shim")?;
        std::fs::write(vendor.join(BOOTLOADER_BIN), "grub")?;
        write_update_metadata(
            utf8_sysroot.as_str(),
            PathBuf::from("EFI.json"),
            &create_test_meta("grub2-efi-x64 1:2.12-58.el10"),
        )?;

        for bootloader in [Bootloader::GrubCC, Bootloader::Systemd] {
            let err = install_without_esp(utf8_sysroot, bootloader)
                .expect_err("install must refuse a bootloader the payload does not carry");
            assert!(
                format!("{err:#}").contains("in usr/lib/bootupd/updates/EFI carries only grub"),
                "{err:#}"
            );
        }
        // GRUB gets past the payload checks.
        let err = install_without_esp(utf8_sysroot, Bootloader::Grub).unwrap_err();
        assert!(format!("{err:#}").contains("no mounted ESP"), "{err:#}");
        Ok(())
    }

    #[test]
    fn test_install_refuses_two_versions_of_bootloader() -> Result<()> {
        let sysroot = tempfile::tempdir()?;
        let utf8_sysroot = Utf8Path::from_path(sysroot.path()).expect("UTF-8");
        std::fs::create_dir_all(utf8_sysroot.join(BOOTUPD_UPDATES_DIR))?;
        write_update_metadata(
            utf8_sysroot.as_str(),
            PathBuf::from("EFI.json"),
            &create_test_meta("grub2 1:2.12-2"),
        )?;
        for version in ["1:2.12-2", "1:2.12-1"] {
            let grub = utf8_sysroot.join(EFILIB).join("grub2").join(version);
            std::fs::create_dir_all(grub.join("EFI/fedora"))?;
            std::fs::write(grub.join("EFI/fedora").join(BOOTLOADER_BIN), version)?;
        }
        let shim = utf8_sysroot.join(EFILIB).join("shim/16.1-1/EFI/fedora");
        std::fs::create_dir_all(&shim)?;
        std::fs::write(shim.join(SHIM), "shim")?;

        let err = install_without_esp(utf8_sysroot, Bootloader::Grub).unwrap_err();
        assert!(
            format!("{err:#}")
                .contains("several versions of its 'grub2' component: 1:2.12-1, 1:2.12-2"),
            "{err:#}"
        );

        // An upgrade can leave the empty directory of the older version.
        let older = utf8_sysroot.join(EFILIB).join("grub2/1:2.12-1/EFI/fedora");
        std::fs::remove_file(older.join(BOOTLOADER_BIN))?;
        let err = install_without_esp(utf8_sysroot, Bootloader::Grub).unwrap_err();
        assert!(format!("{err:#}").contains("no mounted ESP"), "{err:#}");
        Ok(())
    }

    #[test]
    fn test_ensure_one_version() {
        ensure_one_version(Bootloader::Grub, &["1:2.12-9.fc44".into()]).unwrap();
        let versions = ["1:2.12-9.fc44".into(), "1:2.12-10.fc44".into()];
        let err = ensure_one_version(Bootloader::Grub, &versions).unwrap_err();
        // Sorted, as strings
        assert!(
            err.to_string().ends_with(
                "several versions of its 'grub2' component: 1:2.12-10.fc44, 1:2.12-9.fc44"
            ),
            "{err}"
        );
    }

    #[test]
    fn test_install_checks_shim_before_the_esp() -> Result<()> {
        let sysroot = tempfile::tempdir()?;
        let utf8_sysroot = Utf8Path::from_path(sysroot.path()).expect("UTF-8");
        std::fs::create_dir_all(utf8_sysroot.join(BOOTUPD_UPDATES_DIR))?;
        write_update_metadata(
            utf8_sysroot.as_str(),
            PathBuf::from("EFI.json"),
            &create_test_meta("grub2 1:2.12-1"),
        )?;
        let grub = utf8_sysroot.join(EFILIB).join("grub2/1:2.12-1/EFI/fedora");
        std::fs::create_dir_all(&grub)?;
        std::fs::write(grub.join(BOOTLOADER_BIN), "grub")?;
        let shim = |version: &str| utf8_sysroot.join(EFILIB).join("shim").join(version);

        let err = install_without_esp(utf8_sysroot, Bootloader::Grub).unwrap_err();
        assert!(format!("{err:#}").contains("Failed to find"), "{err:#}");

        for version in ["16.1-1", "16.1-2"] {
            let vendor = shim(version).join("EFI/fedora");
            std::fs::create_dir_all(&vendor)?;
            std::fs::write(vendor.join(SHIM), "shim")?;
        }
        let err = install_without_esp(utf8_sysroot, Bootloader::Grub).unwrap_err();
        let found = ["16.1-1", "16.1-2"].map(|v| shim(v).join("EFI/fedora").join(SHIM).to_string());
        assert!(
            format!("{err:#}").ends_with(&format!(
                "Found multiple {SHIM} in the image: {}",
                found.join(", ")
            )),
            "{err:#}"
        );

        // With one shim, `install` gets to the ESP.
        std::fs::remove_dir_all(shim("16.1-2"))?;
        let err = install_without_esp(utf8_sysroot, Bootloader::Grub).unwrap_err();
        assert!(format!("{err:#}").contains("no mounted ESP"), "{err:#}");
        Ok(())
    }

    /// The shim check before the ESP fails on a payload directory that cannot
    /// be read, while the vendor lookups after it keep skipping such
    /// directories, as in 0.4.0.
    #[test]
    fn test_shim_search_unreadable() -> Result<()> {
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        let shim = root.join(EFILIB).join("shim/1.0-1/EFI/fedora");
        std::fs::create_dir_all(&shim)?;
        std::fs::write(shim.join(SHIM), "shim")?;
        // A directory that cannot be read next to the one shim
        let (padded, long) = unreadable_below(root);
        std::fs::create_dir_all(root.join(EFILIB).join(&long))?;
        let efi = Efi::default();
        let err = efi
            .ensure_shim(&padded)
            .expect_err("an unreadable directory could hide a shim");
        let enametoolong = os_error_text(libc::ENAMETOOLONG);
        assert!(format!("{err:#}").contains(&enametoolong), "{err:#}");
        let vendor = efi.get_efi_vendor(padded.as_std_path())?;
        assert_eq!(vendor, Some("fedora".to_string()));
        Ok(())
    }
}