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
use crate::aleph;
#[cfg(any(target_arch = "x86_64", target_arch = "powerpc64"))]
use crate::bios;
use crate::bootloader::{get_bootloader, Bootloader};
use crate::cli::bootupd::InstallOpts;
use crate::component::{self, ComponentType};
use crate::component::{Component, ValidationResult};
#[cfg(any(
    target_arch = "x86_64",
    target_arch = "aarch64",
    target_arch = "riscv64"
))]
use crate::efi;
use crate::freezethaw::fsfreeze_thaw_cycle;
#[cfg(any(
    target_arch = "x86_64",
    target_arch = "aarch64",
    target_arch = "powerpc64",
    target_arch = "riscv64"
))]
use crate::grubconfigs::{ensure_grub_permissions, GRUB2DIR};
use crate::model::{ComponentStatus, ComponentUpdatable, ContentMetadata, SavedState, Status};
use crate::{ostreeutil, util};
use anyhow::{anyhow, Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use cap_std_ext::dirext::CapStdExtDirExt;
use clap::crate_version;
use fn_error_context::context;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};

use bootc_internal_blockdev::Device;
use cap_std::ambient_authority;
use cap_std::fs::{Dir, Permissions, PermissionsExt};
use cap_std_ext::cap_std;

pub(crate) enum ConfigMode {
    None,
    Static,
    WithUUID,
}

impl ConfigMode {
    pub(crate) fn enabled_with_uuid(&self) -> Option<bool> {
        match self {
            ConfigMode::None => None,
            ConfigMode::Static => Some(false),
            ConfigMode::WithUUID => Some(true),
        }
    }
}

/// Choose the EFI bootloader to install when neither `--bootloader` nor a
/// default bootloader says which, from the update payload in `src_root` and
/// its metadata `meta`, see [`pick_efi_bootloader`].
#[cfg(efi_arch)]
fn choose_efi_bootloader(src_root: &Utf8Path, meta: &ContentMetadata) -> Result<Bootloader> {
    let carried = crate::efi::bootloaders_in_payload(src_root)?;
    let location = crate::efi::payload_location(src_root)?;
    pick_efi_bootloader(&carried, &meta.available_bootloaders(), &location)
}

/// Picks the single bootloader that the EFI update payload carries (`carried`)
/// and its metadata names (`named`). An empty `named` does not narrow the
/// choice. `location` is only for error messages.
///
/// Narrowing the payload's bootloaders to what the metadata names keeps the
/// choice for metadata that was not regenerated after adding a component.
/// Metadata that bootupd 0.4.0 or newer generated for an image without
/// usr/lib/efi names packages such as grub2-efi-x64, and so no bootloader.
#[cfg(efi_arch)]
#[context("Could not determine bootloader. Default bootloader not set")]
fn pick_efi_bootloader(
    carried: &[Bootloader],
    named: &[Bootloader],
    location: &Path,
) -> Result<Bootloader> {
    use crate::efi::bootloader_names;
    let location = location.display();
    if carried.is_empty() {
        anyhow::bail!("The EFI update payload in {location} carries no bootloader");
    }
    let candidates = carried
        .iter()
        .copied()
        .filter(|b| named.is_empty() || named.contains(b))
        .collect::<Vec<_>>();
    if candidates.is_empty() {
        anyhow::bail!(
            "The EFI update payload in {location} carries {}, but its metadata names {}. Pass --bootloader, or regenerate the metadata",
            bootloader_names(carried),
            bootloader_names(named)
        );
    }
    if candidates.len() > 1 {
        anyhow::bail!(
            "Multiple bootloaders found as install candidates: {}. Pass --bootloader, or set a default in the image with `bootupctl backend set-default-bootloader`",
            bootloader_names(&candidates)
        );
    }
    Ok(candidates[0])
}

/// Whether GRUB, which the BIOS component asks for, is the bootloader when
/// the EFI component has no default: when the BIOS component installs
/// (`bios_installs`), or when the EFI payload carries GRUB too (`efi_carries`,
/// `None` without an EFI component with update metadata). Otherwise GRUB would
/// only make the EFI component fail, so its payload decides.
#[cfg(efi_arch)]
fn bios_decides(bios_installs: bool, efi_carries: Option<&[Bootloader]>) -> bool {
    bios_installs || efi_carries.is_none_or(|carried| carried.contains(&Bootloader::Grub))
}

/// The bootloader to install: the one given with `--bootloader`, or
/// else the EFI component's default, or GRUB when the BIOS component is among
/// the targets and [`bios_decides`], or the only one the EFI payload offers,
/// see [`choose_efi_bootloader`]. Without `--bootloader`, a targeted EFI
/// component needs update metadata. `devices` are those to install to.
#[cfg(efi_arch)]
fn install_bootloader(
    opts: &InstallOpts,
    target_components: &[&dyn Component],
    devices: &[Device],
    source_root_dir: &Dir,
) -> Result<Bootloader> {
    Ok(match opts.bootloader {
        // CLI overrides anything else
        Some(b) => b,
        None => {
            let mut efi_default = None;
            let mut efi_component_update = None;
            let mut bios_default = None;
            let mut bios_component = None;

            for &c in target_components {
                match c.component_type() {
                    ComponentType::Bios => {
                        bios_default = Some(Bootloader::Grub);
                        bios_component = Some(c);
                    }
                    ComponentType::Efi => {
                        efi_default = c.get_default_bootloader(source_root_dir)?;

                        if efi_default.is_none() {
                            // We don't want to filter any bootloader
                            efi_component_update = c.get_component_update(source_root_dir, None)?;
                        }
                    }
                }
            }

            match (bios_default, efi_default) {
                // EFI bootloader takes precedence
                // Take the following example
                //  - BIOS default = Grub (always)
                //  - EFI default = GrubCC
                //
                //  We can't install GrubCC for BIOS as it's not supported
                //  So we just default to installing GrubCC
                (_, Some(eb)) => eb,
                (Some(bb), None) => {
                    let src_root = Utf8Path::new(&opts.src_root);
                    let efi_carries = efi_component_update
                        .as_ref()
                        .map(|_| crate::efi::bootloaders_in_payload(src_root))
                        .transpose()?;
                    // Whether the BIOS component installs, as
                    // components_to_install() decides, matters only if the
                    // EFI payload lacks GRUB, so only then read its metadata.
                    let efi_lacks_grub = efi_carries
                        .as_deref()
                        .is_some_and(|carried| !carried.contains(&Bootloader::Grub));
                    let bios_installs = match bios_component {
                        Some(bios) if efi_lacks_grub && !devices.is_empty() => bios
                            .query_update(source_root_dir, Bootloader::Grub)?
                            .is_some(),
                        _ => false,
                    };
                    match efi_component_update {
                        Some(meta) if !bios_decides(bios_installs, efi_carries.as_deref()) => {
                            choose_efi_bootloader(src_root, &meta)?
                        }
                        _ => bb,
                    }
                }

                // We still can get the bootloader from the EFI update payload
                // If there's only ONE bootloader to choose from, then that's the
                // one to be installed
                (None, None) => {
                    let Some(efi_component_update) = efi_component_update else {
                        anyhow::bail!("Could not determine bootloader. Default bootloader not set")
                    };

                    choose_efi_bootloader(Utf8Path::new(&opts.src_root), &efi_component_update)?
                }
            }
        }
    })
}

