libredfish 0.2.0

A redfish library. Useful for querying server hardware from a BMC.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
/*
 * SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
use std::{collections::HashMap, path::Path, time::Duration};

use chrono::Utc;
use regex::Regex;
use reqwest::header::HeaderMap;
use reqwest::Method;
use reqwest::StatusCode;
use serde::Serialize;
use serde_json::Value;
use tokio::fs::File;
use tokio::time::sleep;
use tracing::debug;

use crate::model::account_service::ManagerAccount;
use crate::model::certificate::Certificate;
use crate::model::component_integrity::ComponentIntegrities;
use crate::model::oem::lenovo::{BootSettings, FrontPanelUSB, LenovoBootOrder};
use crate::model::oem::nvidia_dpu::{HostPrivilegeLevel, NicMode};
use crate::model::sel::LogService;
use crate::model::service_root::{RedfishVendor, ServiceRoot};
use crate::model::task::Task;
use crate::model::update_service::{ComponentType, TransferProtocolType, UpdateService};
use crate::model::{secure_boot::SecureBoot, ComputerSystem};
use crate::model::{InvalidValueError, Manager};
use crate::{
    jsonmap,
    model::{
        chassis::{Assembly, Chassis, NetworkAdapter},
        network_device_function::NetworkDeviceFunction,
        oem::lenovo,
        power::Power,
        sel::{LogEntry, LogEntryCollection},
        sensor::GPUSensors,
        software_inventory::SoftwareInventory,
        storage::Drives,
        thermal::Thermal,
        BootOption,
    },
    network::REDFISH_ENDPOINT,
    standard::RedfishStandard,
    BiosProfileType, Boot, BootOptions, Collection, EnabledDisabled, MachineSetupDiff,
    MachineSetupStatus, ODataId, PCIeDevice, PowerState, Redfish, RedfishError, Resource, Status,
    StatusInternal, SystemPowerControl,
};
use crate::{JobState, RoleId};

const UEFI_PASSWORD_NAME: &str = "UefiAdminPassword";

pub struct Bmc {
    s: RedfishStandard,
}

impl Bmc {
    pub fn new(s: RedfishStandard) -> Result<Bmc, RedfishError> {
        Ok(Bmc { s })
    }
}

#[async_trait::async_trait]
impl Redfish for Bmc {
    async fn create_user(
        &self,
        username: &str,
        password: &str,
        role_id: RoleId,
    ) -> Result<(), RedfishError> {
        self.s.create_user(username, password, role_id).await
    }

    async fn delete_user(&self, username: &str) -> Result<(), RedfishError> {
        self.s.delete_user(username).await
    }

    async fn change_username(&self, old_name: &str, new_name: &str) -> Result<(), RedfishError> {
        self.s.change_username(old_name, new_name).await
    }

    async fn change_password(&self, user: &str, new: &str) -> Result<(), RedfishError> {
        self.s.change_password(user, new).await
    }

    async fn change_password_by_id(
        &self,
        account_id: &str,
        new_pass: &str,
    ) -> Result<(), RedfishError> {
        self.s.change_password_by_id(account_id, new_pass).await
    }

    async fn get_accounts(&self) -> Result<Vec<ManagerAccount>, RedfishError> {
        self.s.get_accounts().await
    }

    async fn get_power_state(&self) -> Result<PowerState, RedfishError> {
        self.s.get_power_state().await
    }

    async fn get_power_metrics(&self) -> Result<Power, RedfishError> {
        self.s.get_power_metrics().await
    }

    async fn power(&self, action: SystemPowerControl) -> Result<(), RedfishError> {
        if action == SystemPowerControl::ACPowercycle {
            let args: HashMap<String, String> =
                HashMap::from([("ResetType".to_string(), "ACPowerCycle".to_string())]);
            let url = format!(
                "Systems/{}/Actions/Oem/LenovoComputerSystem.SystemReset",
                self.s.system_id()
            );
            return self.s.client.post(&url, args).await.map(|_status_code| ());
        }

        if action == SystemPowerControl::ForceRestart
            && self.use_workaround_for_force_restart().await?
        {
            // We observed that issuing a ForceRestart to SR 675 V3 OVX machines can cause them to hang
            // We have observed that GracefulRestart is not a reliable mechanism to reboot hosts.
            // The most reliable workaround provided by Lenovo is to power off the machine, wait, and power on the machine
            self.s.power(SystemPowerControl::ForceOff).await?;
            sleep(Duration::from_secs(10)).await;
            if self.get_power_state().await? != PowerState::Off {
                return Err(RedfishError::GenericError {
                    error: "Server did not turn off within 10 seconds after issuing a ForceOff"
                        .to_string(),
                });
            }
            self.s.power(SystemPowerControl::On).await
        } else {
            self.s.power(action).await
        }
    }

    fn ac_powercycle_supported_by_power(&self) -> bool {
        true
    }

    async fn bmc_reset(&self) -> Result<(), RedfishError> {
        self.s.bmc_reset().await
    }

    async fn chassis_reset(
        &self,
        chassis_id: &str,
        reset_type: SystemPowerControl,
    ) -> Result<(), RedfishError> {
        self.s.chassis_reset(chassis_id, reset_type).await
    }

    async fn get_thermal_metrics(&self) -> Result<Thermal, RedfishError> {
        self.s.get_thermal_metrics().await
    }

    async fn get_gpu_sensors(&self) -> Result<Vec<GPUSensors>, RedfishError> {
        self.s.get_gpu_sensors().await
    }

    async fn get_system_event_log(&self) -> Result<Vec<LogEntry>, RedfishError> {
        self.get_system_event_log().await
    }

    async fn get_bmc_event_log(
        &self,
        from: Option<chrono::DateTime<Utc>>,
    ) -> Result<Vec<LogEntry>, RedfishError> {
        let url = format!(
            "Systems/{}/LogServices/AuditLog/Entries",
            self.s.system_id()
        );
        self.s.fetch_bmc_event_log(url, from).await
    }

    async fn get_drives_metrics(&self) -> Result<Vec<Drives>, RedfishError> {
        self.s.get_drives_metrics().await
    }

    async fn bios(&self) -> Result<HashMap<String, serde_json::Value>, RedfishError> {
        self.s.bios().await
    }

    async fn set_bios(
        &self,
        values: HashMap<String, serde_json::Value>,
    ) -> Result<(), RedfishError> {
        let mut body = HashMap::new();
        body.insert("Attributes", values);
        let url = format!("Systems/{}/Bios/Pending", self.s.system_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    async fn reset_bios(&self) -> Result<(), RedfishError> {
        let url = format!("Systems/{}/Bios/Actions/Bios.ResetBios", self.s.system_id());
        let mut arg = HashMap::new();
        arg.insert("ResetType", "Reset".to_string());
        self.s.client.post(&url, arg).await.map(|_resp| Ok(()))?
    }

    async fn machine_setup(
        &self,
        _boot_interface_mac: Option<&str>,
        bios_profiles: &HashMap<
            RedfishVendor,
            HashMap<String, HashMap<BiosProfileType, HashMap<String, serde_json::Value>>>,
        >,
        selected_profile: BiosProfileType,
    ) -> Result<(), RedfishError> {
        self.setup_serial_console().await?;
        self.clear_tpm().await?;
        self.boot_first(Boot::Pxe).await?;
        self.set_virt_enable().await?;
        self.set_uefi_boot_only().await?;
        if let Some(lenovo) = bios_profiles.get(&RedfishVendor::Lenovo) {
            let model = crate::model_coerce(
                self.get_system()
                    .await?
                    .model
                    .unwrap_or("".to_string())
                    .as_str(),
            );
            if let Some(all_extra_values) = lenovo.get(&model) {
                if let Some(extra_values) = all_extra_values.get(&selected_profile) {
                    tracing::debug!("Setting extra BIOS values: {extra_values:?}");
                    self.set_bios(extra_values.clone()).await?;
                }
            }
        }

        Ok(())
    }

    async fn machine_setup_status(
        &self,
        boot_interface_mac: Option<&str>,
    ) -> Result<MachineSetupStatus, RedfishError> {
        // Check BIOS and BMC attributes
        let mut diffs = self.diff_bios_bmc_attr().await?;

        // Check lockdown
        let lockdown = self.lockdown_status().await?;
        if !lockdown.is_fully_enabled() {
            diffs.push(MachineSetupDiff {
                key: "lockdown".to_string(),
                expected: "Enabled".to_string(),
                actual: lockdown.status.to_string(),
            });
        }

        // Check the first boot option
        if let Some(mac) = boot_interface_mac {
            let (expected, actual) = self.get_expected_and_actual_first_boot_option(mac).await?;
            if expected.is_none() || expected != actual {
                diffs.push(MachineSetupDiff {
                    key: "boot_first".to_string(),
                    expected: expected.unwrap_or_else(|| "Not found".to_string()),
                    actual: actual.unwrap_or_else(|| "Not found".to_string()),
                });
            }
        }
        Ok(MachineSetupStatus {
            is_done: diffs.is_empty(),
            diffs,
        })
    }

    /// Redfish equivalent of `accseccfg -pew 0 -pe 0 -chgnew off -rc 0 -ci 0 -lf 0`
    async fn set_machine_password_policy(&self) -> Result<(), RedfishError> {
        use serde_json::Value;
        let mut body = HashMap::from([
            (
                "AccountLockoutThreshold".to_string(),
                Value::Number(0.into()),
            ), // -lf 0
            (
                "AccountLockoutDuration".to_string(),
                // 60 secs is the shortest Lenovo allows. The docs say 0 disables it, but my
                // test Lenovo rejects 0.
                Value::Number(60.into()),
            ),
        ]);
        let lenovo = Value::Object(serde_json::Map::from_iter(vec![
            (
                "PasswordExpirationPeriodDays".to_string(),
                Value::Number(0.into()),
            ), // -pe 0
            (
                "PasswordChangeOnFirstAccess".to_string(),
                Value::Bool(false),
            ), // -chgnew off
            (
                "MinimumPasswordChangeIntervalHours".to_string(),
                Value::Number(0.into()),
            ), // -ci 0
            (
                "MinimumPasswordReuseCycle".to_string(),
                Value::Number(0.into()),
            ), // -rc 0
            (
                "PasswordExpirationWarningPeriod".to_string(),
                Value::Number(0.into()),
            ), // -pew 0
        ]));
        let mut oem = serde_json::Map::new();
        oem.insert("Lenovo".to_string(), lenovo);
        body.insert("Oem".to_string(), serde_json::Value::Object(oem));

        self.s
            .client
            .patch("AccountService", body)
            .await
            .map(|_status_code| ())
    }

    async fn lockdown(&self, target: EnabledDisabled) -> Result<(), RedfishError> {
        use EnabledDisabled::*;
        match target {
            Enabled => self.enable_lockdown().await,
            Disabled => self.disable_lockdown().await,
        }
    }

    async fn lockdown_status(&self) -> Result<Status, RedfishError> {
        let kcs = self.get_kcs_lenovo().await?;
        let firmware_rollback = self.get_firmware_rollback_lenovo().await?;
        let eth_usb = self.get_ethernet_over_usb().await?;
        let front_usb = self.get_front_panel_usb_lenovo().await?;

        let message = format!(
            "kcs={kcs}, firmware_rollback={firmware_rollback}, ethernet_over_usb={eth_usb}, front_panel_usb={}/{}",
            front_usb.fp_mode, front_usb.port_switching_to,
        );

        let is_locked = !kcs
            && !eth_usb
            && firmware_rollback == EnabledDisabled::Disabled
            && front_usb.fp_mode == lenovo::FrontPanelUSBMode::Server;

        let is_unlocked = kcs
            && eth_usb
            && firmware_rollback == EnabledDisabled::Enabled
            && front_usb.fp_mode == lenovo::FrontPanelUSBMode::Shared
            && front_usb.port_switching_to == lenovo::PortSwitchingMode::Server;

        Ok(Status {
            message,
            status: if is_locked {
                StatusInternal::Enabled
            } else if is_unlocked {
                StatusInternal::Disabled
            } else {
                StatusInternal::Partial
            },
        })
    }

    async fn setup_serial_console(&self) -> Result<(), RedfishError> {
        let bios = self.bios().await?;
        let url = format!("Systems/{}/Bios", self.s.system_id());
        let current_attrs = jsonmap::get_object(&bios, "Attributes", &url)?;
        
        let mut attributes = HashMap::new();
        
        attributes.insert(
            "DevicesandIOPorts_COMPort1",
            EnabledDisabled::Enabled.to_string(),
        );
        attributes.insert(
            "DevicesandIOPorts_ConsoleRedirection",
            "Enabled".to_string(),
        );
        attributes.insert(
            "DevicesandIOPorts_SerialPortSharing",
            EnabledDisabled::Enabled.to_string(),
        );
        attributes.insert(
            "DevicesandIOPorts_SerialPortAccessMode",
            "Shared".to_string(),
        );

        // Only in older Lenovo systems
        if current_attrs.contains_key("DevicesandIOPorts_SPRedirection") {
            attributes.insert(
                "DevicesandIOPorts_SPRedirection",
                EnabledDisabled::Enabled.to_string(),
            );
        }
        if current_attrs.contains_key("DevicesandIOPorts_COMPortActiveAfterBoot") {
            attributes.insert(
                "DevicesandIOPorts_COMPortActiveAfterBoot",
                EnabledDisabled::Enabled.to_string(),
            );
        }
        
        let mut body = HashMap::new();
        body.insert("Attributes", attributes);
        
        let url = format!("Systems/{}/Bios/Pending", self.s.system_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    async fn serial_console_status(&self) -> Result<Status, RedfishError> {
        let url = format!("Systems/{}/Bios", self.s.system_id());
        let bios = self.bios().await?;
        let attrs = jsonmap::get_object(&bios, "Attributes", &url)?;

        // "any" means any value counts as correctly disabled
        // Attributes are checked if present, missing attributes are skipped
        let expected = vec![
            ("DevicesandIOPorts_COMPort1", "Enabled", "any"),
            ("DevicesandIOPorts_ConsoleRedirection", "Enabled", "Auto"),
            ("DevicesandIOPorts_SerialPortSharing", "Enabled", "Disabled"),
            ("DevicesandIOPorts_SPRedirection", "Enabled", "Disabled"),
            ("DevicesandIOPorts_COMPortActiveAfterBoot", "Enabled", "Disabled"),
            ("DevicesandIOPorts_SerialPortAccessMode", "Shared", "Disabled"),
        ];
        
        let mut message = String::new();
        let mut enabled = true;
        let mut disabled = true;
        
        for (key, val_enabled, val_disabled) in expected {
            if let Some(val_current) = attrs.get(key).and_then(|v| v.as_str()) {
                message.push_str(&format!("{key}={val_current} "));
                if val_current != val_enabled {
                    enabled = false;
                }
                if val_current != val_disabled && val_disabled != "any" {
                    disabled = false;
                }
            }
        }

        Ok(Status {
            message,
            status: match (enabled, disabled) {
                (true, _) => StatusInternal::Enabled,
                (_, true) => StatusInternal::Disabled,
                _ => StatusInternal::Partial,
            },
        })
    }

    async fn get_boot_options(&self) -> Result<BootOptions, RedfishError> {
        self.s.get_boot_options().await
    }

    async fn get_boot_option(&self, option_id: &str) -> Result<BootOption, RedfishError> {
        self.s.get_boot_option(option_id).await
    }

    async fn boot_once(&self, target: Boot) -> Result<(), RedfishError> {
        match target {
            Boot::Pxe => self.set_boot_override(lenovo::BootSource::Pxe).await,
            Boot::HardDisk => self.set_boot_override(lenovo::BootSource::Hdd).await,
            Boot::UefiHttp => Err(RedfishError::NotSupported(
                "No Lenovo UefiHttp implementation".to_string(),
            )),
        }
    }

    async fn boot_first(&self, target: Boot) -> Result<(), RedfishError> {
        match target {
            Boot::Pxe => self.set_boot_first(lenovo::BootOptionName::Network).await,
            Boot::HardDisk => self.set_boot_first(lenovo::BootOptionName::HardDisk).await,
            Boot::UefiHttp => Err(RedfishError::NotSupported(
                "No Lenovo UefiHttp implementation".to_string(),
            )),
        }
    }

    async fn clear_tpm(&self) -> Result<(), RedfishError> {
        let mut body = HashMap::new();
        body.insert(
            "Attributes",
            HashMap::from([("TrustedComputingGroup_DeviceOperation", "Clear")]),
        );
        let url = format!("Systems/{}/Bios/Pending", self.s.system_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    async fn pending(&self) -> Result<HashMap<String, serde_json::Value>, RedfishError> {
        let url = format!("Systems/{}/Bios/Pending", self.s.system_id());
        self.s.pending_with_url(&url).await
    }

    async fn clear_pending(&self) -> Result<(), RedfishError> {
        let url = format!("Systems/{}/Bios/Pending", self.s.system_id());
        self.s.clear_pending_with_url(&url).await
    }

    async fn pcie_devices(&self) -> Result<Vec<PCIeDevice>, RedfishError> {
        self.s.pcie_devices().await
    }

    async fn update_firmware(
        &self,
        firmware: tokio::fs::File,
    ) -> Result<crate::model::task::Task, RedfishError> {
        self.s.update_firmware(firmware).await
    }

    async fn get_update_service(&self) -> Result<UpdateService, RedfishError> {
        self.s.get_update_service().await
    }

    async fn update_firmware_multipart(
        &self,
        filename: &Path,
        _reboot: bool,
        timeout: Duration,
        _component_type: ComponentType,
    ) -> Result<String, RedfishError> {
        let firmware = File::open(&filename)
            .await
            .map_err(|e| RedfishError::FileError(format!("Could not open file: {}", e)))?;

        // The Python example code followed the schema to get the actual endpoint; this may or may not be needed, but
        // it's safest not to assume that it will always be the same thing.
        let update_service = self.get_update_service().await?;

        if update_service.multipart_http_push_uri.is_empty() {
            return Err(RedfishError::NotSupported(
                "Host BMC does not support HTTP multipart push".to_string(),
            ));
        }

        let parameters = serde_json::to_string(&UpdateParameters::new()).map_err(|e| {
            RedfishError::JsonSerializeError {
                url: "".to_string(),
                object_debug: "".to_string(),
                source: e,
            }
        })?;

        let (_status_code, _loc, body) = self
            .s
            .client
            .req_update_firmware_multipart(
                filename,
                firmware,
                parameters,
                &update_service.multipart_http_push_uri,
                true,
                timeout,
            )
            .await?;

        let task: Task =
            serde_json::from_str(&body).map_err(|e| RedfishError::JsonDeserializeError {
                url: update_service.multipart_http_push_uri,
                body,
                source: e,
            })?;

        Ok(task.id)
    }

    async fn get_tasks(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_tasks().await
    }

    async fn get_task(&self, id: &str) -> Result<crate::model::task::Task, RedfishError> {
        self.s.get_task(id).await
    }

    async fn get_firmware(&self, id: &str) -> Result<SoftwareInventory, RedfishError> {
        let mut inv = self.s.get_firmware(id).await?;
        // Lenovo prepends the last two characters of their "Build/Vendor" ID and a dash to most of the versions.  This confuses things, so trim off anything that's before a dash.
        inv.version = inv
            .version
            .map(|x| x.split('-').next_back().unwrap_or("").to_string());
        Ok(inv)
    }

    async fn get_software_inventories(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_software_inventories().await
    }

    async fn get_system(&self) -> Result<ComputerSystem, RedfishError> {
        self.s.get_system().await
    }

    async fn get_secure_boot_certificate(
        &self,
        database_id: &str,
        certificate_id: &str,
    ) -> Result<Certificate, RedfishError> {
        self.s
            .get_secure_boot_certificate(database_id, certificate_id)
            .await
    }

    async fn get_secure_boot_certificates(
        &self,
        database_id: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_secure_boot_certificates(database_id).await
    }

    async fn add_secure_boot_certificate(
        &self,
        pem_cert: &str,
        database_id: &str,
    ) -> Result<Task, RedfishError> {
        self.s
            .add_secure_boot_certificate(pem_cert, database_id)
            .await
    }

    async fn get_secure_boot(&self) -> Result<SecureBoot, RedfishError> {
        self.s.get_secure_boot().await
    }

    async fn enable_secure_boot(&self) -> Result<(), RedfishError> {
        self.s.enable_secure_boot().await
    }

    async fn disable_secure_boot(&self) -> Result<(), RedfishError> {
        self.s.disable_secure_boot().await
    }

    async fn get_network_device_function(
        &self,
        chassis_id: &str,
        id: &str,
        port: Option<&str>,
    ) -> Result<NetworkDeviceFunction, RedfishError> {
        self.s
            .get_network_device_function(chassis_id, id, port)
            .await
    }

    async fn get_network_device_functions(
        &self,
        chassis_id: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_network_device_functions(chassis_id).await
    }

    async fn get_chassis_all(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_chassis_all().await
    }

    async fn get_chassis(&self, id: &str) -> Result<Chassis, RedfishError> {
        self.s.get_chassis(id).await
    }

    async fn get_chassis_assembly(&self, chassis_id: &str) -> Result<Assembly, RedfishError> {
        self.s.get_chassis_assembly(chassis_id).await
    }

    async fn get_chassis_network_adapters(
        &self,
        chassis_id: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_chassis_network_adapters(chassis_id).await
    }

    async fn get_chassis_network_adapter(
        &self,
        chassis_id: &str,
        id: &str,
    ) -> Result<NetworkAdapter, RedfishError> {
        self.s.get_chassis_network_adapter(chassis_id, id).await
    }

    async fn get_base_network_adapters(
        &self,
        system_id: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_base_network_adapters(system_id).await
    }

    async fn get_base_network_adapter(
        &self,
        system_id: &str,
        id: &str,
    ) -> Result<NetworkAdapter, RedfishError> {
        self.s.get_base_network_adapter(system_id, id).await
    }

    async fn get_ports(
        &self,
        chassis_id: &str,
        network_adapter: &str,
    ) -> Result<Vec<String>, RedfishError> {
        self.s.get_ports(chassis_id, network_adapter).await
    }

    async fn get_port(
        &self,
        chassis_id: &str,
        network_adapter: &str,
        id: &str,
    ) -> Result<crate::NetworkPort, RedfishError> {
        self.s.get_port(chassis_id, network_adapter, id).await
    }

    async fn get_manager_ethernet_interfaces(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_manager_ethernet_interfaces().await
    }

    async fn get_manager_ethernet_interface(
        &self,
        id: &str,
    ) -> Result<crate::EthernetInterface, RedfishError> {
        self.s.get_manager_ethernet_interface(id).await
    }

    async fn get_system_ethernet_interfaces(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_system_ethernet_interfaces().await
    }

    async fn get_system_ethernet_interface(
        &self,
        id: &str,
    ) -> Result<crate::EthernetInterface, RedfishError> {
        self.s.get_system_ethernet_interface(id).await
    }

    async fn change_uefi_password(
        &self,
        current_uefi_password: &str,
        new_uefi_password: &str,
    ) -> Result<Option<String>, RedfishError> {
        self.s
            .change_bios_password(UEFI_PASSWORD_NAME, current_uefi_password, new_uefi_password)
            .await
    }

    async fn change_boot_order(&self, boot_array: Vec<String>) -> Result<(), RedfishError> {
        let body = HashMap::from([("Boot", HashMap::from([("BootOrder", boot_array)]))]);
        let url = format!("Systems/{}/Pending", self.s.system_id());
        // BMC takes longer to respond to this one, so override timeout
        let timeout = Duration::from_secs(10);
        let (_status_code, _resp_body, _resp_headers): (
            _,
            Option<HashMap<String, serde_json::Value>>,
            Option<HeaderMap>,
        ) = self
            .s
            .client
            .req(
                Method::PATCH,
                &url,
                Some(body),
                Some(timeout),
                None,
                Vec::new(),
            )
            .await?;
        Ok(())
    }

    async fn get_service_root(&self) -> Result<ServiceRoot, RedfishError> {
        self.s.get_service_root().await
    }

    async fn get_systems(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_systems().await
    }

    async fn get_managers(&self) -> Result<Vec<String>, RedfishError> {
        self.s.get_managers().await
    }

    async fn get_manager(&self) -> Result<Manager, RedfishError> {
        self.s.get_manager().await
    }

    async fn bmc_reset_to_defaults(&self) -> Result<(), RedfishError> {
        self.s.bmc_reset_to_defaults().await
    }

    async fn get_job_state(&self, job_id: &str) -> Result<JobState, RedfishError> {
        self.s.get_job_state(job_id).await
    }

    async fn get_collection(&self, id: ODataId) -> Result<Collection, RedfishError> {
        self.s.get_collection(id).await
    }

    async fn get_resource(&self, id: ODataId) -> Result<Resource, RedfishError> {
        self.s.get_resource(id).await
    }

    async fn set_boot_order_dpu_first(
        &self,
        mac_address: &str,
    ) -> Result<Option<String>, RedfishError> {
        // Try the OEM NetworkBootOrder path first (older firmware)
        match self.set_boot_order_dpu_first_oem(mac_address).await {
            Ok(result) => return Ok(result),
            Err(RedfishError::HTTPErrorCode {
                status_code: StatusCode::NOT_FOUND,
                ..
            }) => {
                // OEM path doesn't exist, fall back to BIOS attributes (newer firmware)
                tracing::info!(
                    "OEM NetworkBootOrder not found, using BIOS attributes for boot order"
                );
            }
            Err(e) => return Err(e),
        }

        self.set_boot_order_dpu_first_bios_attr(mac_address).await
    }

    async fn clear_uefi_password(
        &self,
        current_uefi_password: &str,
    ) -> Result<Option<String>, RedfishError> {
        self.change_uefi_password(current_uefi_password, "").await
    }

    async fn get_base_mac_address(&self) -> Result<Option<String>, RedfishError> {
        self.s.get_base_mac_address().await
    }

    async fn lockdown_bmc(&self, target: crate::EnabledDisabled) -> Result<(), RedfishError> {
        self.s.lockdown_bmc(target).await
    }

    async fn is_ipmi_over_lan_enabled(&self) -> Result<bool, RedfishError> {
        self.s.is_ipmi_over_lan_enabled().await
    }

    async fn enable_ipmi_over_lan(
        &self,
        target: crate::EnabledDisabled,
    ) -> Result<(), RedfishError> {
        self.s.enable_ipmi_over_lan(target).await
    }

    async fn update_firmware_simple_update(
        &self,
        image_uri: &str,
        targets: Vec<String>,
        transfer_protocol: TransferProtocolType,
    ) -> Result<Task, RedfishError> {
        self.s
            .update_firmware_simple_update(image_uri, targets, transfer_protocol)
            .await
    }

    async fn enable_rshim_bmc(&self) -> Result<(), RedfishError> {
        self.s.enable_rshim_bmc().await
    }

    async fn clear_nvram(&self) -> Result<(), RedfishError> {
        self.s.clear_nvram().await
    }

    async fn get_nic_mode(&self) -> Result<Option<NicMode>, RedfishError> {
        self.s.get_nic_mode().await
    }

    async fn set_nic_mode(&self, mode: NicMode) -> Result<(), RedfishError> {
        self.s.set_nic_mode(mode).await
    }

    async fn enable_infinite_boot(&self) -> Result<(), RedfishError> {
        let attrs: HashMap<String, serde_json::Value> =
            HashMap::from([("BootModes_InfiniteBootRetry".to_string(), "Enabled".into())]);
        self.set_bios(attrs).await
    }

    async fn is_infinite_boot_enabled(&self) -> Result<Option<bool>, RedfishError> {
        let url = format!("Systems/{}/Bios", self.s.system_id());
        let bios = self.bios().await?;
        let bios_attributes = jsonmap::get_object(&bios, "Attributes", &url)?;
        let infinite_boot_status = jsonmap::get_str(
            bios_attributes,
            "BootModes_InfiniteBootRetry",
            "Bios Attributes",
        )?;

        Ok(Some(
            infinite_boot_status == EnabledDisabled::Enabled.to_string(),
        ))
    }

    async fn set_host_rshim(&self, enabled: EnabledDisabled) -> Result<(), RedfishError> {
        self.s.set_host_rshim(enabled).await
    }

    async fn get_host_rshim(&self) -> Result<Option<EnabledDisabled>, RedfishError> {
        self.s.get_host_rshim().await
    }

    async fn set_idrac_lockdown(&self, enabled: EnabledDisabled) -> Result<(), RedfishError> {
        self.s.set_idrac_lockdown(enabled).await
    }

    async fn get_boss_controller(&self) -> Result<Option<String>, RedfishError> {
        self.s.get_boss_controller().await
    }

    async fn decommission_storage_controller(
        &self,
        controller_id: &str,
    ) -> Result<Option<String>, RedfishError> {
        self.s.decommission_storage_controller(controller_id).await
    }

    async fn create_storage_volume(
        &self,
        controller_id: &str,
        volume_name: &str,
        raid_type: &str,
    ) -> Result<Option<String>, RedfishError> {
        self.s
            .create_storage_volume(controller_id, volume_name, raid_type)
            .await
    }

    async fn is_boot_order_setup(&self, boot_interface_mac: &str) -> Result<bool, RedfishError> {
        // Check if Network is first in the boot order
        let system = self.get_system().await?;
        let Some(first_boot_id) = system.boot.boot_order.first() else {
            return Ok(false);
        };
        let boot_first = self.get_boot_option(first_boot_id).await?;
        if boot_first.name != "Network" {
            return Ok(false);
        }

        // Check if the specific MAC address is first in the network boot order
        let (expected, actual) = self
            .get_expected_and_actual_first_boot_option(boot_interface_mac)
            .await?;
        Ok(expected.is_some() && expected == actual)
    }

    async fn is_bios_setup(&self, _boot_interface_mac: Option<&str>) -> Result<bool, RedfishError> {
        let diffs = self.diff_bios_bmc_attr().await?;
        Ok(diffs.is_empty())
    }

    async fn get_component_integrities(&self) -> Result<ComponentIntegrities, RedfishError> {
        self.s.get_component_integrities().await
    }

    async fn get_firmware_for_component(
        &self,
        componnent_integrity_id: &str,
    ) -> Result<crate::model::software_inventory::SoftwareInventory, RedfishError> {
        self.s
            .get_firmware_for_component(componnent_integrity_id)
            .await
    }

    async fn get_component_ca_certificate(
        &self,
        url: &str,
    ) -> Result<crate::model::component_integrity::CaCertificate, RedfishError> {
        self.s.get_component_ca_certificate(url).await
    }

    async fn trigger_evidence_collection(
        &self,
        url: &str,
        nonce: &str,
    ) -> Result<Task, RedfishError> {
        self.s.trigger_evidence_collection(url, nonce).await
    }

    async fn get_evidence(
        &self,
        url: &str,
    ) -> Result<crate::model::component_integrity::Evidence, RedfishError> {
        self.s.get_evidence(url).await
    }

    async fn set_host_privilege_level(&self, level: HostPrivilegeLevel) -> Result<(), RedfishError> {
        self.s.set_host_privilege_level(level).await
    }

    async fn set_utc_timezone(&self) -> Result<(), RedfishError> {
        self.s.set_utc_timezone().await
    }
}

impl Bmc {
    /// Set DPU as first network boot option using OEM NetworkBootOrder path (older firmware).
    /// Boot options are strings like "UEFI: SLOT2 HTTP IPv4 Nvidia Network Adapter - A0:88:C2:08:53:C4"
    async fn set_boot_order_dpu_first_oem(
        &self,
        mac_address: &str,
    ) -> Result<Option<String>, RedfishError> {
        let mac = mac_address.to_string();
        // We see three patterns for HTTP IPv4 DPU boot option names in a Lenovo's network boot order:
        // "UEFI:   SLOT2 (31/0/0) HTTP IPv4  Nvidia Network Adapter - A0:88:C2:08:53:C4",
        // "UEFI:   SLOT1 (4B/0/0) HTTP IPv4  Mellanox Network Adapter - B8:3F:D2:90:99:C4"
        // "UEFI:   SLOT 1 (41/0/0) HTTP IPv4  Nvidia BlueField-3 VPI QSFP112 2P 200G PCIe Gen5 x16 - 5C:25:73:79:DA:5C"
        // This regex pattern uses .*? (non-greedy match) to allow any characters to appear between "Nvidia" and the MAC address.
        let net_boot_option_pattern = format!("HTTP IPv4  (Mellanox|Nvidia).*? - {}", mac);
        let net_boot_option_regex =
            Regex::new(&net_boot_option_pattern).map_err(|err| RedfishError::GenericError {
                error: format!(
                    "could not create net_boot_option_regex from {net_boot_option_pattern}: {err}"
                ),
            })?;

        // Check boot_order_supported for the list of currently supported boot options.
        // Set boot_order_next because that's what will happen when we reboot.
        // boot_order_current is the current order.
        let mut net_boot_order = self.get_network_boot_order().await?;
        let dpu_boot_option = net_boot_order
            .boot_order_supported
            .iter()
            .find(|s| net_boot_option_regex.is_match(s))
            .ok_or_else(|| {
                RedfishError::MissingBootOption(format!(
                    "Oem/Lenovo NetworkBootOrder BootOrderSupported {mac} (matching on {net_boot_option_pattern}); currently supported boot options: {:#?}",
                    net_boot_order.boot_order_supported
                ))
            })?;

        if let Some(pos) = net_boot_order
            .boot_order_next
            .iter()
            .position(|s| s == dpu_boot_option)
        {
            // the DPU boot option is already at the first index of the boot_order_next list
            if pos == 0 {
                tracing::info!(
                    "NO-OP: DPU ({mac_address}) will already be the first netboot option ({dpu_boot_option}) after reboot"
                );
                return Ok(None);
            } else {
                // boot_order_next contains the DPU boot option. move it to the front.
                net_boot_order.boot_order_next.swap(0, pos);
            }
        } else {
            // boot_order_next did not have the DPU boot option. add it to the beginning.
            net_boot_order
                .boot_order_next
                .insert(0, dpu_boot_option.clone());
        }

        // Patch remote
        let url = format!(
            "{}/BootOrder.NetworkBootOrder",
            self.get_boot_settings_uri()
        );
        let body = HashMap::from([("BootOrderNext", net_boot_order.boot_order_next.clone())]);
        self.s
            .client
            .patch(&url, body)
            .await
            .map(|_status_code| ())?;
        Ok(None)
    }

    /// Set DPU as first network boot option using BIOS attributes (newer firmware).
    /// Boot options are BIOS attributes like BootOrder_NetworkPriority_1 with
    /// values like "Slot5Port1HTTPv4NvidiaNetworkAdapter_B8_E9_24_18_42_52".
    async fn set_boot_order_dpu_first_bios_attr(
        &self,
        mac_address: &str,
    ) -> Result<Option<String>, RedfishError> {
        let mac = mac_address.replace(':', "_").to_uppercase();
        let bios = self.s.bios_attributes().await?;

        let (pos, dpu_val) = (1u32..=10)
            .find_map(|i| {
                bios.get(format!("BootOrder_NetworkPriority_{i}"))
                    .and_then(|v| v.as_str())
                    .filter(|v| v.to_uppercase().contains(&mac) && v.contains("HTTPv4"))
                    .map(|v| (i, v.to_string()))
            })
            .ok_or_else(|| {
                RedfishError::MissingBootOption(format!(
                    "No BootOrder_NetworkPriority_* contains MAC {mac_address} (HTTPv4)"
                ))
            })?;

        if pos == 1 {
            return Ok(None);
        }

        // Swap our DPU with the old network priority
        let mut attrs = HashMap::from([("BootOrder_NetworkPriority_1".to_string(), dpu_val)]);
        if let Some(old) = bios.get("BootOrder_NetworkPriority_1").and_then(|v| v.as_str()) {
            attrs.insert(format!("BootOrder_NetworkPriority_{pos}"), old.to_string());
        }

        self.s
            .client
            .patch(
                &format!("Systems/{}/Bios/Pending", self.s.system_id()),
                HashMap::from([("Attributes", attrs)]),
            )
            .await
            .map(|_| ())?;

        Ok(None)
    }

    /// Get expected and actual first boot option using OEM NetworkBootOrder path (older firmware).
    async fn get_expected_and_actual_first_boot_option_oem(
        &self,
        boot_interface_mac: &str,
    ) -> Result<(Option<String>, Option<String>), RedfishError> {
        let mac = boot_interface_mac.to_string();
        // We see three patterns for HTTP IPv4 DPU boot option names in a Lenovo's network boot order:
        // "UEFI:   SLOT2 (31/0/0) HTTP IPv4  Nvidia Network Adapter - A0:88:C2:08:53:C4",
        // "UEFI:   SLOT1 (4B/0/0) HTTP IPv4  Mellanox Network Adapter - B8:3F:D2:90:99:C4"
        // "UEFI:   SLOT 1 (41/0/0) HTTP IPv4  Nvidia BlueField-3 VPI QSFP112 2P 200G PCIe Gen5 x16 - 5C:25:73:79:DA:5C"
        // This regex pattern uses .*? (non-greedy match) to allow any characters to appear between "Nvidia" and the MAC address.
        let net_boot_option_pattern = format!("HTTP IPv4  (Mellanox|Nvidia).*? - {}", mac);
        let net_boot_option_regex =
            Regex::new(&net_boot_option_pattern).map_err(|err| RedfishError::GenericError {
                error: format!(
                    "could not create net_boot_option_regex from {net_boot_option_pattern}: {err}"
                ),
            })?;

        // Check boot_order_supported for the list of currently supported boot options.
        // Set boot_order_next because that's what will happen when we reboot.
        // boot_order_current is the current order.
        let net_boot_order = self.get_network_boot_order().await?;
        let expected_first_boot_option = net_boot_order
            .boot_order_supported
            .iter()
            .find(|s| net_boot_option_regex.is_match(s))
            .cloned();

        let actual_first_boot_option = net_boot_order.boot_order_next.first().cloned();

        Ok((expected_first_boot_option, actual_first_boot_option))
    }

    /// Get expected and actual first boot option using BIOS attributes (newer firmware).
    async fn get_expected_and_actual_first_boot_option_bios_attr(
        &self,
        boot_interface_mac: &str,
    ) -> Result<(Option<String>, Option<String>), RedfishError> {
        let mac = boot_interface_mac.replace(':', "_").to_uppercase();
        let bios = self.s.bios_attributes().await?;

        let expected = (1u32..=10).find_map(|i| {
            bios.get(format!("BootOrder_NetworkPriority_{i}"))
                .and_then(|v| v.as_str())
                .filter(|v| v.to_uppercase().contains(&mac) && v.contains("HTTPv4"))
                .map(|v| v.to_string())
        });

        let actual = bios
            .get("BootOrder_NetworkPriority_1")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        Ok((expected, actual))
    }

    /// Check BIOS and BMC attributes and return differences
    async fn diff_bios_bmc_attr(&self) -> Result<Vec<MachineSetupDiff>, RedfishError> {
        let mut diffs = vec![];

        let sc = self.serial_console_status().await?;
        if !sc.is_fully_enabled() {
            diffs.push(MachineSetupDiff {
                key: "serial_console".to_string(),
                expected: "Enabled".to_string(),
                actual: sc.status.to_string(),
            });
        }

        // clear_tpm has no 'check' operation, so skip that

        let virt = self.get_virt_enabled().await?;
        if virt != EnabledDisabled::Enabled {
            diffs.push(MachineSetupDiff {
                key: "Processors_IntelVirtualizationTechnology".to_string(),
                expected: EnabledDisabled::Enabled.to_string(),
                actual: virt.to_string(),
            });
        }

        let bios = self.s.bios_attributes().await?;
        for (key, expected) in self.uefi_boot_only_attributes() {
            let Some(actual) = bios.get(key) else {
                diffs.push(MachineSetupDiff {
                    key: key.to_string(),
                    expected: expected.to_string(),
                    actual: "_missing_".to_string(),
                });
                continue;
            };
            let actual_str = actual.as_str().unwrap_or("_wrong_type_");
            if actual_str != expected {
                diffs.push(MachineSetupDiff {
                    key: key.to_string(),
                    expected: expected.to_string(),
                    actual: actual_str.to_string(),
                });
            }
        }

        // Get the first boot option from the actual boot order 
        // Some lenovos return an unordered BootOptions collection
        let system = self.get_system().await?;
        let boot_first_name = match system.boot.boot_order.first() {
            Some(first_boot_id) => self.get_boot_option(first_boot_id).await?.name,
            None => "_empty_boot_order_".to_string(),
        };
        if boot_first_name != "Network" {
            // Boot::Pxe maps to lenovo::BootOptionName::Network
            diffs.push(MachineSetupDiff {
                key: "boot_first_type".to_string(),
                expected: lenovo::BootOptionName::Network.to_string(),
                actual: boot_first_name,
            });
        }

        Ok(diffs)
    }

    /// Lock a Lenovo server to make it ready for tenants
    async fn enable_lockdown(&self) -> Result<(), RedfishError> {
        self.set_kcs_lenovo(false).await.inspect_err(|err| {
            debug!(%err, "Failed disabling 'IPMI over KCS Access'");
        })?;
        self.set_firmware_rollback_lenovo(EnabledDisabled::Disabled)
            .await
            .inspect_err(|err| {
                debug!(%err, "Failed changing 'Prevent System Firmware Down-Level'");
            })?;
        self.set_ethernet_over_usb(false).await.inspect_err(|err| {
            debug!(%err, "Failed disabling Ethernet over USB");
        })?;
        self.set_front_panel_usb_lenovo(
            lenovo::FrontPanelUSBMode::Server,
            lenovo::PortSwitchingMode::Server,
        )
        .await
        .inspect_err(|err| {
            debug!(%err, "Failed locking front panel USB to host-only.");
        })?;
        Ok(())
    }

    /// Unlock a Lenovo server, restoring defaults
    pub async fn disable_lockdown(&self) -> Result<(), RedfishError> {
        self.set_kcs_lenovo(true).await.inspect_err(|err| {
            debug!(%err, "Failed enabling 'IPMI over KCS Access'");
        })?;
        self.set_firmware_rollback_lenovo(EnabledDisabled::Enabled)
            .await
            .inspect_err(|err| {
                debug!(%err, "Failed changing 'Prevent System Firmware Down-Level'");
            })?;
        self.set_ethernet_over_usb(true).await.inspect_err(|err| {
            debug!(%err, "Failed disabling Ethernet over USB");
        })?;
        self.set_front_panel_usb_lenovo(
            lenovo::FrontPanelUSBMode::Shared,
            lenovo::PortSwitchingMode::Server,
        )
        .await
        .inspect_err(|err| {
            debug!(%err, "Failed unlocking front panel USB to shared mode.");
        })?;
        Ok(())
    }

    async fn get_kcs_value(&self) -> Result<Value, RedfishError> {
        let url = format!("Managers/{}", self.s.manager_id());
        let (_, body): (_, HashMap<String, serde_json::Value>) = self.s.client.get(&url).await?;

        let oem_obj = jsonmap::get_object(&body, "Oem", &url)?;
        let lenovo_obj = jsonmap::get_object(oem_obj, "Lenovo", &url)?;
        let is_kcs_enabled = jsonmap::get_value(lenovo_obj, "KCSEnabled", &url)?;

        Ok(is_kcs_enabled.clone())
    }

    async fn set_kcs_lenovo(&self, is_allowed: bool) -> Result<(), RedfishError> {
        let kcs_val: Value = match self.get_kcs_value().await? {
            Value::Bool(_) => serde_json::Value::Bool(is_allowed),
            Value::String(_) => {
                if is_allowed {
                    serde_json::Value::String("Enabled".to_owned())
                } else {
                    serde_json::Value::String("Disabled".to_owned())
                }
            }
            v => {
                return Err(RedfishError::InvalidValue {
                    url: format!("Managers/{}", self.s.manager_id()),
                    field: "KCS".to_string(),
                    err: InvalidValueError(format!(
                        "expected bool or string as KCS enabled value type; got {v}"
                    )),
                })
            }
        };

        let body = HashMap::from([(
            "Oem",
            HashMap::from([("Lenovo", HashMap::from([("KCSEnabled", kcs_val)]))]),
        )]);
        let url = format!("Managers/{}", self.s.manager_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    async fn get_kcs_lenovo(&self) -> Result<bool, RedfishError> {
        let manager = self.get_manager().await?;
        match &manager.oem {
            Some(oem) => match &oem.lenovo {
                Some(lenovo_oem) => Ok(lenovo_oem.kcs_enabled),
                None => Err(RedfishError::GenericError {
                    error: format!(
                        "Manager is missing Lenovo specific OEM field: \n{:#?}",
                        manager.clone()
                    ),
                }),
            },
            None => Err(RedfishError::GenericError {
                error: format!("Manager is missing OEM field: \n{:#?}", manager.clone()),
            }),
        }
    }

    async fn set_firmware_rollback_lenovo(&self, set: EnabledDisabled) -> Result<(), RedfishError> {
        let body = HashMap::from([(
            "Configurator",
            HashMap::from([("FWRollback", set.to_string())]),
        )]);
        let url = format!("Managers/{}/Oem/Lenovo/Security", self.s.manager_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    async fn get_firmware_rollback_lenovo(&self) -> Result<EnabledDisabled, RedfishError> {
        let url = format!("Managers/{}/Oem/Lenovo/Security", self.s.manager_id());
        let (_, body): (_, HashMap<String, serde_json::Value>) = self.s.client.get(&url).await?;

        let configurator = jsonmap::get_object(&body, "Configurator", &url)?;
        let fw_rollback = jsonmap::get_str(configurator, "FWRollback", &url)?;

        let fw_typed = fw_rollback
            .parse()
            .map_err(|_| RedfishError::InvalidKeyType {
                key: "FWRollback".to_string(),
                expected_type: "EnabledDisabled".to_string(),
                url: url.to_string(),
            })?;
        Ok(fw_typed)
    }

    async fn get_front_panel_usb_kv_lenovo(&self) -> Result<(String, FrontPanelUSB), RedfishError> {
        let url = format!("Systems/{}", self.s.system_id());
        let (_, body): (_, HashMap<String, serde_json::Value>) = self.s.client.get(&url).await?;

        let oem_obj = jsonmap::get_object(&body, "Oem", &url)?;
        let lenovo_obj = jsonmap::get_object(oem_obj, "Lenovo", &url)?;

        let mut front_panel_usb_key = "FrontPanelUSB";
        let val = match lenovo_obj.get(front_panel_usb_key) {
            Some(val) => val,
            None => {
                front_panel_usb_key = "USBManagementPortAssignment";
                match lenovo_obj.get(front_panel_usb_key) {
                    Some(val) => val,
                    None => {
                        return Err(RedfishError::MissingKey {
                            key: front_panel_usb_key.to_string(),
                            url,
                        })
                    }
                }
            }
        };

        let front_panel_usb_val = serde_json::from_value(val.clone()).map_err(|err| {
            RedfishError::JsonDeserializeError {
                url,
                body: format!("{val:?}"),
                source: err,
            }
        })?;

        Ok((front_panel_usb_key.to_string(), front_panel_usb_val))
    }

    async fn set_front_panel_usb_lenovo(
        &self,
        mode: lenovo::FrontPanelUSBMode,
        owner: lenovo::PortSwitchingMode,
    ) -> Result<(), RedfishError> {
        let mut body = HashMap::new();
        let (front_panel_usb_key, _) = self.get_front_panel_usb_kv_lenovo().await?;
        body.insert(
            "Oem",
            HashMap::from([(
                "Lenovo",
                HashMap::from([(
                    front_panel_usb_key,
                    HashMap::from([
                        ("FPMode", mode.to_string()),
                        ("PortSwitchingTo", owner.to_string()),
                    ]),
                )]),
            )]),
        );
        let url = format!("Systems/{}", self.s.system_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    async fn get_front_panel_usb_lenovo(&self) -> Result<lenovo::FrontPanelUSB, RedfishError> {
        let (_, front_panel_usb_val) = self.get_front_panel_usb_kv_lenovo().await?;
        Ok(front_panel_usb_val)
    }

    async fn set_ethernet_over_usb(&self, is_allowed: bool) -> Result<(), RedfishError> {
        let body = HashMap::from([("InterfaceEnabled", is_allowed)]);
        let url = format!("Managers/{}/EthernetInterfaces/ToHost", self.s.manager_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    async fn get_ethernet_over_usb(&self) -> Result<bool, RedfishError> {
        let url = format!("Managers/{}/EthernetInterfaces/ToHost", self.s.manager_id());
        let (_, body): (_, HashMap<String, serde_json::Value>) = self.s.client.get(&url).await?;

        jsonmap::get_bool(&body, "InterfaceEnabled", &url)
    }

    /// Both Intel and AMD have virtualization technologies that help fix the issue of x86 instruction
    /// architecture not being virtualizable.
    /// get_enable_virtualization_key returns the KEY for enabling virtualization in the bios attributes
    /// map that the Lenovo's BMC returns when querying the bios attributes registry. The string returned
    /// will depend on the processors within the given Lenovo. For example, 655v3/675v3s use AMD processors
    /// whereas, 650v2/670v2s use Intel processors.
    async fn get_enable_virtualization_key(
        &self,
        bios_attributes: &Value,
    ) -> Result<&str, RedfishError> {
        const INTEL_ENABLE_VIRTUALIZATION_KEY: &str = "Processors_IntelVirtualizationTechnology";
        const AMD_ENABLE_VIRTUALIZATION_KEY: &str = "Processors_SVMMode";

        // Intel specific
        if bios_attributes
            .get(INTEL_ENABLE_VIRTUALIZATION_KEY)
            .is_some()
        {
            Ok(INTEL_ENABLE_VIRTUALIZATION_KEY)
        // AMD specific
        } else if bios_attributes.get(AMD_ENABLE_VIRTUALIZATION_KEY).is_some() {
            Ok(AMD_ENABLE_VIRTUALIZATION_KEY)
        } else {
            Err(RedfishError::MissingKey {
                key: format!(
                    "{}/{}",
                    INTEL_ENABLE_VIRTUALIZATION_KEY, AMD_ENABLE_VIRTUALIZATION_KEY
                )
                .to_string(),
                url: format!("Systems/{}/Bios", self.s.system_id()),
            })
        }
    }

    async fn set_virt_enable(&self) -> Result<(), RedfishError> {
        let bios = self.s.bios_attributes().await?;
        let mut body = HashMap::new();
        let enable_virtualization_key = self.get_enable_virtualization_key(&bios).await?;
        body.insert(
            "Attributes",
            HashMap::from([(enable_virtualization_key, "Enabled")]),
        );
        let url = format!("Systems/{}/Bios/Pending", self.s.system_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    async fn get_virt_enabled(&self) -> Result<EnabledDisabled, RedfishError> {
        let bios = self.s.bios_attributes().await?;
        let enable_virtualization_key = self.get_enable_virtualization_key(&bios).await?;
        let Some(val) = bios.get(enable_virtualization_key) else {
            return Err(RedfishError::MissingKey {
                key: enable_virtualization_key.to_string(),
                url: "bios".to_string(),
            });
        };
        let Some(val) = val.as_str() else {
            return Err(RedfishError::InvalidKeyType {
                key: enable_virtualization_key.to_string(),
                expected_type: "str".to_string(),
                url: "bios".to_string(),
            });
        };
        val.parse().map_err(|_e| RedfishError::InvalidKeyType {
            key: enable_virtualization_key.to_string(),
            expected_type: "EnabledDisabled".to_string(),
            url: "bios".to_string(),
        })
    }

    /// Set so that we only UEFI IPv4 HTTP boot, and we retry that.
    ///
    /// Disable PXE Boot
    /// Disable LegacyBIOS Mode (if supported)
    /// Set Bootmode to UEFI
    /// Enable IPv4 HTTP Boot
    /// Disable IPv4 PXE Boot
    /// Disable IPv6 PXE Boot
    /// Enable Infinite Boot Mode
    async fn set_uefi_boot_only(&self) -> Result<(), RedfishError> {
        let bios = self.bios().await?;
        let url = format!("Systems/{}/Bios", self.s.system_id());
        let attrs = jsonmap::get_object(&bios, "Attributes", &url)?;
        
        let mut attributes = self.uefi_boot_only_attributes();
        
        // Legacy BIOS attributes only exist in older systems
        // Only set them if they're present in the current BIOS
        if attrs.contains_key("LegacyBIOS_NonOnboardPXE") {
            attributes.insert("LegacyBIOS_NonOnboardPXE", "Disabled");
        }
        if attrs.contains_key("LegacyBIOS_LegacyBIOS") {
            attributes.insert("LegacyBIOS_LegacyBIOS", "Disabled");
        }
        
        let mut body = HashMap::new();
        body.insert("Attributes", attributes);
        let url = format!("Systems/{}/Bios/Pending", self.s.system_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    fn uefi_boot_only_attributes(&self) -> HashMap<&str, &str> {
        HashMap::from([
            ("BootModes_SystemBootMode", "UEFIMode"),
            ("NetworkStackSettings_IPv4HTTPSupport", "Enabled"),
            ("NetworkStackSettings_IPv4PXESupport", "Disabled"),
            ("NetworkStackSettings_IPv6PXESupport", "Disabled"),
            ("BootModes_InfiniteBootRetry", "Enabled"),
            ("BootModes_PreventOSChangesToBootOrder", "Enabled"),
        ])
    }

    async fn set_boot_override(&self, target: lenovo::BootSource) -> Result<(), RedfishError> {
        let target_str = &target.to_string();
        let body = HashMap::from([(
            "Boot",
            HashMap::from([
                ("BootSourceOverrideEnabled", "Once"),
                ("BootSourceOverrideTarget", target_str),
            ]),
        )]);
        let url = format!("Systems/{}", self.s.system_id());
        self.s.client.patch(&url, body).await.map(|_status_code| ())
    }

    // name: The name of the device you want to make the first boot choice.
    //
    // Note that _within_ the type you choose you could also give the order. e.g for "Network"
    // see Systems/1/Oem/Lenovo/BootSettings/BootOrder.NetworkBootOrder
    // and for "HardDisk" see Systems/1/Oem/Lenovo/BootSettings/BootOrder.HardDiskBootOrder
    async fn set_boot_first(&self, name: lenovo::BootOptionName) -> Result<(), RedfishError> {
        let boot_array = match self.get_boot_options_ids_with_first(name).await? {
            None => {
                return Err(RedfishError::MissingBootOption(name.to_string()));
            }
            Some(b) => b,
        };

        self.change_boot_order(boot_array).await
    }

    // A Vec of string boot option names, with the one you want first.
    //
    // Example: get_boot_options_ids_with_first(lenovo::BootOptionName::Network) might return
    // ["Boot0003", "Boot0002", "Boot0001", "Boot0004"] where Boot0003 is Network. It has been
    // moved to the front ready for sending as an update.
    // The order of the other boot options does not change.
    //
    // If the boot option you want is not found returns Ok(None)
    async fn get_boot_options_ids_with_first(
        &self,
        with_name: lenovo::BootOptionName,
    ) -> Result<Option<Vec<String>>, RedfishError> {
        let with_name_str = with_name.to_string();
        let mut with_name_match = None; // the ID of the option matching with_name
        let mut ordered = Vec::new(); // the final boot options
        let boot_options = self.s.get_boot_options().await?;
        for member in boot_options.members {
            let url = member
                .odata_id
                .replace(&format!("/{REDFISH_ENDPOINT}/"), "");
            let b: BootOption = self.s.client.get(&url).await?.1;
            if b.name == with_name_str {
                with_name_match = Some(b.id);
            } else {
                ordered.push(b.id);
            }
        }
        match with_name_match {
            None => Ok(None),
            Some(with_name_id) => {
                ordered.insert(0, with_name_id);
                Ok(Some(ordered))
            }
        }
    }

    // lenovo stores the sel as part of the system
    async fn get_system_event_log(&self) -> Result<Vec<LogEntry>, RedfishError> {
        let url = format!("Systems/{}/LogServices/SEL", self.s.system_id());
        let (_status_code, log_service): (_, LogService) = self.s.client.get(&url).await?;
        // If there are no log entries, this field and the `SEL/Entries` endpoint do not exist.
        if log_service.entries.is_none() {
            return Ok(vec![]);
        }
        let url = format!("Systems/{}/LogServices/SEL/Entries", self.s.system_id());
        let (_status_code, log_entry_collection): (_, LogEntryCollection) =
            self.s.client.get(&url).await?;
        let log_entries = log_entry_collection.members;
        Ok(log_entries)
    }

    async fn is_lenovo_sr_675_v3_ovx(&self) -> Result<bool, RedfishError> {
        let system = self.get_system().await?;
        match system.sku {
            /*  7D9RCTOLWW is the SKU for Lenovo ThinkSystem SR675 V3 OVX
                Taken from sample redfish response against an SR675 in AZ51:
                curl -k -D - --user root:'password' -H 'Content-Type: application/json' -X GET https://10.91.48.100:443/redfish/v1/Systems/1
                {..."SKU":"7D9RCTOLWW","PowerState":"On"...}
            */
            Some(sku) => Ok(sku == "7D9RCTOLWW"),
            None => Err(RedfishError::MissingKey {
                key: "sku".to_string(),
                url: "Systems".to_string(),
            }),
        }
    }

    async fn get_bmc_version(&self) -> Result<String, RedfishError> {
        let uefi_fw_info = self.get_firmware("BMC-Primary").await?;
        Ok(uefi_fw_info.version.unwrap_or_default())
    }

    async fn get_uefi_version(&self) -> Result<String, RedfishError> {
        let uefi_fw_info = self.get_firmware("UEFI").await?;
        Ok(uefi_fw_info.version.unwrap_or_default())
    }

    async fn use_workaround_for_force_restart(&self) -> Result<bool, RedfishError> {
        if self.is_lenovo_sr_675_v3_ovx().await? {
            let uefi_version = self.get_uefi_version().await?;
            let bmc_version = self.get_bmc_version().await?;

            let is_uefi_at_7_10 = version_compare::compare(uefi_version, "7.10")
                .is_ok_and(|c| c == version_compare::Cmp::Eq);

            let is_bmc_at_9_10 = version_compare::compare(bmc_version, "9.10")
                .is_ok_and(|c| c == version_compare::Cmp::Eq);

            if is_uefi_at_7_10 && is_bmc_at_9_10 {
                return Ok(true);
            }
        }

        Ok(false)
    }

    fn get_boot_settings_uri(&self) -> String {
        format!("Systems/{}/Oem/Lenovo/BootSettings", self.s.system_id())
    }

    async fn get_network_boot_order(&self) -> Result<LenovoBootOrder, RedfishError> {
        let url = self.get_boot_settings_uri();
        let (_status_code, boot_settings): (_, BootSettings) = self.s.client.get(&url).await?;
        for member in &boot_settings.members {
            let id = member.odata_id_get()?;
            if id.contains("BootOrder.NetworkBootOrder") {
                let (_status_code, net_boot_order): (_, LenovoBootOrder) =
                    self.s.client.get(&format!("{url}/{id}")).await?;

                return Ok(net_boot_order);
            }
        }

        Err(RedfishError::GenericError {
            error: format!(
                "Could not find the NetworkBootOrder out of Boot Settings members: {:#?}",
                boot_settings.members
            ),
        })
    }

    async fn get_expected_and_actual_first_boot_option(
        &self,
        boot_interface_mac: &str,
    ) -> Result<(Option<String>, Option<String>), RedfishError> {
        // Try the OEM NetworkBootOrder path first (older firmware)
        match self.get_expected_and_actual_first_boot_option_oem(boot_interface_mac).await {
            Ok(result) => return Ok(result),
            Err(RedfishError::HTTPErrorCode {
                status_code: StatusCode::NOT_FOUND,
                ..
            }) => {
                // OEM path doesn't exist, fall back to BIOS attributes (newer firmware)
            }
            Err(e) => return Err(e),
        }

        self.get_expected_and_actual_first_boot_option_bios_attr(boot_interface_mac)
            .await
    }
}

#[derive(Debug, Default, Serialize, Clone)]
#[serde(rename_all = "PascalCase")]
struct UpdateParameters {
    targets: Vec<String>,
    #[serde(rename = "@Redfish.OperationApplyTime")]
    operation_apply_time: String,
}

impl UpdateParameters {
    fn new() -> Self {
        Self {
            targets: vec![],
            operation_apply_time: "Immediate".to_string(),
        }
    }
}