/// The `targets` that `install` installs `bootloader` for, in order, after
/// checking each one's update payload in `src_root`, so that a payload one of
/// them refuses fails before any is installed. BIOS is skipped without
/// `devices`, and any component that does not support `bootloader` or has no
/// update metadata.
fn components_to_install<'a>(
    targets: &[&'a dyn Component],
    devices: &[Device],
    bootloader: Bootloader,
    src_root: &str,
    source_root_dir: &Dir,
) -> Result<Vec<&'a dyn Component>> {
    let mut components = Vec::new();
    for &component in targets {
        // skip for BIOS if no devices specified
        if component.component_type() == ComponentType::Bios && devices.is_empty() {
            println!(
                "Skip installing component {} without target device",
                component.name()
            );
            continue;
        }

        if !component.is_bootloader_supported(bootloader) {
            println!(
                "Skip installing component {} as it does not support bootloader {bootloader}",
                component.name()
            );
            continue;
        }

        // skip components that don't have an update metadata
        if component
            .query_update(source_root_dir, bootloader)?
            .is_none()
        {
            println!(
                "Skip installing component {} without update metadata",
                component.name()
            );
            continue;
        }
        components.push(component);
    }
    for component in &components {
        component
            .check_payload(src_root, bootloader)
            .with_context(|| format!("installing component {}", component.name()))?;
    }
    Ok(components)
}

pub(crate) fn install(opts: &InstallOpts, devices: &[Device], configs: ConfigMode) -> Result<()> {
    let all_components = get_components_impl(opts.auto);

    if all_components.is_empty() {
        println!("No components available for this platform.");
        return Ok(());
    }

    let source_root_dir = Dir::open_ambient_dir(&opts.src_root, ambient_authority())
        .context("Opening source root")?;

    let target_components = if let Some(target_components) = &opts.components {
        // Checked by CLI parser
        assert!(!opts.auto);
        target_components
            .iter()
            .map(|name| {
                all_components
                    .get(name.as_str())
                    .map(|c| c.as_ref())
                    .ok_or_else(|| anyhow!("Unknown component: {name}"))
            })
            .collect::<Result<Vec<_>>>()?
    } else {
        all_components.values().map(|c| c.as_ref()).collect()
    };

    if target_components.is_empty() && !opts.auto {
        anyhow::bail!("No components specified");
    }

    log::debug!(
        "Auto: {}, Target components: {:?}",
        opts.auto,
        target_components
            .iter()
            .map(|c| c.name())
            .collect::<Vec<_>>()
    );

    let has_efi_component = target_components
        .iter()
        .any(|c| c.component_type() == ComponentType::Efi);

    // SavedState needs to be per component
    // Consider this scenario:
    // - Grub installed (statefile in /sysroot/boot)
    // - Re-install attempted with GrubCC
    //
    // So we can't just check statefile based on the determined bootloader
    // We need to check all cases
    for b in Bootloader::iter() {
        if !has_efi_component && b != Bootloader::Grub {
            log::debug!("Skipping bootloader {b} as there's no EFI component");
            continue;
        }

        SavedState::ensure_not_present(&opts.dest_root, b)
            .context("failed to install, invalid re-install attempted")?;
    }

    #[cfg(efi_arch)]
    let bootloader = install_bootloader(opts, &target_components, devices, &source_root_dir)?;

    #[cfg(not(efi_arch))]
    let bootloader = Bootloader::Grub;

    let components = components_to_install(
        &target_components,
        devices,
        bootloader,
        &opts.src_root,
        &source_root_dir,
    )?;

    let mut state = SavedState::default();
    let mut installed_efi_vendor = None;

    for &component in components.iter() {
        // Determine which devices to install to. For EFI, filter to only
        // devices that have an ESP partition.
        let devices_to_install: Vec<Option<&Device>> = if devices.is_empty() {
            // No devices specified: install once with auto-detection (None).
            vec![None]
        } else if component.component_type() == ComponentType::Efi {
            // For EFI, only install to devices that have an ESP partition.
            let esp_devices: Vec<&Device> = devices
                .iter()
                .filter(|dev| match dev.find_partition_of_esp() {
                    Ok(_) => true,
                    Err(e) => {
                        log::warn!("Skipping device {} for EFI: {:#}", dev.path(), e);
                        false
                    }
                })
                .collect();
            if esp_devices.is_empty() {
                // No devices had a detectable ESP partition. This can happen with
                // loopback devices or other setups where partition scanning fails.
                // Fall back to auto-detection — the EFI component will look for
                // an already-mounted ESP at the destination.
                log::info!(
                    "No ESP partitions detected on specified devices; \
                     falling back to mounted ESP detection"
                );
                vec![None]
            } else {
                esp_devices.into_iter().map(Some).collect()
            }
        } else {
            devices.iter().map(|dev| Some(dev)).collect()
        };

        for device in &devices_to_install {
            let device_desc = device.map_or("(auto)".to_string(), |d| d.path());
            let meta = component
                .install(
                    &opts.src_root,
                    &opts.dest_root,
                    *device,
                    opts.update_firmware,
                    bootloader,
                )
                .with_context(|| {
                    format!(
                        "installing component {} to device {}",
                        component.name(),
                        device_desc,
                    )
                })?;
            log::info!(
                "Installed {} {} to {}",
                component.name(),
                meta.meta.version,
                device_desc,
            );
            // State is tracked per-component, not per-device. The metadata
            // (version, filetree, etc.) is identical across all devices, so we
            // only need to record it once. Updates and validation discover all
            // colocated devices at runtime (e.g. via find_colocated_esps()).
            if !state.installed.contains_key(component.name()) {
                state.installed.insert(component.name().into(), meta);
            }
            // Yes this is a hack...the Component thing just turns out to be too generic.
            if installed_efi_vendor.is_none() {
                if let Some(vendor) = component.get_efi_vendor(Path::new(&opts.src_root))? {
                    installed_efi_vendor = Some(vendor);
                }
            }
        }
    }
    let sysroot = &Dir::open_ambient_dir(&opts.dest_root, ambient_authority())?;

    #[cfg(any(
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "powerpc64",
        target_arch = "riscv64"
    ))]
    if bootloader == Bootloader::Grub {
        match configs.enabled_with_uuid() {
            Some(uuid) => {
                let meta = get_static_config_meta()?;
                state.static_configs = Some(meta);

                let mut esp_dir = None;

                #[cfg(efi_arch)]
                {
                    for c in &target_components {
                        use crate::efi::Efi;

                        if let Some(efi) = c.as_any().downcast_ref::<Efi>() {
                            let mounted_esp_path = efi.get_esp_mountpoint();
                            let mounted_esp_path = mounted_esp_path.as_ref().ok_or_else(|| {
                                anyhow!("Mounted ESP not found to install static grub config")
                            })?;

                            esp_dir = Some(
                                Dir::open_ambient_dir(mounted_esp_path, ambient_authority())
                                    .context("Opening mounted ESP dir")?,
                            );

                            break;
                        }
                    }
                }

                crate::grubconfigs::install(
                    sysroot,
                    Some(&source_root_dir),
                    installed_efi_vendor.as_deref(),
                    uuid,
                    esp_dir.as_ref(),
                )?;
            }
            // On other architectures, assume that there's nothing to do.
            None => {}
        }
    }

    // Unmount the ESP, etc.
    drop(target_components);

    let mut state_guard = SavedState::unlocked(opts.dest_root.clone().into(), sysroot.try_clone()?)
        .context("failed to acquire write lock")?;
    state_guard
        .update_state(&state, bootloader)
        .context("failed to update state")?;

    Ok(())
}

#[context("Get static config metadata")]
fn get_static_config_meta() -> Result<ContentMetadata> {
    let self_bin_meta = std::fs::metadata("/proc/self/exe").context("Querying self meta")?;
    let self_meta = ContentMetadata {
        timestamp: self_bin_meta.modified()?.into(),
        version: crate_version!().into(),
        versions: None,

        #[cfg(efi_arch)]
        default_bootloader: None,
    };
    Ok(self_meta)
}

type Components = BTreeMap<&'static str, Box<dyn Component>>;

#[allow(clippy::box_default)]
/// Return the set of known components; if `auto` is specified then the system
/// filters to the target booted state.
pub(crate) fn get_components_impl(_auto: bool) -> Components {
    #[cfg(not(target_arch = "s390x"))]
    let mut components = BTreeMap::new();

    #[cfg(target_arch = "s390x")]
    let components = BTreeMap::new();

    fn insert_component(components: &mut Components, component: Box<dyn Component>) {
        components.insert(component.name(), component);
    }

    #[cfg(target_arch = "x86_64")]
    {
        if _auto {
            let is_efi_booted = crate::efi::is_efi_booted().unwrap();
            log::info!(
                "System boot method: {}",
                if is_efi_booted { "EFI" } else { "BIOS" }
            );
            if is_efi_booted {
                insert_component(&mut components, Box::new(efi::Efi::default()));
            } else {
                insert_component(&mut components, Box::new(bios::Bios::default()));
            }
        } else {
            insert_component(&mut components, Box::new(bios::Bios::default()));
            insert_component(&mut components, Box::new(efi::Efi::default()));
        }
    }
    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
    insert_component(&mut components, Box::new(efi::Efi::default()));

    #[cfg(target_arch = "powerpc64")]
    insert_component(&mut components, Box::new(bios::Bios::default()));

    components
}

pub(crate) fn get_components() -> Components {
    get_components_impl(false)
}

pub(crate) fn generate_update_metadata(sysroot_path: &str) -> Result<()> {
    // create bootupd update dir which will save component metadata files for both components
    let updates_dir = Path::new(sysroot_path).join(crate::model::BOOTUPD_UPDATES_DIR);

    std::fs::create_dir_all(&updates_dir)
        .with_context(|| format!("Failed to create updates dir {:?}", &updates_dir))?;

    for component in get_components().values() {
        if let Some(v) = component.generate_update_metadata(sysroot_path)? {
            println!(
                "Generated update layout for {}: {}",
                component.name(),
                v.version,
            );
        } else {
            println!(
                "Generating update layout for {} was not possible, skipping.",
                component.name(),
            );
        }
    }

    Ok(())
}

/// Return value from daemon → client for component update
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ComponentUpdateResult {
    AtLatestVersion,
    Updated {
        previous: ContentMetadata,
        interrupted: Option<ContentMetadata>,
        new: ContentMetadata,
    },
}

fn ensure_writable_boot() -> Result<()> {
    util::ensure_writable_mount("/boot")
}

/// daemon implementation of component update
pub(crate) fn update(name: &str, rootcxt: &RootContext) -> Result<ComponentUpdateResult> {
    let bootloader = get_bootloader()?;

    let mut state = SavedState::load_from_disk("/", Some(bootloader))?.unwrap_or_default();
    let component = component::new_from_name(name)?;
    let inst = if let Some(inst) = state.installed.get(name) {
        inst.clone()
    } else {
        anyhow::bail!("Component {} is not installed", name);
    };
    let sysroot = &rootcxt.sysroot;
    let (update, updatable) = component
        .query_updatable(rootcxt.as_sysroot(), &inst, bootloader)
        .with_context(|| format!("Failed to check {} for updates", name))?;
    let update = match (update, &updatable) {
        (Some(p), ComponentUpdatable::Upgradable) => p,
        (Some(_), ComponentUpdatable::NoUpdateAvailable) => {
            anyhow::bail!("update metadata exists but the component reports NoUpdateAvailable");
        }
        // No update metadata, only an error when the active boot method
        // requires it
        (None, _) => {
            log::debug!("Skipping update, updatable: {updatable:?}");
            component.query_requires_update(sysroot)?;
            return Ok(ComponentUpdateResult::AtLatestVersion);
        }
        // The content already matches. Another client completed this
        // update between our status query and this one.
        (Some(_), ComponentUpdatable::AtLatestVersion) => {
            log::debug!("Skipping update, updatable: {updatable:?}");
            return Ok(ComponentUpdateResult::AtLatestVersion);
        }
    };

    ensure_writable_boot()?;
    // Verify the permissions of grub files are 0600
    #[cfg(any(
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "powerpc64",
        target_arch = "riscv64"
    ))]
    {
        if bootloader == Bootloader::Grub {
            let grub2dir = &sysroot
                .open_dir(format!("boot/{GRUB2DIR}"))
                .context("Opening /boot/grub2")?;
            ensure_grub_permissions(grub2dir)?;
        }
    }

    let mut pending_container = state.pending.take().unwrap_or_default();
    let interrupted = pending_container.get(component.name()).cloned();
    pending_container.insert(component.name().into(), update.clone());
    let sysroot = sysroot.try_clone()?;
    let mut state_guard = SavedState::acquire_write_lock(rootcxt.path.clone(), sysroot)
        .context("Failed to acquire write lock")?;
    state_guard
        .update_state(&state, bootloader)
        .context("Failed to update state")?;

    let newinst = component
        .run_update(rootcxt, &inst)
        .with_context(|| format!("Failed to update {}", component.name()))?;
    state.installed.insert(component.name().into(), newinst);
    pending_container.remove(component.name());
    state_guard.update_state(&state, bootloader)?;

    Ok(ComponentUpdateResult::Updated {
        previous: inst.meta,
        interrupted,
        new: update.clone(),
    })
}

/// daemon implementation of component adoption
pub(crate) fn adopt_and_update(
    name: &str,
    rootcxt: &RootContext,
    with_static_config: bool,
) -> Result<Option<ContentMetadata>> {
    let bootloader = get_bootloader()?;
    let sysroot = &rootcxt.sysroot;
    let mut state = SavedState::load_from_disk("/", Some(bootloader))?.unwrap_or_default();
    let component = component::new_from_name(name)?;
    if state.installed.contains_key(name) {
        anyhow::bail!("Component {} is already installed", name);
    };

    ensure_writable_boot()?;
    // Verify the permissions of grub files are 0600
    #[cfg(any(
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "powerpc64",
        target_arch = "riscv64"
    ))]
    {
        if bootloader == Bootloader::Grub {
            let grub2dir = &sysroot
                .open_dir(format!("boot/{GRUB2DIR}"))
                .context("Opening /boot/grub2")?;
            ensure_grub_permissions(grub2dir)?;
        }
    }

    let Some(update) = component.query_update(sysroot, bootloader)? else {
        anyhow::bail!("Component {} has no available update", name);
    };

    let sysroot = sysroot.try_clone()?;
    let mut state_guard = SavedState::acquire_write_lock(rootcxt.path.clone(), sysroot)
        .context("Failed to acquire write lock")?;

    let inst = component
        .adopt_update(&rootcxt, &update, with_static_config, bootloader)
        .context("Failed adopt and update")?;
    if let Some(inst) = inst {
        state.installed.insert(component.name().into(), inst);
        // Set static_configs metadata and save
        if with_static_config && state.static_configs.is_none() {
            let meta = get_static_config_meta()?;
            state.static_configs = Some(meta);
            // Set bootloader to none
            ostreeutil::set_ostree_bootloader("none")?;

            println!("Static GRUB configuration has been adopted successfully.");
        }
        state_guard.update_state(&state, bootloader)?;
        return Ok(Some(update));
    } else {
        // Nothing adopted, skip
        log::info!("Component '{}' skipped adoption", component.name());
        return Ok(None);
    }
}

/// Get the block device backing the current root by trying `/boot` first,
/// then falling back to `/sysroot`. This avoids issues with virtual
/// filesystems like composefs that are mounted on `/`.
#[context("Finding block device from boot or sysroot")]
pub(crate) fn list_dev_current_root() -> Result<Device> {
    let auth = cap_std::ambient_authority();
    for path in ["/boot", "/sysroot"] {
        if let Ok(dir) = Dir::open_ambient_dir(path, auth) {
            if let Ok(dev) = bootc_internal_blockdev::list_dev_by_dir(&dir) {
                return Ok(dev);
            }
        }
    }
    anyhow::bail!("Failed to find block device from /boot or /sysroot")
}

/// daemon implementation of component validate
pub(crate) fn validate(name: &str) -> Result<ValidationResult> {
    let state = SavedState::load_from_disk("/", Some(get_bootloader()?))?.unwrap_or_default();
    let component = component::new_from_name(name)?;
    let Some(inst) = state.installed.get(name) else {
        anyhow::bail!("Component {} is not installed", name);
    };
    let device = list_dev_current_root()?;
    component.validate(inst, &device)
}

/// Impl for bootupctl status
/// This function assumes we're not running in a container
pub(crate) fn status() -> Result<Status> {
    let mut ret: Status = Default::default();
    let mut known_components = get_components();
    let path_root = Utf8Path::new("/");
    let root = Dir::open_ambient_dir(path_root, ambient_authority())?;

    // Populate aleph version
    ret.aleph_version =
        aleph::get_aleph_version(path_root.as_std_path())?.and_then(|a| a.aleph.version);

    // Populate boot method
    #[cfg(any(
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "riscv64"
    ))]
    {
        ret.boot_method = Some(if efi::is_efi_booted()? { "EFI" } else { "BIOS" }.into());
    }

    let bootloader = get_bootloader()?;
    let state = SavedState::load_from_disk("/", Some(bootloader))?;

    if let Some(state) = state {
        let sysroot = Sysroot {
            dir: &root,
            path: path_root,
        };
        for (name, ic) in state.installed.iter() {
            log::trace!("Gathering status for installed component: {}", name);
            let component = known_components
                .remove(name.as_str())
                .ok_or_else(|| anyhow!("Unknown component installed: {}", name))?;
            let component = component.as_ref();
            let interrupted = state.pending.as_ref().and_then(|p| p.get(name.as_str()));
            let (update, updatable) = component
                .query_updatable(sysroot, &ic, bootloader)
                .with_context(|| format!("Querying update status for component {}", name))?;
            let adopted_from = ic.adopted_from.clone();
            ret.components.insert(
                name.to_string(),
                ComponentStatus {
                    installed: ic.meta.clone(),
                    interrupted: interrupted.cloned(),
                    update,
                    updatable,
                    adopted_from,
                },
            );
        }
    } else {
        log::trace!("No saved state");
    }

    // Process the remaining components not installed
    log::trace!("Remaining known components: {}", known_components.len());
    for (name, _) in known_components {
        // To determine if not-installed components can be adopted:
        //
        // `query_adopt_state()` checks for existing installation state,
        // such as a `version` in an aleph file (e.g. `.coreos-aleph-version.json` or `.bootc-aleph.json`),
        // or the presence of `/ostree/deploy`.
        //
        // `component.query_adopt()` performs additional checks,
        // including hardware/device requirements.
        // For example, it will skip BIOS adoption if the system is booted via EFI
        // and lacks a BIOS_BOOT partition.
        //
        // Once a component is determined to be adoptable, it is added to the
        // adoptable list, and adoption proceeds automatically.
        //
        // Therefore, calling `query_adopt_state()` alone is sufficient.
        if let Some(adopt_ver) = component::query_adopt_state()? {
            let component = component::new_from_name(&name)?;
            // Skip if the update metadata could not be found
            if component.query_update(&root, bootloader)?.is_none() {
                continue;
            };
            ret.adoptable.insert(name.to_string(), adopt_ver);
        } else {
            log::trace!("Not adoptable: {}", name);
        }
    }

    Ok(ret)
}

pub(crate) fn print_status_avail(status: &Status) -> Result<()> {
    let mut avail = Vec::new();
    for (name, component) in status.components.iter() {
        if let ComponentUpdatable::Upgradable = component.updatable {
            avail.push(name.as_str());
        }
    }
    for (name, adoptable) in status.adoptable.iter() {
        if adoptable.confident {
            avail.push(name.as_str());
        }
    }
    if !avail.is_empty() {
        println!("Updates available: {}", avail.join(" "));
    }
    Ok(())
}

pub(crate) fn print_status(status: &Status) -> Result<()> {
    if status.components.is_empty() {
        println!("No components installed.");
    }
    for (name, component) in status.components.iter() {
        println!("Component {}", name);
        println!("  Installed: {}", component.installed.version);

        if let Some(i) = component.interrupted.as_ref() {
            println!(
                "  WARNING: Previous update to {} was interrupted",
                i.version
            );
        }
        let msg = match component.updatable {
            ComponentUpdatable::NoUpdateAvailable => Cow::Borrowed("No update found"),
            ComponentUpdatable::AtLatestVersion => Cow::Borrowed("At latest version"),
            ComponentUpdatable::Upgradable => Cow::Owned(format!(
                "Available: {}",
                component.update.as_ref().expect("update").version
            )),
        };
        println!("  Update: {}", msg);
    }

    if status.adoptable.is_empty() {
        println!("No components are adoptable.");
    }
    for (name, adopt) in status.adoptable.iter() {
        let ver = &adopt.version.version;
        if adopt.confident {
            println!("Detected: {}: {}", name, ver);
        } else {
            println!("Adoptable: {}: {}", name, ver);
        }
    }

    if let Some(aleph_version) = &status.aleph_version {
        println!("Aleph version: {}", aleph_version);
    }

    if let Some(boot_method) = &status.boot_method {
        println!("Boot method: {}", boot_method);
    }

    Ok(())
}

/// A borrowed view of a sysroot, used by the read-only query paths.
///
/// Unlike [`RootContext`], this carries no block device, so
/// callers like `status` avoid requiring device discovery.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Sysroot<'a> {
    pub(crate) dir: &'a Dir,
    pub(crate) path: &'a Utf8Path,
}

pub struct RootContext {
    pub sysroot: Dir,
    pub path: Utf8PathBuf,

    /// The block device backing the root filesystem.
    ///
    /// Used to determine the device to install to for components that need
    /// it, and passed to component update/adoption logic for validation.
    pub device: Device,
}

impl RootContext {
    fn new(sysroot: Dir, path: &str, device: Device) -> Self {
        Self {
            sysroot,
            path: Utf8Path::new(path).into(),
            device,
        }
    }

    /// The sysroot view used by the query paths, which do not touch the
    /// block device.
    pub(crate) fn as_sysroot(&self) -> Sysroot<'_> {
        Sysroot {
            dir: &self.sysroot,
            path: &self.path,
        }
    }
}

/// Initialize parent devices to prepare the update
fn prep_before_update() -> Result<RootContext> {
    let path = "/";
    let sysroot = Dir::open_ambient_dir(path, ambient_authority()).context("Opening root dir")?;
    let device = list_dev_current_root()?;
    Ok(RootContext::new(sysroot, path, device))
}

pub(crate) fn client_run_update() -> Result<()> {
    crate::try_fail_point!("update");
    let rootcxt = prep_before_update()?;
    let status: Status = status()?;
    if status.components.is_empty() && status.adoptable.is_empty() {
        println!("No components installed.");
        return Ok(());
    }
    let mut updated = false;
    for (name, cstatus) in status.components.iter() {
        match cstatus.updatable {
            ComponentUpdatable::Upgradable => {}
            _ => continue,
        };
        match update(name, &rootcxt)? {
            ComponentUpdateResult::AtLatestVersion => {
                // Shouldn't happen unless we raced with another client
                eprintln!(
                    "warning: Expected update for {}, raced with a different client?",
                    name
                );
                continue;
            }
            ComponentUpdateResult::Updated {
                previous,
                interrupted,
                new,
            } => {
                if let Some(i) = interrupted {
                    eprintln!(
                        "warning: Continued from previous interrupted update: {}",
                        i.version,
                    );
                }
                println!("Previous {}: {}", name, previous.version);
                println!("Updated {}: {}", name, new.version);
            }
        }
        updated = true;
    }
    for (name, adoptable) in status.adoptable.iter() {
        if adoptable.confident {
            if let Some(r) = adopt_and_update(name, &rootcxt, false)? {
                println!("Adopted and updated: {}: {}", name, r.version);
                updated = true;
            }
        } else {
            println!("Component {} requires explicit adopt-and-update", name);
        }
    }
    if !updated {
        println!("No update available for any component.");
    }
    Ok(())
}

pub(crate) fn client_run_adopt_and_update(with_static_config: bool) -> Result<()> {
    let rootcxt = prep_before_update()?;
    let status: Status = status()?;
    if status.adoptable.is_empty() {
        println!("No components are adoptable.");
    } else {
        for (name, _) in status.adoptable.iter() {
            if let Some(r) = adopt_and_update(name, &rootcxt, with_static_config)? {
                println!("Adopted and updated: {}: {}", name, r.version);
            }
        }
    }
    Ok(())
}

pub(crate) fn client_run_validate() -> Result<()> {
    let status: Status = status()?;
    if status.components.is_empty() {
        println!("No components installed.");
        return Ok(());
    }
    let mut caught_validation_error = false;
    for (name, _) in status.components.iter() {
        match validate(name)? {
            ValidationResult::Valid => {
                println!("Validated: {}", name);
            }
            ValidationResult::Skip => {
                println!("Skipped: {}", name);
            }
            ValidationResult::Errors(errs) => {
                for err in errs {
                    eprintln!("{}", err);
                }
                caught_validation_error = true;
            }
        }
    }
    if caught_validation_error {
        anyhow::bail!("Caught validation errors");
    }
    Ok(())
}

#[context("Migrating to a static GRUB config")]
pub(crate) fn client_run_migrate_static_grub_config() -> Result<()> {
    // Did we already complete the migration?
    // We need to migrate if bootloader is not none (or not set)
    if let Some(bootloader) = ostreeutil::get_ostree_bootloader()? {
        if bootloader == "none" {
            println!("Already using a static GRUB config");
            return Ok(());
        }
        println!(
            "ostree repo 'sysroot.bootloader' config option is currently set to: '{}'",
            bootloader
        );
    } else {
        println!("ostree repo 'sysroot.bootloader' config option is not set yet");
    }

    // Remount /boot read write just for this unit (we are called in a slave mount namespace by systemd)
    ensure_writable_boot()?;

    let grub_config_dir = PathBuf::from("/boot/grub2");
    let dirfd = Dir::open_ambient_dir(&grub_config_dir, ambient_authority())
        .context("Opening /boot/grub2")?;

    // We mark the bootloader as BLS capable to disable the ostree-grub2 logic.
    // We can do that as we know that we are run after the bootloader has been
    // updated and all recent GRUB2 versions support reading BLS configs.
    // Ignore errors as this is not critical. This is a safety net if a user
    // manually overwrites the (soon) static GRUB config by calling `grub2-mkconfig`.
    // We need this until we can rely on ostree-grub2 being removed from the image.
    println!("Marking bootloader as BLS capable...");
    _ = File::create("/boot/grub2/.grub2-blscfg-supported");

    // Migrate /boot/grub2/grub.cfg to a static GRUB config if it is a symlink
    let grub_config_filename = PathBuf::from("/boot/grub2/grub.cfg");
    match dirfd.read_link("grub.cfg") {
        Err(_) => {
            println!(
                "'{}' is not a symlink, nothing to migrate",
                grub_config_filename.display()
            );
        }
        Ok(path) => {
            println!("Migrating to a static GRUB config...");

            // Resolve symlink location
            let mut current_config = grub_config_dir.clone();
            current_config.push(path);

            // Backup the current GRUB config which is hopefully working right now
            let backup_config = PathBuf::from("/boot/grub2/grub.cfg.backup");
            println!(
                "Creating a backup of the current GRUB config '{}' in '{}'...",
                current_config.display(),
                backup_config.display()
            );
            fs::copy(&current_config, &backup_config).context("Failed to backup GRUB config")?;

            // Read the current config, strip the ostree generated GRUB entries and
            // write the result to a temporary file
            println!("Stripping ostree generated entries from GRUB config...");
            let stripped_config = "grub.cfg.stripped";
            let current_config_file =
                File::open(current_config).context("Could not open current GRUB config")?;
            let content = BufReader::new(current_config_file);

            strip_grub_config_file(content, &dirfd, stripped_config)?;

            // Atomically replace the symlink
            dirfd
                .rename(stripped_config, &dirfd, "grub.cfg")
                .context("Failed to replace symlink with current GRUB config")?;

            fsfreeze_thaw_cycle(dirfd.reopen_as_ownedfd()?)?;

            println!("GRUB config symlink successfully replaced with the current config");
        }
    };

    println!("Setting 'sysroot.bootloader' to 'none' in ostree repo config...");
    ostreeutil::set_ostree_bootloader("none")?;

    println!("Static GRUB config migration completed successfully");
    Ok(())
}

/// Writes a stripped GRUB config to `stripped_config_name`, removing lines between
/// `### BEGIN /etc/grub.d/15_ostree ###` and `### END /etc/grub.d/15_ostree ###`.
fn strip_grub_config_file(
    current_config_content: impl BufRead,
    dirfd: &Dir,
    stripped_config_name: &str,
) -> Result<()> {
    let mut writer = vec![];

    let mut skip = false;
    for line in current_config_content.lines() {
        let line = line.context("Failed to read line from GRUB config")?;
        if line == "### END /etc/grub.d/15_ostree ###" {
            skip = false;
            continue;
        }
        if skip {
            continue;
        }
        if line == "### BEGIN /etc/grub.d/15_ostree ###" {
            skip = true;
            continue;
        }
        writer
            .write_all(line.as_bytes())
            .context("Failed to write stripped GRUB config")?;
        writer
            .write_all(b"\n")
            .context("Failed to write stripped GRUB config")?;
    }

    // mode = -rw------- (600)
    dirfd
        .atomic_write_with_perms(stripped_config_name, writer, Permissions::from_mode(0o600))
        .with_context(|| format!("Writing to {stripped_config_name}"))?;

    Ok(())
}

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

    #[test]
    fn test_failpoint_update() {
        let guard = fail::FailScenario::setup();
        fail::cfg("update", "return").unwrap();
        let r = client_run_update();
        assert_eq!(r.is_err(), true);
        guard.teardown();
    }

    #[test]
    fn test_strip_grub_config_file() -> Result<()> {
        let root: &tempfile::TempDir = &tempfile::tempdir()?;
        let root_path = root.path();
        let rootd = Dir::open_ambient_dir(root_path, ambient_authority())?;
        let stripped_config = "stripped";
        let content = r"
### BEGIN /etc/grub.d/10_linux ###

### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/15_ostree ###
menuentry 'Red Hat Enterprise Linux CoreOS 4 (ostree)' --class gnu-linux --class gnu --class os --unrestricted 'ostree-0-a92522f9-74dc-456a-ae0c-05ba22bca976' {
load_video
set gfxpayload=keep
insmod gzio
insmod part_gpt
insmod ext2
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root  a92522f9-74dc-456a-ae0c-05ba22bca976
else
  search --no-floppy --fs-uuid --set=root a92522f9-74dc-456a-ae0c-05ba22bca976
fi
linuxefi /ostree/rhcos-bf3b382/vmlinuz console=tty0 console=ttyS0,115200n8 rootflags=defaults,prjquota rw $ignition_firstboot root=UUID=cbac8cdc
initrdefi /ostree/rhcos-bf3b382/initramfs.img
}
### END /etc/grub.d/15_ostree ###

### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###";

        strip_grub_config_file(
            BufReader::new(std::io::Cursor::new(content)),
            &rootd,
            stripped_config,
        )?;
        let stripped_content = rootd.read_to_string(stripped_config)?;
        let expected = r"
### BEGIN /etc/grub.d/10_linux ###

### END /etc/grub.d/10_linux ###


### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###
";
        assert_eq!(expected, stripped_content);
        Ok(())
    }

    #[test]
    #[cfg(efi_arch)]
    fn test_pick_efi_bootloader() {
        use Bootloader::{Grub, GrubCC, Systemd};
        let location = Path::new("usr/lib/efi");
        // What the payload carries, what the metadata names, and the choice
        let cases: &[(&[Bootloader], &[Bootloader], Option<Bootloader>)] = &[
            // An image without usr/lib/efi, whose metadata names packages
            (&[Grub], &[], Some(Grub)),
            (&[Grub], &[Grub], Some(Grub)),
            (&[GrubCC], &[GrubCC], Some(GrubCC)),
            (&[Grub, Systemd], &[Grub, Systemd], None),
            // Metadata not regenerated after adding systemd-boot,
            (&[Grub, Systemd], &[Grub], Some(Grub)),
            // or after removing it
            (&[Grub], &[Grub, Systemd], Some(Grub)),
            (&[], &[], None),
            (&[Systemd], &[Grub], None),
        ];
        for (carried, named, expected) in cases {
            let chosen = pick_efi_bootloader(carried, named, location);
            assert_eq!(
                chosen.as_ref().ok(),
                expected.as_ref(),
                "{carried:?} {named:?}: {chosen:?}"
            );
        }
        let message = |carried: &[Bootloader], named: &[Bootloader]| {
            format!(
                "{:#}",
                pick_efi_bootloader(carried, named, location).unwrap_err()
            )
        };
        let several = message(&[Grub, Systemd], &[Grub, Systemd]);
        assert!(
            several.contains("candidates: grub, systemd. Pass --bootloader, or set a default"),
            "{several}"
        );
        let none = message(&[], &[]);
        assert!(
            none.ends_with("in usr/lib/efi carries no bootloader"),
            "{none}"
        );
        let other = message(&[Systemd], &[Grub]);
        assert!(
            other.contains("carries systemd, but its metadata names grub. Pass --bootloader"),
            "{other}"
        );
    }

    /// Metadata of an image without usr/lib/efi, as bootupd 0.4.0 writes it
    #[cfg(efi_arch)]
    const PACKAGE_METADATA: &str = r#"{"timestamp":"2026-11-16T17:14:09Z","version":"grub2-efi-x64 1:2.12-58.el10,shim-x64 16.1-1.el10","versions":[{"name":"grub2-efi-x64","evr":"1:2.12-58.el10"},{"name":"shim-x64","evr":"16.1-1.el10"}],"default-bootloader":null}"#;

    /// An empty file at `path` in `root`
    #[cfg(efi_arch)]
    fn write_empty(root: &Utf8Path, path: &str) -> Result<()> {
        let path = root.join(path);
        std::fs::create_dir_all(path.parent().unwrap())?;
        std::fs::write(path, "")?;
        Ok(())
    }

    /// The choice from a payload and its metadata as bootupd writes them
    #[test]
    #[cfg(efi_arch)]
    fn test_choose_efi_bootloader() -> Result<()> {
        use crate::efi::{BOOTLOADER_BIN, SHIM};
        let packages: ContentMetadata = serde_json::from_str(PACKAGE_METADATA)?;
        // As CentOS Stream 10's bootupd 0.2.35 wrote it, naming components
        let stream10: ContentMetadata = serde_json::from_str(
            r#"{"timestamp":"2026-10-19T21:00:56Z","version":"grub2-efi-x64-1:2.12-58.el10.x86_64,shim-x64-16.1-1.el10.x86_64","versions":[{"name":"grub2","rpm_evr":"1:2.12-58.el10"},{"name":"shim","rpm_evr":"16.1-1.el10"}]}"#,
        )?;
        // As written for usr/lib/efi before systemd-boot was added
        let components: ContentMetadata = serde_json::from_str(
            r#"{"timestamp":"2026-11-16T17:14:09Z","version":"grub2 1:2.12-58.fc45,shim 16.1-7","versions":[{"name":"grub2","evr":"1:2.12-58.fc45"},{"name":"shim","evr":"16.1-7"}],"default-bootloader":null}"#,
        )?;

        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        write_empty(root, &format!("usr/lib/bootupd/updates/EFI/centos/{SHIM}"))?;
        let err = choose_efi_bootloader(root, &packages).unwrap_err();
        assert_eq!(
            format!("{err:#}"),
            "Could not determine bootloader. Default bootloader not set: The EFI update payload in usr/lib/bootupd/updates/EFI carries no bootloader"
        );
        write_empty(
            root,
            &format!("usr/lib/bootupd/updates/EFI/centos/{BOOTLOADER_BIN}"),
        )?;
        assert_eq!(choose_efi_bootloader(root, &packages)?, Bootloader::Grub);
        assert_eq!(choose_efi_bootloader(root, &stream10)?, Bootloader::Grub);

        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        for (component, binary) in [
            ("grub2", BOOTLOADER_BIN),
            ("shim", SHIM),
            ("systemd-boot", BOOTLOADER_BIN),
        ] {
            write_empty(
                root,
                &format!("usr/lib/efi/{component}/1.0-1/EFI/fedora/{binary}"),
            )?;
        }
        assert_eq!(choose_efi_bootloader(root, &components)?, Bootloader::Grub);

        // Metadata naming two versions of grub2, which the payload lacks
        let two_grub2: ContentMetadata = serde_json::from_str(
            r#"{"timestamp":"2026-11-16T17:14:09Z","version":"grub2 1:2.12-56.fc44,grub2 1:2.12-58.fc44,shim 16.1-7","versions":[{"name":"grub2","evr":"1:2.12-56.fc44"},{"name":"grub2","evr":"1:2.12-58.fc44"},{"name":"shim","evr":"16.1-7"}],"default-bootloader":null}"#,
        )?;
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        for (component, binary) in [("shim", SHIM), ("systemd-boot", BOOTLOADER_BIN)] {
            write_empty(
                root,
                &format!("usr/lib/efi/{component}/1.0-1/EFI/fedora/{binary}"),
            )?;
        }
        let err = choose_efi_bootloader(root, &two_grub2).unwrap_err();
        assert!(
            format!("{err:#}")
                .ends_with("carries systemd, but its metadata names grub. Pass --bootloader, or regenerate the metadata"),
            "{err:#}"
        );
        Ok(())
    }

    /// A payload a component refuses fails before any component is installed,
    /// even when BIOS, which comes first, could install. BIOS checks for the
    /// grub2-install that it runs from the running system, which the host
    /// running this test may lack.
    #[test]
    #[cfg(efi_arch)]
    fn test_components_to_install() -> Result<()> {
        use crate::efi::{BOOTLOADER_BIN, SHIM};
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        // The legacy update directory with shim, but without GRUB
        write_empty(root, &format!("usr/lib/bootupd/updates/EFI/centos/{SHIM}"))?;
        let updates = root.join("usr/lib/bootupd/updates");
        std::fs::write(updates.join("EFI.json"), PACKAGE_METADATA)?;
        std::fs::write(updates.join("BIOS.json"), PACKAGE_METADATA)?;
        let src_dir = Dir::open_ambient_dir(root, ambient_authority())?;
        let all = get_components();
        let targets = all.values().map(|c| c.as_ref()).collect::<Vec<_>>();
        let device: Device = serde_json::from_value(serde_json::json!({
            "name": "vda",
            "size": 0
        }))?;
        let devices = [device];
        let names = |components: Vec<&dyn Component>| {
            components.iter().map(|c| c.name()).collect::<Vec<_>>()
        };
        let install = |devices: &[Device]| {
            components_to_install(&targets, devices, Bootloader::Grub, root.as_str(), &src_dir)
        };
        // What the BIOS component, on platforms with one, makes of this host
        let bios = all
            .get("BIOS")
            .map(|bios| bios.check_payload(root.as_str(), Bootloader::Grub));

        let Err(err) = install(&devices) else {
            panic!("a payload a component refuses must fail the install");
        };
        let expected = match &bios {
            Some(Err(e)) => format!("installing component BIOS: {e:#}"),
            _ => "installing component EFI: Cannot install bootloader 'grub': the update payload in usr/lib/bootupd/updates/EFI carries no bootloader".into(),
        };
        assert!(format!("{err:#}").starts_with(&expected), "{err:#}");

        write_empty(
            root,
            &format!("usr/lib/bootupd/updates/EFI/centos/{BOOTLOADER_BIN}"),
        )?;
        match &bios {
            Some(Ok(())) => assert_eq!(names(install(&devices)?), ["BIOS", "EFI"]),
            Some(Err(_)) => assert!(install(&devices).is_err(), "BIOS cannot install here"),
            None => assert_eq!(names(install(&devices)?), ["EFI"]),
        }
        // BIOS needs a device to install to, and is not checked without one.
        assert_eq!(names(install(&[])?), ["EFI"]);
        // A component without update metadata is not checked either.
        std::fs::remove_file(updates.join("EFI.json"))?;
        std::fs::remove_file(updates.join(format!("EFI/centos/{BOOTLOADER_BIN}")))?;
        assert_eq!(names(install(&[])?), Vec::<&str>::new());
        Ok(())
    }

    /// A device to install to, for tests that don't look at it
    #[cfg(efi_arch)]
    fn test_device() -> Device {
        serde_json::from_value(serde_json::json!({"name": "vda", "size": 1})).unwrap()
    }

    /// `install`'s choice, from its options, for the EFI component
    #[test]
    #[cfg(efi_arch)]
    fn test_install_bootloader() -> Result<()> {
        use crate::efi::{BOOTLOADER_BIN, SHIM};
        use clap::Parser;
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        for binary in [SHIM, BOOTLOADER_BIN] {
            write_empty(
                root,
                &format!("usr/lib/bootupd/updates/EFI/centos/{binary}"),
            )?;
        }
        std::fs::write(
            root.join("usr/lib/bootupd/updates/EFI.json"),
            PACKAGE_METADATA,
        )?;
        let src_dir = Dir::open_ambient_dir(root, ambient_authority())?;
        let components = get_components();
        let efi = components["EFI"].as_ref();
        let dest = tempfile::tempdir()?;
        let dest = Utf8Path::from_path(dest.path()).unwrap();
        let opts = |root: &Utf8Path, bootloader: &[&str]| {
            let args = ["install", "--src-root", root.as_str(), "--component", "EFI"];
            InstallOpts::try_parse_from(args.iter().chain(bootloader).chain([&dest.as_str()]))
        };
        assert_eq!(
            install_bootloader(&opts(root, &[])?, &[efi], &[], &src_dir)?,
            Bootloader::Grub
        );
        // An explicit --bootloader wins, whether or not the payload carries it.
        let systemd = opts(root, &["--bootloader", "systemd"])?;
        assert_eq!(
            install_bootloader(&systemd, &[efi], &[], &src_dir)?,
            Bootloader::Systemd
        );

        // A payload with two bootloaders needs a default, unless the BIOS
        // component is a target, which installs GRUB.
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        for (component, binary) in [
            ("grub2", BOOTLOADER_BIN),
            ("shim", SHIM),
            ("systemd-boot", BOOTLOADER_BIN),
        ] {
            write_empty(
                root,
                &format!("usr/lib/efi/{component}/1.0-1/EFI/fedora/{binary}"),
            )?;
        }
        let metadata = r#"{"timestamp":"2026-11-16T17:14:09Z","version":"grub2 1.0-1,shim 1.0-1,systemd-boot 1.0-1","versions":[{"name":"grub2","evr":"1.0-1"},{"name":"shim","evr":"1.0-1"},{"name":"systemd-boot","evr":"1.0-1"}],"default-bootloader":null}"#;
        let efi_json = root.join("usr/lib/bootupd/updates/EFI.json");
        std::fs::create_dir_all(efi_json.parent().unwrap())?;
        std::fs::write(&efi_json, metadata)?;
        let src_dir = Dir::open_ambient_dir(root, ambient_authority())?;
        let err = install_bootloader(&opts(root, &[])?, &[efi], &[], &src_dir).unwrap_err();
        assert!(
            format!("{err:#}").contains("Multiple bootloaders"),
            "{err:#}"
        );
        let bios = components.get("BIOS").map(|c| c.as_ref());
        if let Some(bios) = bios {
            assert_eq!(
                install_bootloader(&opts(root, &[])?, &[bios, efi], &[], &src_dir)?,
                Bootloader::Grub
            );
        }
        // The EFI default wins, even over the BIOS component.
        std::fs::write(
            &efi_json,
            metadata.replace(
                r#""default-bootloader":null"#,
                r#""default-bootloader":"Systemd""#,
            ),
        )?;
        assert_eq!(
            install_bootloader(&opts(root, &[])?, &[efi], &[], &src_dir)?,
            Bootloader::Systemd
        );
        if let Some(bios) = bios {
            assert_eq!(
                install_bootloader(&opts(root, &[])?, &[bios, efi], &[], &src_dir)?,
                Bootloader::Systemd
            );
            // BIOS metadata isn't read then, even with a device
            std::fs::write(root.join("usr/lib/bootupd/updates/BIOS.json"), "not json")?;
            let device = test_device();
            assert_eq!(
                install_bootloader(
                    &opts(root, &[])?,
                    &[bios, efi],
                    std::slice::from_ref(&device),
                    &src_dir
                )?,
                Bootloader::Systemd
            );
        }

        // A payload with systemd-boot only: the BIOS component's GRUB is
        // chosen only if BIOS installs, which needs a device and BIOS metadata.
        let td = tempfile::tempdir()?;
        let root = Utf8Path::from_path(td.path()).unwrap();
        for (component, binary) in [("shim", SHIM), ("systemd-boot", BOOTLOADER_BIN)] {
            write_empty(
                root,
                &format!("usr/lib/efi/{component}/1.0-1/EFI/fedora/{binary}"),
            )?;
        }
        let updates = root.join("usr/lib/bootupd/updates");
        std::fs::create_dir_all(&updates)?;
        std::fs::write(
            updates.join("EFI.json"),
            r#"{"timestamp":"2026-11-16T17:14:09Z","version":"shim 1.0-1,systemd-boot 1.0-1","versions":[{"name":"shim","evr":"1.0-1"},{"name":"systemd-boot","evr":"1.0-1"}],"default-bootloader":null}"#,
        )?;
        let src_dir = Dir::open_ambient_dir(root, ambient_authority())?;
        if let Some(bios) = bios {
            let device = test_device();
            let devices = std::slice::from_ref(&device);
            let choose =
                |devices| install_bootloader(&opts(root, &[])?, &[bios, efi], devices, &src_dir);
            assert_eq!(choose(&[])?, Bootloader::Systemd);
            assert_eq!(choose(devices)?, Bootloader::Systemd);
            std::fs::write(
                updates.join("BIOS.json"),
                r#"{"timestamp":"2026-11-16T17:14:09Z","version":"grub2-tools 1:2.12-1","versions":[{"name":"grub2-tools","evr":"1:2.12-1"}],"default-bootloader":null}"#,
            )?;
            assert_eq!(choose(&[])?, Bootloader::Systemd);
            assert_eq!(choose(devices)?, Bootloader::Grub);
        }
        Ok(())
    }

    /// GRUB from the BIOS component is the choice when BIOS installs, or the
    /// EFI payload carries GRUB, or there is no EFI payload to choose from.
    #[cfg(efi_arch)]
    #[test]
    fn test_bios_decides() {
        use Bootloader::{Grub, Systemd};
        assert!(bios_decides(true, Some(&[Systemd])));
        assert!(!bios_decides(false, Some(&[Systemd])));
        assert!(bios_decides(false, Some(&[Grub, Systemd])));
        assert!(bios_decides(false, None));
    }
}