framework_lib 0.6.2

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

use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use guid_create::{CGuid, GUID};
use log::Level;
use num_traits::FromPrimitive;

#[cfg(not(feature = "uefi"))]
pub mod clap_std;
#[cfg(feature = "uefi")]
pub mod uefi;

#[cfg(not(feature = "uefi"))]
use std::fs;
#[cfg(not(feature = "uefi"))]
use std::io::prelude::*;

#[cfg(feature = "rusb")]
use crate::audio_card::check_synaptics_fw_version;
use crate::built_info;
#[cfg(feature = "rusb")]
use crate::camera::check_camera_version;
use crate::capsule;
use crate::capsule_content::{
    find_bios_version, find_ec_in_bios_cap, find_pd_in_bios_cap, find_retimer_version,
};
use crate::ccgx::device::{FwMode, PdController, PdPort};
#[cfg(feature = "hidapi")]
use crate::ccgx::hid::{check_ccg_fw_version, find_devices, DP_CARD_PID, HDMI_CARD_PID};
use crate::ccgx::{self, MainPdVersions, PdVersions, SiliconId::*};
use crate::chromium_ec;
use crate::chromium_ec::commands::BoardIdType;
use crate::chromium_ec::commands::DeckStateMode;
use crate::chromium_ec::commands::FpLedBrightnessLevel;
use crate::chromium_ec::commands::RebootEcCmd;
use crate::chromium_ec::commands::RgbS;
use crate::chromium_ec::commands::TabletModeOverride;
use crate::chromium_ec::EcResponseStatus;
use crate::chromium_ec::{print_err, EcFlashType};
use crate::chromium_ec::{CrosEcDriver, EcError, EcResult};
use crate::csme;
use crate::ec_binary;
use crate::esrt::{self, ResourceType};
#[cfg(feature = "uefi")]
use crate::fw_uefi::enable_page_break;
#[cfg(feature = "rusb")]
use crate::inputmodule::check_inputmodule_version;
#[cfg(target_os = "linux")]
use crate::nvme;
use crate::os_specific;
use crate::parade_retimer;
use crate::power;
use crate::smbios;
use crate::smbios::ConfigDigit0;
use crate::smbios::{get_smbios, is_framework};
#[cfg(feature = "hidapi")]
use crate::touchpad::print_touchpad_fw_ver;
#[cfg(feature = "hidapi")]
use crate::touchscreen;
#[cfg(feature = "rusb")]
use crate::usbhub::check_usbhub_version;
use crate::util::{self, Config, Platform, PlatformFamily};
use dmidecode::Structure;
#[cfg(feature = "hidapi")]
use hidapi::HidApi;
use sha2::{Digest, Sha256, Sha384, Sha512};

#[cfg(feature = "nvidia")]
use nvml_wrapper::{enum_wrappers::device::TemperatureSensor, Nvml};

use crate::chromium_ec::{CrosEc, CrosEcDriverType, HardwareDeviceType};

#[cfg(feature = "uefi")]
use core::prelude::rust_2021::derive;

#[cfg_attr(not(feature = "uefi"), derive(clap::ValueEnum))]
#[derive(Clone, Debug, PartialEq)]
pub enum TabletModeArg {
    Auto,
    Tablet,
    Laptop,
}

#[cfg_attr(not(feature = "uefi"), derive(clap::ValueEnum))]
#[derive(Clone, Debug, PartialEq)]
pub enum ConsoleArg {
    Recent,
    Follow,
}

#[cfg_attr(not(feature = "uefi"), derive(clap::ValueEnum))]
#[derive(Clone, Debug, PartialEq)]
pub enum RebootEcArg {
    Reboot,
    JumpRo,
    JumpRw,
    CancelJump,
    DisableJump,
}

#[cfg_attr(not(feature = "uefi"), derive(clap::ValueEnum))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FpBrightnessArg {
    High,
    Medium,
    Low,
    UltraLow,
    Auto,
}
impl From<FpBrightnessArg> for FpLedBrightnessLevel {
    fn from(w: FpBrightnessArg) -> FpLedBrightnessLevel {
        match w {
            FpBrightnessArg::High => FpLedBrightnessLevel::High,
            FpBrightnessArg::Medium => FpLedBrightnessLevel::Medium,
            FpBrightnessArg::Low => FpLedBrightnessLevel::Low,
            FpBrightnessArg::UltraLow => FpLedBrightnessLevel::UltraLow,
            FpBrightnessArg::Auto => FpLedBrightnessLevel::Auto,
        }
    }
}

#[cfg_attr(not(feature = "uefi"), derive(clap::ValueEnum))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum InputDeckModeArg {
    Auto,
    Off,
    On,
}
impl From<InputDeckModeArg> for DeckStateMode {
    fn from(w: InputDeckModeArg) -> DeckStateMode {
        match w {
            InputDeckModeArg::Auto => DeckStateMode::Required,
            InputDeckModeArg::Off => DeckStateMode::ForceOff,
            InputDeckModeArg::On => DeckStateMode::ForceOn,
        }
    }
}

#[derive(Debug)]
pub struct LogLevel(log::LevelFilter);

impl Default for LogLevel {
    fn default() -> Self {
        LogLevel(log::LevelFilter::Error)
    }
}

/// Shadows `clap_std::ClapCli` with extras for UEFI
///
/// The UEFI commandline currently doesn't use clap, so we need to shadow the struct.
/// Also it has extra options.
#[derive(Debug, Default)]
pub struct Cli {
    pub verbosity: LogLevel,
    pub versions: bool,
    pub version: bool,
    pub features: bool,
    pub esrt: bool,
    pub device: Option<HardwareDeviceType>,
    pub compare_version: Option<String>,
    pub power: bool,
    pub thermal: bool,
    pub sensors: bool,
    pub fansetduty: Option<(Option<u32>, u32)>,
    pub fansetrpm: Option<(Option<u32>, u32)>,
    pub autofanctrl: Option<Option<u8>>,
    pub pdports: bool,
    pub pdports_chromebook: bool,
    pub privacy: bool,
    pub pd_info: bool,
    pub pd_reset: Option<u8>,
    pub pd_disable: Option<u8>,
    pub pd_enable: Option<u8>,
    pub dp_hdmi_info: bool,
    pub dp_hdmi_update: Option<String>,
    pub audio_card_info: bool,
    pub pd_bin: Option<String>,
    pub ec_bin: Option<String>,
    pub capsule: Option<String>,
    pub dump: Option<String>,
    pub h2o_capsule: Option<String>,
    pub dump_ec_flash: Option<String>,
    pub flash_full_ec: Option<String>,
    pub flash_ec: Option<String>,
    pub flash_ro_ec: Option<String>,
    pub flash_rw_ec: Option<String>,
    pub driver: Option<CrosEcDriverType>,
    pub test: bool,
    pub test_retimer: bool,
    pub boardid: bool,
    pub dry_run: bool,
    pub force: bool,
    pub intrusion: bool,
    pub inputdeck: bool,
    pub inputdeck_mode: Option<InputDeckModeArg>,
    pub expansion_bay: bool,
    pub charge_limit: Option<Option<u8>>,
    pub charge_current_limit: Option<(u32, Option<u32>)>,
    pub charge_rate_limit: Option<(f32, Option<f32>)>,
    pub get_gpio: Option<Option<String>>,
    pub fp_led_level: Option<Option<FpBrightnessArg>>,
    pub fp_brightness: Option<Option<u8>>,
    pub kblight: Option<Option<u8>>,
    pub remap_key: Option<(u8, u8, u16)>,
    pub rgbkbd: Vec<u64>,
    pub ps2_enable: Option<bool>,
    pub tablet_mode: Option<TabletModeArg>,
    pub touchscreen_enable: Option<bool>,
    pub stylus_battery: bool,
    pub console: Option<ConsoleArg>,
    pub reboot_ec: Option<RebootEcArg>,
    pub ec_hib_delay: Option<Option<u32>>,
    pub uptimeinfo: bool,
    pub s0ix_counter: bool,
    pub hash: Option<String>,
    pub pd_addrs: Option<(u16, u16, u16)>,
    pub pd_ports: Option<(u8, u8, u8)>,
    pub help: bool,
    pub info: bool,
    pub meinfo: Option<Option<String>>,
    pub flash_gpu_descriptor: Option<(u8, String)>,
    pub flash_gpu_descriptor_file: Option<String>,
    pub dump_gpu_descriptor_file: Option<String>,
    pub nvidia: bool,
    // UEFI only
    pub allupdate: bool,
    pub paginate: bool,
    pub host_command: Option<(u16, u8, Vec<u8>)>,
}

pub fn parse(args: &[String]) -> Cli {
    #[cfg(feature = "uefi")]
    let cli = uefi::parse(args);
    #[cfg(not(feature = "uefi"))]
    let cli = clap_std::parse(args);

    if cfg!(feature = "readonly") {
        // Initialize a new Cli with no arguments
        // Set all arguments that are readonly/safe
        // We explicitly only cope the safe ones so that if we add new arguments in the future,
        // which might be unsafe, we can't forget to exclude them from the safe set.
        // TODO: Instead of silently ignoring blocked command, we should remind the user
        Cli {
            verbosity: cli.verbosity,
            versions: cli.versions,
            version: cli.version,
            features: cli.features,
            esrt: cli.esrt,
            device: cli.device,
            compare_version: cli.compare_version,
            power: cli.power,
            thermal: cli.thermal,
            sensors: cli.sensors,
            // fansetduty
            // fansetrpm
            // autofanctrl
            pdports: cli.pdports,
            pdports_chromebook: cli.pdports_chromebook,
            privacy: cli.privacy,
            pd_info: cli.version,
            // pd_reset
            // pd_disable
            // pd_enable
            dp_hdmi_info: cli.dp_hdmi_info,
            // dp_hdmi_update
            audio_card_info: cli.audio_card_info,
            pd_bin: cli.pd_bin,
            ec_bin: cli.ec_bin,
            capsule: cli.capsule,
            dump: cli.dump,
            h2o_capsule: cli.h2o_capsule,
            // dump_ec_flash
            // flash_full_ec
            // flash_ec
            // flash_ro_ec
            // flash_rw_ec
            driver: cli.driver,
            test: cli.test,
            test_retimer: cli.test_retimer,
            boardid: cli.boardid,
            dry_run: cli.dry_run,
            // force
            intrusion: cli.intrusion,
            inputdeck: cli.inputdeck,
            inputdeck_mode: cli.inputdeck_mode,
            expansion_bay: cli.expansion_bay,
            // charge_limit
            // charge_current_limit
            // charge_rate_limit
            get_gpio: cli.get_gpio,
            fp_led_level: cli.fp_led_level,
            fp_brightness: cli.fp_brightness,
            kblight: cli.kblight,
            remap_key: cli.remap_key,
            rgbkbd: cli.rgbkbd,
            ps2_enable: cli.ps2_enable,
            // tablet_mode
            // touchscreen_enable
            stylus_battery: cli.stylus_battery,
            console: cli.console,
            reboot_ec: cli.reboot_ec,
            // ec_hib_delay
            uptimeinfo: cli.uptimeinfo,
            s0ix_counter: cli.s0ix_counter,
            hash: cli.hash,
            pd_addrs: cli.pd_addrs,
            pd_ports: cli.pd_ports,
            help: cli.help,
            info: cli.info,
            // flash_gpu_descriptor
            // flash_gpu_descriptor_file
            nvidia: cli.nvidia,
            // allupdate
            paginate: cli.paginate,
            // host_command
            ..Default::default()
        }
    } else {
        cli
    }
}

fn print_single_pd_details(pd: &PdController) {
    if let Ok(si) = pd.get_silicon_id() {
        println!("  Silicon ID:     0x{:X}", si);
    } else {
        println!("  Failed to read Silicon ID/Family");
        return;
    }
    if let Ok((mode, frs)) = pd.get_device_info() {
        println!("  Mode:           {:?}", mode);
        println!("  Flash Row Size: {} B", frs);
    } else {
        println!("  Failed to device info");
    }
    if let Ok(port_mask) = pd.get_port_status() {
        let ports = match port_mask {
            1 => "0",
            2 => "1",
            3 => "0, 1",
            _ => "None",
        };
        println!("  Ports Enabled:  {}", ports);
    } else {
        println!("  Ports Enabled:  Unknown");
    }
    pd.print_fw_info();
}

fn print_pd_details(ec: &CrosEc) {
    if !is_framework() {
        println!("Only supported on Framework systems");
        return;
    }
    let pd_01 = PdController::new(PdPort::Right01, ec.clone());
    let pd_23 = PdController::new(PdPort::Left23, ec.clone());
    let pd_back = PdController::new(PdPort::Back, ec.clone());

    println!("Right / Ports 01");
    print_single_pd_details(&pd_01);
    println!("Left / Ports 23");
    print_single_pd_details(&pd_23);
    println!("Back");
    print_single_pd_details(&pd_back);
}

#[cfg(feature = "hidapi")]
const NOT_SET: &str = "NOT SET";

#[cfg(feature = "rusb")]
fn print_audio_card_details() {
    check_synaptics_fw_version();
}

#[cfg(feature = "hidapi")]
fn print_dp_hdmi_details(verbose: bool) {
    match HidApi::new() {
        Ok(api) => {
            for dev_info in find_devices(&api, &[HDMI_CARD_PID, DP_CARD_PID], None) {
                let vid = dev_info.vendor_id();
                let pid = dev_info.product_id();

                let device = dev_info.open_device(&api).unwrap();
                if let Some(name) = ccgx::hid::device_name(vid, pid) {
                    println!("{}", name);
                }

                // On Windows this value is "Control Interface", probably hijacked by the kernel driver
                debug!(
                    "  Product String:  {}",
                    dev_info.product_string().unwrap_or(NOT_SET)
                );

                debug!(
                    "  Serial Number:        {}",
                    dev_info.serial_number().unwrap_or(NOT_SET)
                );
                check_ccg_fw_version(&device, verbose);
            }
        }
        Err(e) => {
            eprintln!("Error: {e}");
        }
    };
}

fn print_tool_version() {
    let q = "?".to_string();
    println!("Tool Version Information");
    println!("  Version:     {}", built_info::PKG_VERSION);
    println!("  Built At:    {}", built_info::BUILT_TIME_UTC);
    println!(
        "  Git Commit:  {}",
        built_info::GIT_COMMIT_HASH.unwrap_or(&q)
    );
    println!(
        "  Git Dirty:   {}",
        built_info::GIT_DIRTY
            .map(|x| x.to_string())
            .unwrap_or(q.clone())
    );

    if log_enabled!(Level::Info) {
        println!(
            "  Built on CI: {:?}",
            built_info::CI_PLATFORM.unwrap_or("None")
        );
        println!(
            "  Git ref:     {:?}",
            built_info::GIT_HEAD_REF.unwrap_or(&q)
        );
        println!("  rustc Ver:   {}", built_info::RUSTC_VERSION);
        println!("  Features     {:?}", built_info::FEATURES);
        println!("  DEBUG:       {}", built_info::DEBUG);
        println!("  Target OS:   {}", built_info::CFG_OS);
    }
}

// TODO: Check if HDMI card is same
#[cfg(feature = "hidapi")]
fn flash_dp_hdmi_card(pd_bin_path: &str) {
    let data = match fs::read(pd_bin_path) {
        Ok(data) => Some(data),
        // TODO: Perhaps a more user-friendly error
        Err(e) => {
            println!("Error {:?}", e);
            None
        }
    };
    if let Some(data) = data {
        // TODO: Check if exists, otherwise err
        //ccgx::hid::find_device().unwrap();
        ccgx::hid::flash_firmware(&data);
    } else {
        error!("Failed to open firmware file");
    }
}

fn active_mode(mode: &FwMode, reference: FwMode) -> &'static str {
    if mode == &reference {
        " (Active)"
    } else {
        ""
    }
}

#[cfg(feature = "hidapi")]
fn print_stylus_battery_level() {
    loop {
        if let Some(level) = touchscreen::get_battery_level() {
            println!("Stylus Battery Strength: {}%", level);
            return;
        } else {
            debug!("Stylus Battery Strength: Unknown");
        }
    }
}

fn print_versions(ec: &CrosEc) {
    println!("Tool Version:     {}", built_info::PKG_VERSION);
    println!("OS Version:       {}", os_specific::get_os_version());
    println!("Mainboard Hardware");
    if let Some(ver) = smbios::get_product_name() {
        println!("  Type:           {}", ver);
    } else {
        println!("  Type:           Unknown");
    }
    if let Some(ver) = smbios::get_baseboard_version() {
        println!("  Revision:       {:?}", ver);
    } else {
        println!("  Revision:       Unknown");
    }
    println!("UEFI BIOS");
    if let Some(smbios) = get_smbios() {
        if let Some(bios) = smbios.structures().find_map(|r| match r {
            Ok(Structure::Bios(b)) => Some(b),
            _ => None,
        }) {
            println!("  Version:        {}", bios.bios_version);
            println!("  Release Date:   {}", bios.bios_release_date);
        } else {
            println!("  Version:        Unknown");
        }
    } else {
        println!("  Version:        Unknown");
    }

    println!("EC Firmware");
    let ver = print_err(ec.version_info()).unwrap_or_else(|| "UNKNOWN".to_string());
    println!("  Build version:  {}", ver);

    if let Some((ro, rw, curr)) = ec.flash_version() {
        if ro != rw || log_enabled!(Level::Info) {
            println!("  RO Version:     {}", ro);
            println!("  RW Version:     {}", rw);
        }
        print!("  Current image:  ");
        if curr == chromium_ec::EcCurrentImage::RO {
            println!("RO");
        } else if curr == chromium_ec::EcCurrentImage::RW {
            println!("RW");
        } else {
            println!("Unknown");
        }
    } else {
        println!("  RO Version:     Unknown");
        println!("  RW Version:     Unknown");
        println!("  Current image:  Unknown");
    }

    println!("PD Controllers");
    let ccgx_pd_vers = ccgx::get_pd_controller_versions(ec);
    if let Ok(PdVersions::RightLeft((right, left))) = ccgx_pd_vers {
        if let Some(Platform::IntelGen11) = smbios::get_platform() {
            if right.main_fw.base != right.backup_fw.base {
                println!("  Right (01)");
                println!(
                    "    Main:           {}{}",
                    right.main_fw.base,
                    active_mode(&right.active_fw, FwMode::MainFw)
                );
                println!(
                    "    Backup:         {}{}",
                    right.backup_fw.base,
                    active_mode(&right.active_fw, FwMode::BackupFw)
                );
            } else {
                println!(
                    "  Right (01):       {} ({:?})",
                    right.main_fw.base, right.active_fw
                );
            }
        } else if right.main_fw.app != right.backup_fw.app {
            println!(
                "    Main:           {}{}",
                right.main_fw.app,
                active_mode(&right.active_fw, FwMode::MainFw)
            );
            println!(
                "    Backup:         {}{}",
                right.backup_fw.app,
                active_mode(&right.active_fw, FwMode::BackupFw)
            );
        } else {
            println!(
                "  Right (01):       {} ({:?})",
                right.main_fw.app, right.active_fw
            );
        }
        if let Some(Platform::IntelGen11) = smbios::get_platform() {
            if left.main_fw.base != left.backup_fw.base {
                println!("  Left  (23)");
                println!(
                    "    Main:           {}{}",
                    left.main_fw.base,
                    active_mode(&left.active_fw, FwMode::MainFw)
                );
                println!(
                    "    Backup:         {}{}",
                    left.backup_fw.base,
                    active_mode(&left.active_fw, FwMode::BackupFw)
                );
            } else {
                println!(
                    "  Left  (23):       {} ({:?})",
                    left.main_fw.base, left.active_fw
                );
            }
        } else if left.main_fw.app != left.backup_fw.app {
            println!("  Left  (23)");
            println!(
                "    Main:           {}{}",
                left.main_fw.app,
                active_mode(&left.active_fw, FwMode::MainFw)
            );
            println!(
                "    Backup:         {}{}",
                left.backup_fw.app,
                active_mode(&left.active_fw, FwMode::BackupFw)
            );
        } else {
            println!(
                "  Left  (23):       {} ({:?})",
                left.main_fw.app, left.active_fw
            );
        }
    } else if let Ok(PdVersions::Many(versions)) = ccgx_pd_vers {
        for (i, version) in versions.into_iter().enumerate() {
            if version.main_fw.app != version.backup_fw.app {
                println!("  PD {}", 1);
                println!(
                    "    Main:           {}{}",
                    version.main_fw.app,
                    active_mode(&version.active_fw, FwMode::MainFw)
                );
                println!(
                    "    Backup:         {}{}",
                    version.backup_fw.app,
                    active_mode(&version.active_fw, FwMode::BackupFw)
                );
            } else {
                println!(
                    "  PD {}:            {} ({:?})",
                    i, version.main_fw.app, version.active_fw
                );
            }
        }
    } else if let Ok(PdVersions::Single(pd)) = ccgx_pd_vers {
        if pd.main_fw.app != pd.backup_fw.app {
            println!(
                "    Main:         {}{}",
                pd.main_fw.app,
                active_mode(&pd.active_fw, FwMode::MainFw)
            );
            println!(
                "    Backup:       {}{}",
                pd.backup_fw.app,
                active_mode(&pd.active_fw, FwMode::BackupFw)
            );
        } else {
            println!("  Version:        {} ({:?})", pd.main_fw.app, pd.active_fw);
        }
    } else if let Ok(pd_versions) = power::read_pd_version(ec) {
        // As fallback try to get it from the EC. But not all EC versions have this command
        debug!("  Fallback to PD Host command");
        match pd_versions {
            MainPdVersions::RightLeft((controller01, controller23)) => {
                if let Some(Platform::IntelGen11) = smbios::get_platform() {
                    println!("  Right (01):     {}", controller01.base);
                    println!("  Left  (23):     {}", controller23.base);
                } else {
                    println!("  Right (01):     {}", controller01.app);
                    println!("  Left  (23):     {}", controller23.app);
                }
            }
            MainPdVersions::Single(version) => {
                println!("  Version:        {}", version.app);
            }
            MainPdVersions::Many(versions) => {
                for (i, version) in versions.into_iter().enumerate() {
                    println!("  PD {}:          {}", i, version.app);
                }
            }
        }
    } else {
        println!("  Unknown")
    }

    let has_retimer = matches!(
        smbios::get_platform(),
        Some(Platform::IntelGen11)
            | Some(Platform::IntelGen12)
            | Some(Platform::IntelGen13)
            | Some(Platform::IntelCoreUltra1)
    );
    let mut left_retimer: Option<u32> = None;
    let mut right_retimer: Option<u32> = None;
    if let Some(esrt) = esrt::get_esrt() {
        for entry in &esrt.entries {
            match GUID::from(entry.fw_class) {
                esrt::TGL_RETIMER01_GUID
                | esrt::ADL_RETIMER01_GUID
                | esrt::RPL_RETIMER01_GUID
                | esrt::MTL_RETIMER01_GUID => {
                    right_retimer = Some(entry.fw_version);
                }
                esrt::TGL_RETIMER23_GUID
                | esrt::ADL_RETIMER23_GUID
                | esrt::RPL_RETIMER23_GUID
                | esrt::MTL_RETIMER23_GUID => {
                    left_retimer = Some(entry.fw_version);
                }
                _ => {}
            }
        }
    }
    if has_retimer {
        println!("Intel Retimers");
        if let Some(fw_version) = left_retimer {
            println!("  Left:           0x{:X} ({})", fw_version, fw_version);
        }
        if let Some(fw_version) = right_retimer {
            println!("  Right:          0x{:X} ({})", fw_version, fw_version);
        }
        if left_retimer.is_none() && right_retimer.is_none() {
            // This means there's a bug, we should've found one but didn't
            println!("  Unknown");
        }
    } else {
        // If we don't know the GUID, print all the device firmwares in ESRT
        println!("Intel Retimers (Potential)");
        if let Some(esrt) = esrt::get_esrt() {
            for entry in esrt.entries.iter() {
                if ResourceType::from_int(entry.fw_type) != ResourceType::DeviceFirmware {
                    continue;
                }
                println!("  GUID:          {}", entry.fw_class);
                println!(
                    "  Version:       0x{:X} ({})",
                    entry.fw_version, entry.fw_version
                );
            }
        } else {
            println!("Could not find and parse ESRT table.");
        }
    }
    match parade_retimer::get_version(ec) {
        // Does not exist
        Ok(None) => {}
        Ok(Some(ver)) => {
            println!("Parade Retimers");
            if let [a, b, c, d, ..] = ver.as_slice() {
                println!("  dGPU:           {:X}.{:X}.{:X}.{:X}", a, b, c, d);
            } else {
                println!("  dGPU:           Unknown");
            }
        }
        _err => {
            // Only Framework 16 has dGPU support (which has Parade Retimer)
            if smbios::get_platform().and_then(Platform::which_family)
                == Some(PlatformFamily::Framework16)
            {
                println!("Parade Retimers");
                println!("  Unknown");
            }
        }
    }

    #[cfg(target_os = "linux")]
    if smbios::get_platform().and_then(Platform::which_cpu_vendor) != Some(util::CpuVendor::Amd) {
        println!("CSME");
        if let Ok(csme) = csme::csme_from_sysfs() {
            info!("  Enabled:          {}", csme.enabled);
            println!("  Firmware Version: {}", csme.main_ver);
            if csme.main_ver != csme.recovery_ver || csme.main_ver != csme.fitc_ver {
                println!("  Recovery Ver:     {}", csme.recovery_ver);
                println!("  Original Ver:     {}", csme.fitc_ver);
            }
        } else {
            println!("  Unknown");
        }
    }
    #[cfg(feature = "rusb")]
    let _ignore_err = check_camera_version();

    #[cfg(feature = "rusb")]
    let _ignore_err = check_usbhub_version();

    #[cfg(feature = "rusb")]
    let _ignore_err = check_inputmodule_version();

    #[cfg(feature = "hidapi")]
    let _ignore_err = print_touchpad_fw_ver();

    #[cfg(feature = "hidapi")]
    if let Some(Platform::Framework12IntelGen13) = smbios::get_platform() {
        let _ignore_err = touchscreen::print_fw_ver();
    }
    #[cfg(feature = "hidapi")]
    print_dp_hdmi_details(false);

    #[cfg(target_os = "linux")]
    for i in 0..4 {
        let device = format!("/dev/nvme{i}");
        match nvme::get_nvme_firmware_version(&device) {
            Ok(dev) => {
                println!("NVMe Device: {}", device);
                println!(" Model Number:     {}", dev.model_number);
                println!(" Firmware Version: {}", dev.firmware_version);
            }
            Err(_e) => {
                // TODO: Maybe print errors but ignore "Not such file or directory"
                // eprintln!("Failed to get firmware version for {}: {}", device, e);
            }
        }
    }

    #[cfg(feature = "nvidia")]
    print_nvidia_details();
}

#[cfg(feature = "nvidia")]
fn probably_has_nvidia() -> bool {
    match smbios::get_platform().and_then(Platform::which_family) {
        Some(PlatformFamily::Framework12) => return false,
        Some(PlatformFamily::Framework13) => return false,
        Some(PlatformFamily::FrameworkDesktop) => return false,
        _ => {}
    }

    // No Intel Framework system with nvidia so far
    // TODO: Matching on PCI device would be better
    if let Some(smbios) = get_smbios() {
        if csme::me_version_from_smbios(&smbios).is_some() {
            return false;
        }
    }

    true
}

/// Brief NVIDIA details for --version output
#[cfg(feature = "nvidia")]
fn print_nvidia_details() {
    let probably_has_nvidia = probably_has_nvidia();
    let nvml = match Nvml::init() {
        Ok(nvml) => nvml,
        Err(err) => {
            if probably_has_nvidia {
                error!("Nvidia, library init fail: {:?}", err);
            }
            return;
        }
    };
    let device = match nvml.device_by_index(0) {
        Ok(device) => device,
        Err(err) => {
            if probably_has_nvidia {
                error!("Nvidia, device not found: {:?}", err);
            }
            return;
        }
    };

    println!("NVIDIA GPU");
    println!(
        "  Name:           {}",
        device.name().unwrap_or("Unknown".to_string())
    );
    println!(
        "  VBIOS Version:  {}",
        device.vbios_version().unwrap_or("Unknown".to_string())
    );
}

/// Detailed NVIDIA information for --nvidia command
#[cfg(feature = "nvidia")]
fn print_nvidia_info() {
    let probably_has_nvidia = probably_has_nvidia();
    let nvml = match Nvml::init() {
        Ok(nvml) => nvml,
        Err(err) => {
            if probably_has_nvidia {
                error!("Nvidia, library init fail: {:?}", err);
            }
            return;
        }
    };
    let device = match nvml.device_by_index(0) {
        Ok(device) => device,
        Err(err) => {
            if probably_has_nvidia {
                error!("Nvidia, device not found: {:?}", err);
            }
            return;
        }
    };

    println!("NVIDIA GPU");

    // Basic identification
    println!("Identification");
    println!(
        "  Name:              {}",
        device.name().unwrap_or("Unknown".to_string())
    );
    if let Ok(arch) = device.architecture() {
        println!("  Architecture:      {:?}", arch);
    }
    if let Ok(serial) = device.serial() {
        println!("  Serial Number:     {}", serial);
    }
    if let Ok(part_number) = device.board_part_number() {
        println!("  Part Number:       {}", part_number);
    }
    if let Ok(board_id) = device.board_id() {
        println!("  Board ID:          {}", board_id);
    }

    // Firmware versions
    println!("Firmware");
    println!(
        "  VBIOS Version:     {}",
        device.vbios_version().unwrap_or("Unknown".to_string())
    );
    println!(
        "  InfoROM Version:   {}",
        device
            .info_rom_image_version()
            .unwrap_or("Unknown".to_string())
    );

    // PCI information
    println!("PCI");
    if let Ok(pci) = device.pci_info() {
        println!("  Bus:               {:02X}", pci.bus);
        println!("  Device:            {:02X}", pci.device);
        println!("  Domain:            {:04X}", pci.domain);
        println!("  Device ID:         {:04X}", pci.pci_device_id);
        if let Some(sub_id) = pci.pci_sub_system_id {
            println!("  Subsystem ID:      {:08X}", sub_id);
        }
    }

    // Power information
    println!("Power");
    if let Ok(state) = device.performance_state() {
        println!("  Performance State: {:?}", state);
    }
    if let Ok(power) = device.power_usage() {
        println!("  Current Usage:     {:.2} W", power as f64 / 1000.0);
    }
    if let Ok(limit) = device.power_management_limit() {
        println!("  Power Limit:       {:.2} W", limit as f64 / 1000.0);
    }
    if let Ok(default) = device.power_management_limit_default() {
        println!("  Default Limit:     {:.2} W", default as f64 / 1000.0);
    }
    if let Ok(constraints) = device.power_management_limit_constraints() {
        println!(
            "  Min Limit:         {:.2} W",
            constraints.min_limit as f64 / 1000.0
        );
        println!(
            "  Max Limit:         {:.2} W",
            constraints.max_limit as f64 / 1000.0
        );
    }
    if let Ok(energy) = device.total_energy_consumption() {
        println!("  Total Energy:      {:.2} J", energy as f64 / 1000.0);
    }

    // Thermal information
    println!("Thermal");
    if let Ok(temp) = device.temperature(TemperatureSensor::Gpu) {
        println!("  GPU Temperature:   {}C", temp);
    }
    if let Ok(num_fans) = device.num_fans() {
        println!("  Number of Fans:    {}", num_fans);
    }

    // Throttling
    if let Ok(throttle) = device.current_throttle_reasons() {
        println!("Throttle Reasons");
        if throttle.is_empty() {
            println!("  None");
        } else {
            if throttle.contains(nvml_wrapper::bitmasks::device::ThrottleReasons::GPU_IDLE) {
                println!("  GPU Idle");
            }
            if throttle.contains(
                nvml_wrapper::bitmasks::device::ThrottleReasons::APPLICATIONS_CLOCKS_SETTING,
            ) {
                println!("  Applications Clocks Setting");
            }
            if throttle.contains(nvml_wrapper::bitmasks::device::ThrottleReasons::SW_POWER_CAP) {
                println!("  Software Power Cap");
            }
            if throttle.contains(nvml_wrapper::bitmasks::device::ThrottleReasons::HW_SLOWDOWN) {
                println!("  Hardware Slowdown");
            }
            if throttle.contains(nvml_wrapper::bitmasks::device::ThrottleReasons::SYNC_BOOST) {
                println!("  Sync Boost");
            }
            if throttle
                .contains(nvml_wrapper::bitmasks::device::ThrottleReasons::SW_THERMAL_SLOWDOWN)
            {
                println!("  Software Thermal Slowdown");
            }
            if throttle
                .contains(nvml_wrapper::bitmasks::device::ThrottleReasons::HW_THERMAL_SLOWDOWN)
            {
                println!("  Hardware Thermal Slowdown");
            }
            if throttle
                .contains(nvml_wrapper::bitmasks::device::ThrottleReasons::HW_POWER_BRAKE_SLOWDOWN)
            {
                println!("  Hardware Power Brake Slowdown");
            }
            if throttle
                .contains(nvml_wrapper::bitmasks::device::ThrottleReasons::DISPLAY_CLOCK_SETTING)
            {
                println!("  Display Clock Setting");
            }
        }
    }

    // Utilization
    println!("Utilization");
    if let Ok(util) = device.utilization_rates() {
        println!("  GPU:               {}%", util.gpu);
        println!("  Memory:            {}%", util.memory);
    }

    // Memory information
    println!("Memory");
    if let Ok(mem) = device.memory_info() {
        let total_gb = mem.total as f64 / (1024.0 * 1024.0 * 1024.0);
        let used_gb = mem.used as f64 / (1024.0 * 1024.0 * 1024.0);
        let free_gb = mem.free as f64 / (1024.0 * 1024.0 * 1024.0);
        println!("  Total:             {:.2} GB", total_gb);
        println!("  Used:              {:.2} GB", used_gb);
        println!("  Free:              {:.2} GB", free_gb);
    }

    // Display status
    println!("Display");
    if let Ok(active) = device.is_display_active() {
        println!("  Active:            {}", if active { "Yes" } else { "No" });
    }
    if let Ok(connected) = device.is_display_connected() {
        println!(
            "  Connected:         {}",
            if connected { "Yes" } else { "No" }
        );
    }
}

fn print_esrt() {
    if let Some(esrt) = esrt::get_esrt() {
        esrt::print_esrt(&esrt);
    } else {
        println!("Could not find and parse ESRT table.");
    }
}

fn flash_ec(ec: &CrosEc, ec_bin_path: &str, flash_type: EcFlashType, dry_run: bool) {
    #[cfg(feature = "uefi")]
    let data = crate::fw_uefi::fs::shell_read_file(ec_bin_path);
    #[cfg(not(feature = "uefi"))]
    let data: Option<Vec<u8>> = {
        match fs::read(ec_bin_path) {
            Ok(data) => Some(data),
            // TODO: Perhaps a more user-friendly error
            Err(e) => {
                println!("Error {:?}", e);
                None
            }
        }
    };

    if let Some(data) = data {
        println!("File");
        println!("  Size:       {:>20} B", data.len());
        println!("  Size:       {:>20} KB", data.len() / 1024);
        if let Err(err) = ec.reflash(&data, flash_type, dry_run) {
            println!("Error: {:?}", err);
        } else {
            println!("Success!");
        }
    }
}

fn dump_ec_flash(ec: &CrosEc, dump_path: &str) {
    let flash_bin = ec.get_entire_ec_flash().unwrap();

    #[cfg(not(feature = "uefi"))]
    {
        let mut file = fs::File::create(dump_path).unwrap();
        file.write_all(&flash_bin).unwrap();
    }
    #[cfg(feature = "uefi")]
    {
        let ret = crate::fw_uefi::fs::shell_write_file(dump_path, &flash_bin);
        if ret.is_err() {
            println!("Failed to dump EC FW image.");
        }
    }
}

fn dump_dgpu_eeprom(ec: &CrosEc, dump_path: &str) {
    // Read raw bytes from EEPROM
    let raw_bytes = match ec.read_ec_gpu_chunk(0x00, 256) {
        Ok(data) => data,
        Err(err) => {
            error!("Failed to read EEPROM: {:?}", err);
            return;
        }
    };

    // For stdout, just print the raw bytes
    if dump_path == "-" {
        println!("{:02X?}", raw_bytes);
        println!("Read {} bytes from EEPROM", raw_bytes.len());
        return;
    }

    // Check if header is valid by examining magic bytes
    let expected_magic = [0x32, 0xAC, 0x00, 0x00];
    let has_valid_header = raw_bytes.len() >= 4 && raw_bytes[0..4] == expected_magic;

    let flash_bin = if has_valid_header {
        // Header looks valid, try to read the full descriptor
        match ec.read_gpu_descriptor() {
            Ok(data) => data,
            Err(err) => {
                error!("GPU descriptor read failed: {:?}", err);
                println!("Falling back to raw EEPROM dump (256 bytes)");
                raw_bytes
            }
        }
    } else {
        error!(
            "GPU descriptor invalid: magic {:02X?} != expected {:02X?}",
            &raw_bytes[0..4],
            expected_magic
        );
        println!("Dumping raw EEPROM (256 bytes)");
        raw_bytes
    };

    #[cfg(not(feature = "uefi"))]
    {
        match fs::File::create(dump_path) {
            Ok(mut file) => {
                if let Err(err) = file.write_all(&flash_bin) {
                    error!("Failed to write file: {:?}", err);
                    return;
                }
            }
            Err(err) => {
                error!("Failed to create file: {:?}", err);
                return;
            }
        }
    }
    #[cfg(feature = "uefi")]
    {
        if let Err(err) = crate::fw_uefi::fs::shell_write_file(dump_path, &flash_bin) {
            error!("Failed to dump EC FW image: {:?}", err);
            return;
        }
    }
    println!("Wrote {} bytes to {}", flash_bin.len(), dump_path);
}

fn compare_version(device: Option<HardwareDeviceType>, version: String, ec: &CrosEc) -> i32 {
    println!("Target Version {:?}", version);

    if let Some(smbios) = get_smbios() {
        if let Some(bios) = smbios.structures().find_map(|r| match r {
            Ok(Structure::Bios(b)) => Some(b),
            _ => None,
        }) {
            if device == Some(HardwareDeviceType::BIOS) {
                println!("Comparing BIOS version {:?}", bios.bios_version);
                if version.to_uppercase() == bios.bios_version.to_uppercase() {
                    return 0;
                } else {
                    return 1;
                }
            }
        }
    }

    match device {
        Some(HardwareDeviceType::EC) => {
            let ver = print_err(ec.version_info()).unwrap_or_else(|| "UNKNOWN".to_string());
            println!("Comparing EC version {:?}", ver);

            if ver.contains(&version) {
                return 0;
            } else {
                return 1;
            }
        }
        Some(HardwareDeviceType::PD0) => {
            if let Ok(PdVersions::RightLeft((pd01, _pd23))) = ccgx::get_pd_controller_versions(ec) {
                let ver = pd01.active_fw_ver();
                println!("Comparing PD0 version {:?}", ver);

                if ver.contains(&version) {
                    return 0;
                } else {
                    return 1;
                }
            }
        }
        Some(HardwareDeviceType::PD1) => {
            if let Ok(PdVersions::RightLeft((_pd01, pd23))) = ccgx::get_pd_controller_versions(ec) {
                let ver = pd23.active_fw_ver();
                println!("Comparing PD1 version {:?}", ver);

                if ver.contains(&version) {
                    return 0;
                } else {
                    return 1;
                }
            }
        }
        Some(HardwareDeviceType::AcLeft) => {
            if let Ok((_right, left)) = power::is_charging(ec) {
                let ver = format!("{}", left as i32);
                println!("Comparing AcLeft {:?}", ver);
                if ver == version {
                    return 0;
                } else {
                    return 1;
                }
            } else {
                error!("Failed to get charging information");
                // Not charging is the safe default
                return 1;
            }
        }
        Some(HardwareDeviceType::AcRight) => {
            if let Ok((right, _left)) = power::is_charging(ec) {
                let ver = format!("{}", right as i32);
                println!("Comparing AcRight {:?}", ver);
                if ver == version {
                    return 0;
                } else {
                    return 1;
                }
            } else {
                error!("Failed to get charging information");
                // Not charging is the safe default
                return 1;
            }
        }
        _ => {}
    }

    if let Some(esrt) = esrt::get_esrt() {
        for entry in &esrt.entries {
            match GUID::from(entry.fw_class) {
                esrt::TGL_RETIMER01_GUID | esrt::ADL_RETIMER01_GUID | esrt::RPL_RETIMER01_GUID => {
                    if device == Some(HardwareDeviceType::RTM01) {
                        println!("Comparing RTM01 version {:?}", entry.fw_version.to_string());

                        if entry.fw_version.to_string().contains(&version) {
                            return 0;
                        }
                    }
                }
                esrt::TGL_RETIMER23_GUID | esrt::ADL_RETIMER23_GUID | esrt::RPL_RETIMER23_GUID => {
                    if device == Some(HardwareDeviceType::RTM23) {
                        println!("Comparing RTM23 version {:?}", entry.fw_version.to_string());
                        if entry.fw_version.to_string().contains(&version) {
                            return 0;
                        }
                    }
                }
                _ => {}
            }
        }
    }

    1
}

pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 {
    #[cfg(feature = "uefi")]
    {
        log::set_max_level(args.verbosity.0);
    }
    #[cfg(not(feature = "uefi"))]
    {
        // TOOD: Should probably have a custom env variable?
        // let env = Env::default()
        //     .filter("FRAMEWORK_COMPUTER_LOG")
        //     .write_style("FRAMEWORK_COMPUTER_LOG_STYLE");

        let level = args.verbosity.0.as_str();
        env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(level))
            .format_target(false)
            .format_timestamp(None)
            .init();
    }

    // Must be run before any application code to set the config
    if let (Some(pd_addrs), Some(pd_ports)) = (args.pd_addrs, args.pd_ports) {
        let platform = Platform::GenericFramework(pd_addrs, pd_ports);
        Config::set(platform);
    }

    let ec = if let Some(driver) = args.driver {
        if let Some(driver) = CrosEc::with(driver) {
            driver
        } else {
            println!("Selected driver {:?} not available.", driver);
            return 1;
        }
    } else {
        CrosEc::new()
    };

    #[cfg(feature = "uefi")]
    if args.paginate {
        enable_page_break();
    }

    if args.help {
        // Only print with uefi feature here because without clap will already
        // have printed the help by itself.
        #[cfg(feature = "uefi")]
        print_help(_allupdate);
        return 2;
    } else if args.versions {
        print_versions(&ec);
    } else if args.version {
        print_tool_version();
    } else if args.features {
        print_err(ec.get_features());
    } else if args.esrt {
        print_esrt();
    } else if let Some(compare_version_ver) = &args.compare_version {
        let compare_ret = compare_version(args.device, compare_version_ver.to_string(), &ec);
        println!("Comparison Result:  {}", compare_ret);
        return compare_ret;
    } else if args.intrusion {
        println!("Chassis status:");
        if let Some(status) = print_err(ec.get_intrusion_status()) {
            println!(
                "  Coin cell ever removed:   {}",
                status.coin_cell_ever_removed
            );
            println!("  Chassis currently open:   {}", status.currently_open);
            println!("  Chassis ever opened:      {}", status.ever_opened);
            println!("  Chassis opened:           {} times", status.total_opened);
            println!(
                "  Chassis opened while off: {} times",
                status.vtr_open_count
            );
        } else {
            println!("  Unable to tell");
        }
    } else if args.inputdeck {
        let res = match smbios::get_platform().and_then(Platform::which_family) {
            Some(PlatformFamily::Framework12) => ec.print_fw12_inputdeck_status(),
            Some(PlatformFamily::Framework13) => ec.print_fw13_inputdeck_status(),
            Some(PlatformFamily::Framework16) => ec.print_fw16_inputdeck_status(),
            // If we don't know which platform it is, we can use some heuristics
            _ => {
                // Only Framework 16 has this GPIO
                if ec.get_gpio("sleep_l").is_ok() {
                    ec.print_fw16_inputdeck_status()
                } else {
                    if let Ok(status) = ec.get_input_deck_status() {
                        println!("  Deck State:          {:?}", status.state);
                        println!(
                            "  Touchpad present:    {} ({})",
                            status.touchpad_present, status.touchpad_id
                        );
                    } else {
                        println!("  Unable to tell");
                    }
                    Ok(())
                }
            }
        };
        print_err(res);
    } else if let Some(mode) = &args.inputdeck_mode {
        println!("Set mode to: {:?}", mode);
        ec.set_input_deck_mode((*mode).into()).unwrap();
    } else if args.expansion_bay {
        if let Err(err) = ec.check_bay_status() {
            error!("{:?}", err);
        }
        if let Ok(header) = ec.read_gpu_desc_header() {
            println!("  Expansion Bay EEPROM");
            println!(
                "    Valid:       {:?}",
                header.magic == [0x32, 0xAC, 0x00, 0x00]
            );
            println!("    HW Version:  {}.{}", { header.hardware_version }, {
                header.hardware_revision
            });
            if log_enabled!(Level::Info) {
                println!("    Hdr Length   {} B", { header.length });
                println!("    Desc Ver:    {}.{}", { header.desc_ver_major }, {
                    header.desc_ver_minor
                });
                println!("    Serialnumber:{:X?}", { header.serial });
                println!("    Desc Length: {} B", { header.descriptor_length });
                println!("    Desc CRC:    {:X}", { header.descriptor_crc32 });
                println!("    Hdr CRC:     {:X}", { header.crc32 });
            }
        }
    } else if args.nvidia {
        #[cfg(feature = "nvidia")]
        print_nvidia_info();
        #[cfg(not(feature = "nvidia"))]
        error!("Not built with nvidia feature");
    } else if let Some(maybe_limit) = args.charge_limit {
        print_err(handle_charge_limit(&ec, maybe_limit));
    } else if let Some((limit, soc)) = args.charge_current_limit {
        print_err(ec.set_charge_current_limit(limit, soc));
    } else if let Some((limit, soc)) = args.charge_rate_limit {
        print_err(ec.set_charge_rate_limit(limit, soc));
    } else if let Some(gpio_name) = &args.get_gpio {
        if let Some(gpio_name) = gpio_name {
            print!("GPIO {}: ", gpio_name);
            if let Ok(value) = ec.get_gpio(gpio_name) {
                println!("{:?}", value);
            } else {
                println!("Not found");
            }
        } else {
            print_err(ec.get_all_gpios());
        }
    } else if let Some(maybe_led_level) = &args.fp_led_level {
        print_err(handle_fp_led_level(&ec, *maybe_led_level));
    } else if let Some(maybe_brightness) = &args.fp_brightness {
        print_err(handle_fp_brightness(&ec, *maybe_brightness));
    } else if let Some(Some(kblight)) = args.kblight {
        if kblight > 100 {
            error!("--kblight must be percentage 0-100");
        } else {
            ec.set_keyboard_backlight(kblight);
        }
    } else if let Some(None) = args.kblight {
        print!("Keyboard backlight: ");
        if let Some(percentage) = print_err(ec.get_keyboard_backlight()) {
            println!("{}%", percentage);
        } else {
            println!("Unable to tell");
        }
    } else if let Some((row, col, scanset)) = args.remap_key {
        print_err(ec.remap_key(row, col, scanset));
    } else if !args.rgbkbd.is_empty() {
        if args.rgbkbd.len() < 2 {
            println!(
                "Must provide at least 2 arguments. Provided only: {}",
                args.rgbkbd.len()
            );
        } else {
            let start_key = args.rgbkbd[0] as u8;
            let colors = args.rgbkbd[1..].iter().map(|color| RgbS {
                r: ((color & 0x00FF0000) >> 16) as u8,
                g: ((color & 0x0000FF00) >> 8) as u8,
                b: (color & 0x000000FF) as u8,
            });
            ec.rgbkbd_set_color(start_key, colors.collect()).unwrap();
        }
    } else if let Some(enable) = args.ps2_enable {
        print_err(ec.ps2_emulation_enable(enable));
    } else if let Some(tablet_arg) = &args.tablet_mode {
        let mode = match tablet_arg {
            TabletModeArg::Auto => TabletModeOverride::Default,
            TabletModeArg::Tablet => TabletModeOverride::ForceTablet,
            TabletModeArg::Laptop => TabletModeOverride::ForceClamshell,
        };
        ec.set_tablet_mode(mode);
    } else if let Some(_enable) = &args.touchscreen_enable {
        #[cfg(feature = "hidapi")]
        if touchscreen::enable_touch(*_enable).is_none() {
            error!("Failed to enable/disable touch");
        }
    } else if args.stylus_battery {
        #[cfg(feature = "hidapi")]
        print_stylus_battery_level();
        #[cfg(not(feature = "hidapi"))]
        error!("Not build with hidapi feature");
    } else if let Some(console_arg) = &args.console {
        match console_arg {
            ConsoleArg::Follow => {
                // Ignore result because we only finish when it crashes
                let _res = ec.console_read();
            }
            ConsoleArg::Recent => match ec.console_read_one() {
                Ok(output) => println!("{}", output),
                Err(err) => println!("Failed to read console: {:?}", err),
            },
        }
    } else if let Some(reboot_arg) = &args.reboot_ec {
        match reboot_arg {
            RebootEcArg::Reboot => match ec.reboot_ec(RebootEcCmd::ColdReboot) {
                Ok(_) => {}
                Err(err) => println!("Failed: {:?}", err),
            },
            RebootEcArg::JumpRo => match ec.jump_ro() {
                Ok(_) => {}
                Err(err) => println!("Failed: {:?}", err),
            },
            RebootEcArg::JumpRw => match ec.jump_rw() {
                Ok(_) => {}
                Err(err) => println!("Failed: {:?}", err),
            },
            RebootEcArg::CancelJump => match ec.cancel_jump() {
                Ok(_) => {}
                Err(err) => println!("Failed: {:?}", err),
            },
            RebootEcArg::DisableJump => match ec.disable_jump() {
                Ok(_) => {}
                Err(err) => println!("Failed: {:?}", err),
            },
        }
    } else if let Some(delay) = &args.ec_hib_delay {
        if let Some(delay) = delay {
            print_err(ec.set_ec_hib_delay(*delay));
        }
        print_err(ec.get_ec_hib_delay());
    } else if args.uptimeinfo {
        print_err(ec.get_uptime_info());
    } else if args.s0ix_counter {
        if let Some(counter) = print_err(ec.get_s0ix_counter()) {
            println!("s0ix_counter: {}", counter);
        } else {
            println!("s0ix_counter: Unknown");
        }
    } else if args.test {
        println!("Self-Test");
        let result = selftest(&ec);
        if result.is_none() {
            println!("FAILED!!");
            return 1;
        }
    } else if args.test_retimer {
        println!("Retimer Self-Test");
        if let Err(err) = selftest_retimer(&ec) {
            println!("  Failed: {:?}", err);
        }
    } else if args.boardid {
        print_board_ids(&ec);
    } else if args.power {
        return power::get_and_print_power_info(&ec);
    } else if args.thermal {
        power::print_thermal(&ec);
    } else if args.sensors {
        power::print_sensors(&ec);
    } else if let Some((fan, percent)) = args.fansetduty {
        print_err(ec.fan_set_duty(fan, percent));
    } else if let Some((fan, rpm)) = args.fansetrpm {
        print_err(ec.fan_set_rpm(fan, rpm));
    } else if let Some(Some(fan_id)) = args.autofanctrl {
        print_err(ec.autofanctrl(Some(fan_id)));
    } else if let Some(None) = args.autofanctrl {
        print_err(ec.autofanctrl(None));
    } else if args.pdports {
        power::get_and_print_cypd_pd_info(&ec);
    } else if args.pdports_chromebook {
        power::get_and_print_pd_info(&ec);
    } else if args.info {
        smbios_info();
    } else if let Some(dump_path) = &args.meinfo {
        let verbose = args.verbosity.0 >= log::LevelFilter::Warn;
        me_info(verbose, dump_path.as_deref());
    } else if args.pd_info {
        print_pd_details(&ec);
    } else if let Some(pd) = args.pd_reset {
        println!("Resetting PD {}...", pd);
        print_err(match pd {
            0 => PdController::new(PdPort::Right01, ec.clone()).reset_device(),
            1 => PdController::new(PdPort::Left23, ec.clone()).reset_device(),
            2 => PdController::new(PdPort::Back, ec.clone()).reset_device(),
            _ => {
                error!("PD {} does not exist", pd);
                Ok(())
            }
        });
    } else if let Some(pd) = args.pd_disable {
        println!("Disabling PD {}...", pd);
        print_err(match pd {
            0 => PdController::new(PdPort::Right01, ec.clone()).enable_ports(false),
            1 => PdController::new(PdPort::Left23, ec.clone()).enable_ports(false),
            2 => PdController::new(PdPort::Back, ec.clone()).enable_ports(false),
            _ => {
                error!("PD {} does not exist", pd);
                Ok(())
            }
        });
    } else if let Some(pd) = args.pd_enable {
        println!("Enabling PD {}...", pd);
        print_err(match pd {
            0 => PdController::new(PdPort::Right01, ec.clone()).enable_ports(true),
            1 => PdController::new(PdPort::Left23, ec.clone()).enable_ports(true),
            2 => PdController::new(PdPort::Back, ec.clone()).enable_ports(true),
            _ => {
                error!("PD {} does not exist", pd);
                Ok(())
            }
        });
    } else if args.dp_hdmi_info {
        #[cfg(feature = "hidapi")]
        print_dp_hdmi_details(true);
    } else if let Some(pd_bin_path) = &args.dp_hdmi_update {
        #[cfg(feature = "hidapi")]
        flash_dp_hdmi_card(pd_bin_path);
        #[cfg(not(feature = "hidapi"))]
        let _ = pd_bin_path;
    } else if args.audio_card_info {
        #[cfg(feature = "rusb")]
        print_audio_card_details();
    } else if args.privacy {
        if let Some((mic, cam)) = print_err(ec.get_privacy_info()) {
            println!("Privacy Slider (Black = Device Connected; Red = Device Disconnected)");
            println!(
                "  Microphone:  {}",
                if mic { "Connected" } else { "Disconnected" }
            );
            println!(
                "  Camera:      {}",
                if cam { "Connected" } else { "Disconnected" }
            );
        } else {
            println!("Not all EC versions support this comand.")
        };
    } else if let Some((command_id, command_version, ref data)) = args.host_command {
        match ec.send_command(command_id, command_version, data) {
            Ok(response) => {
                println!("Response ({} bytes):", response.len());
                if response.is_empty() {
                    println!("  (empty)");
                } else {
                    util::print_multiline_buffer(&response, 0);
                }
            }
            Err(e) => println!("EC command failed: {:?}", e),
        }
    } else if let Some(pd_bin_path) = &args.pd_bin {
        #[cfg(feature = "uefi")]
        let data: Option<Vec<u8>> = crate::fw_uefi::fs::shell_read_file(pd_bin_path);
        #[cfg(not(feature = "uefi"))]
        let data = match fs::read(pd_bin_path) {
            Ok(data) => Some(data),
            // TODO: Perhaps a more user-friendly error
            Err(e) => {
                println!("Error {:?}", e);
                None
            }
        };

        if let Some(data) = data {
            println!("File");
            println!("  Size:       {:>20} B", data.len());
            println!("  Size:       {:>20} KB", data.len() / 1024);
            analyze_ccgx_pd_fw(&data);
        }
    } else if let Some(ec_bin_path) = &args.ec_bin {
        #[cfg(feature = "uefi")]
        let data: Option<Vec<u8>> = crate::fw_uefi::fs::shell_read_file(ec_bin_path);
        #[cfg(not(feature = "uefi"))]
        let data = match fs::read(ec_bin_path) {
            Ok(data) => Some(data),
            // TODO: Perhaps a more user-friendly error
            Err(e) => {
                println!("Error {:?}", e);
                None
            }
        };

        if let Some(data) = data {
            println!("File");
            println!("  Size:       {:>20} B", data.len());
            println!("  Size:       {:>20} KB", data.len() / 1024);
            analyze_ec_fw(&data);
        }
    } else if let Some(capsule_path) = &args.capsule {
        #[cfg(feature = "uefi")]
        let data: Option<Vec<u8>> = crate::fw_uefi::fs::shell_read_file(capsule_path);
        #[cfg(not(feature = "uefi"))]
        let data = match fs::read(capsule_path) {
            Ok(data) => Some(data),
            // TODO: Perhaps a more user-friendly error
            Err(e) => {
                println!("Error {:?}", e);
                None
            }
        };

        if let Some(data) = data {
            println!("File");
            println!("  Size:       {:>20} B", data.len());
            println!("  Size:       {:>20} KB", data.len() / 1024);
            if let Some(header) = analyze_capsule(&data) {
                if header.capsule_guid == CGuid::from(esrt::WINUX_GUID) {
                    let ux_header = capsule::parse_ux_header(&data);
                    if let Some(dump_path) = &args.dump {
                        // TODO: Better error handling, rather than just panicking
                        capsule::dump_winux_image(&data, &ux_header, dump_path);
                    }
                }
            } else {
                println!("Capsule is invalid.");
            }
        }
    } else if let Some(capsule_path) = &args.h2o_capsule {
        #[cfg(feature = "uefi")]
        let data = crate::fw_uefi::fs::shell_read_file(capsule_path);
        #[cfg(not(feature = "uefi"))]
        let data = match fs::read(capsule_path) {
            Ok(data) => Some(data),
            // TODO: Perhaps a more user-friendly error
            Err(e) => {
                println!("Error {:?}", e);
                None
            }
        };

        if let Some(data) = data {
            println!("File");
            println!("  Size:       {:>20} B", data.len());
            println!("  Size:       {:>20} KB", data.len() / 1024);
            if let Some(cap) = find_bios_version(&data) {
                println!("  BIOS Platform:{:>18}", cap.platform);
                println!("  BIOS Version: {:>18}", cap.version);
            }
            if let Some(ec_bin) = find_ec_in_bios_cap(&data) {
                debug!("Found EC binary in BIOS capsule");
                analyze_ec_fw(ec_bin);
            } else {
                debug!("Didn't find EC binary in BIOS capsule");
            }
            if let Some(pd_bin) = find_pd_in_bios_cap(&data) {
                debug!("Found PD binary in BIOS capsule");
                analyze_ccgx_pd_fw(pd_bin);
            } else {
                debug!("Didn't find PD binary in BIOS capsule");
            }
        }
    } else if let Some(dump_path) = &args.dump_ec_flash {
        println!("Dumping to {}", dump_path);
        // TODO: Should have progress indicator
        dump_ec_flash(&ec, dump_path);
    } else if let Some(ec_bin_path) = &args.flash_full_ec {
        if args.force {
            flash_ec(&ec, ec_bin_path, EcFlashType::Full, args.dry_run);
        } else {
            error!("Flashing full EC flash is unsafe. Use --flash-ec instead");
        }
    } else if let Some(ec_bin_path) = &args.flash_ec {
        if args.force {
            flash_ec(&ec, ec_bin_path, EcFlashType::Both, args.dry_run);
        } else {
            error!("Flashing EC RO region is unsafe. Use --flash-ec-rw instead");
        }
    } else if let Some(ec_bin_path) = &args.flash_ro_ec {
        if args.force {
            flash_ec(&ec, ec_bin_path, EcFlashType::Ro, args.dry_run);
        } else {
            error!("Flashing EC RO region is unsafe. Use --flash-ec-rw instead");
        }
    } else if let Some(ec_bin_path) = &args.flash_rw_ec {
        flash_ec(&ec, ec_bin_path, EcFlashType::Rw, args.dry_run);
    } else if let Some(hash_file) = &args.hash {
        println!("Hashing file: {}", hash_file);
        #[cfg(feature = "uefi")]
        let data = crate::fw_uefi::fs::shell_read_file(hash_file);
        #[cfg(not(feature = "uefi"))]
        let data = match fs::read(hash_file) {
            Ok(data) => Some(data),
            // TODO: Perhaps a more user-friendly error
            Err(e) => {
                println!("Error {:?}", e);
                None
            }
        };
        if let Some(data) = data {
            println!("File");
            println!("  Size:       {:>20} B", data.len());
            println!("  Size:       {:>20} KB", data.len() / 1024);
            hash(&data);
        }
    } else if let Some(gpu_descriptor) = &args.flash_gpu_descriptor {
        let res = ec.set_gpu_serial(gpu_descriptor.0, gpu_descriptor.1.to_ascii_uppercase());
        match res {
            Ok(1) => println!("GPU Descriptor successfully written"),
            Ok(x) => println!("GPU Descriptor write failed with status code:  {}", x),
            Err(err) => println!("GPU Descriptor write failed with error:  {:?}", err),
        }
    } else if let Some(gpu_descriptor_file) = &args.flash_gpu_descriptor_file {
        if matches!(
            smbios::get_family(),
            Some(PlatformFamily::Framework16) | None
        ) {
            #[cfg(feature = "uefi")]
            let data: Option<Vec<u8>> = crate::fw_uefi::fs::shell_read_file(gpu_descriptor_file);
            #[cfg(not(feature = "uefi"))]
            let data = match fs::read(gpu_descriptor_file) {
                Ok(data) => Some(data),
                // TODO: Perhaps a more user-friendly error
                Err(e) => {
                    println!("Error {:?}", e);
                    None
                }
            };
            if let Some(data) = data {
                println!("File");
                println!("  Size:       {:>20} B", data.len());
                println!("  Size:       {:>20} KB", data.len() / 1024);
                let res = ec.set_gpu_descriptor(&data, args.dry_run);
                match res {
                    Ok(()) => println!("GPU Descriptor successfully written"),
                    Err(err) => println!("GPU Descriptor write failed with error:  {:?}", err),
                }
            }
        } else {
            println!("Unsupported on this platform");
        }
    } else if let Some(dump_path) = &args.dump_gpu_descriptor_file {
        if dump_path != "-" {
            println!("Dumping to {}", dump_path);
        }
        dump_dgpu_eeprom(&ec, dump_path);
    }

    0
}

// Only on UEFI. Clap prints this by itself
#[cfg(feature = "uefi")]
fn print_help(updater: bool) {
    println!(
        r#"Swiss army knife for Framework laptops

Usage: framework_tool [OPTIONS]

Options:
  -v, --verbose...           More output per occurrence
  -q, --quiet...             Less output per occurrence
      --versions             List current firmware versions
      --version              Show tool version information (Add -vv for more detailed information)
      --features             Show features support by the firmware
      --esrt                 Display the UEFI ESRT table
      --device <DEVICE>      Device used to compare firmware version [possible values: bios, ec, pd0, pd1, rtm01, rtm23]
      --compare-version      Version string used to match firmware version (use with --device)
      --power                Show current power status (battery and AC)
      --thermal              Print thermal information (Temperatures and Fan speed)
      --sensors              Print sensor information (ALS, G-Sensor)
      --fansetduty           Set fan duty cycle (0-100%)
      --fansetrpm            Set fan RPM (limited by EC fan table max RPM)
      --autofanctrl [<FANID>]Turn on automatic fan speed control (optionally provide fan index)
      --pdports              Show USB-C PD port state
      --pdports-chromebook   Show PD port info (generic Chromium EC)
      --info                 Show info from SMBIOS (Only on UEFI)
      --meinfo [<DUMPFILE>]   Show Intel ME information (from SMBIOS type 0xDB)
      --pd-info              Show details about the PD controllers
      --pd-reset <PD_NUM>    Reset a specific PD controller (for debugging only)
      --pd-disable <PD_NUM>  Disable all ports on a specific PD controller (for debugging only)
      --pd-enable <PD_NUM>   Enable all ports on a specific PD controller (for debugging only)
      --privacy              Show privacy switch statuses (camera and microphone)
      --pd-bin <PD_BIN>      Parse versions from PD firmware binary file
      --ec-bin <EC_BIN>      Parse versions from EC firmware binary file
      --capsule <CAPSULE>    Parse UEFI Capsule information from binary file
      --dump <DUMP>          Dump extracted UX capsule bitmap image to a file
      --h2o-capsule <H2O_CAPSULE>      Parse UEFI Capsule information from binary file
      --dump-ec-flash <DUMP_EC_FLASH>  Dump EC flash contents
      --flash-ec <FLASH_EC>            Flash EC with new firmware from file
      --flash-ro-ec <FLASH_EC>         Flash EC with new firmware from file
      --flash-rw-ec <FLASH_EC>         Flash EC with new firmware from file
      --reboot-ec            Control EC RO/RW jump [possible values: reboot, jump-ro, jump-rw, cancel-jump, disable-jump]
      --ec-hib-delay [<SECONDS>]   Get or set EC hibernate delay (S5 to G3)
      --uptimeinfo           Show EC uptime information
      --s0ix-counter         Show S0ix counter
      --intrusion            Show status of intrusion switch
      --inputdeck            Show status of the input deck
      --inputdeck-mode       Set input deck power mode [possible values: auto, off, on] (Framework 12, 13, 16)
      --expansion-bay        Show status of the expansion bay (Framework 16 only)
      --nvidia               Show NVIDIA GPU information (Framework 16 only)
      --charge-limit [<VAL>] Get or set battery charge limit (Percentage number as arg, e.g. '100')
      --charge-current-limit [<VAL>] Get or set battery current charge limit (Percentage number as arg, e.g. '100')
      --charge-rate-limit [<VAL>]   Set max charge rate limit
      --get-gpio <GET_GPIO>  Get GPIO value by name or all, if no name provided
      --fp-led-level [<VAL>] Get or set fingerprint LED brightness level [possible values: high, medium, low]
      --fp-brightness [<VAL>]Get or set fingerprint LED brightness percentage
      --kblight [<KBLIGHT>]  Set keyboard backlight percentage or get, if no value provided
      --remap-key <ROW> <COL> <SCANCODE>
                             Remap a key by changing the scancode
      --rgbkbd <START> <HEXCOLOR> [<HEXCOLOR> ...]
                             Set the color of a key to RGB. Multiple colors for adjacent keys can be set at once
      --tablet-mode <MODE>   Set tablet mode override [possible values: auto, tablet, laptop]
      --console <CONSOLE>    Get EC console, choose whether recent or to follow the output [possible values: recent, follow]
      --hash <HASH>          Hash a file of arbitrary data
      --flash-gpu-descriptor <MAGIC> <18 DIGIT SN> Overwrite the GPU bay descriptor SN and type.
      --flash-gpu-descriptor-file <DESCRIPTOR_FILE> Write the GPU bay descriptor with a descriptor file.
      --dump-gpu-descriptor-file <DESCRIPTOR_FILE> Dump the GPU bay descriptor to a file
  -f, --force                Force execution of an unsafe command - may render your hardware unbootable!
      --dry-run              Simulate execution of a command (e.g. --flash-ec)
      --pd-addrs <PD_ADDR_LEFT> <PD_ADDR_RIGHT>  <PD_ADDR_BACK>
          Specify I2C addresses of the PD chips (Advanced)
      --pd-ports <PD_PORT_LEFT> <PD_PORT_RIGHT>  <PD_PORT_BACK>
          Specify I2C ports of the PD chips (Advanced)
      --has-mec <HAS_MEC>
          Specify the type of EC chip (MEC/MCHP or other) [possible values: true, false]
      --host-command <CMD_ID> <VERSION> [DATA...]
                             Send an EC host command
  -t, --test                 Run self-test to check if interaction with EC is possible
      --test-retimer         Run self-test to check if interaction with retimers is possible
      --boardid              Print all board IDs
  -h, --help                 Print help information
  -b                         Print output one screen at a time
    "#
    );
    if updater {
        println!(
            r#"
        --allupdate   - Run procedure to update everything (Involves some manual steps)
    "#
        );
    }
    // TODO: Not supported yet
    //println!(
    //    r#"
    //    --raw-command - Send a raw command to the EC
    //                    Example: raw-command 0x3E14
    //"#
    //);
}

/// Useful to hash update files to check integrity
fn hash(data: &[u8]) {
    let mut sha256_hasher = Sha256::new();
    let mut sha384_hasher = Sha384::new();
    let mut sha512_hasher = Sha512::new();

    sha256_hasher.update(data);
    sha384_hasher.update(data);
    sha512_hasher.update(data);

    let sha256 = &sha256_hasher.finalize()[..];
    let sha384 = &sha384_hasher.finalize()[..];
    let sha512 = &sha512_hasher.finalize()[..];

    println!("Hashes");
    print!("  SHA256:  ");
    util::print_buffer(sha256);
    print!("  SHA384:  ");
    util::print_buffer(sha384);
    print!("  SHA512:  ");
    util::print_buffer(sha512);
}

fn print_board_ids(ec: &CrosEc) {
    println!("Board IDs");
    println!(
        "  Mainboard:    {:?}",
        ec.read_board_id_hc(BoardIdType::Mainboard)
    );
    println!(
        "  PowerButton:  {:?}",
        ec.read_board_id_hc(BoardIdType::PowerButtonBoard)
    );
    println!(
        "  Touchpad:     {:?}",
        ec.read_board_id_hc(BoardIdType::Touchpad)
    );
    println!(
        "  AudioBoard:   {:?}",
        ec.read_board_id_hc(BoardIdType::AudioBoard)
    );
    println!(
        "  dGPU0:        {:?}",
        ec.read_board_id_hc(BoardIdType::DGpu0)
    );
    println!(
        "  dGPU1:        {:?}",
        ec.read_board_id_hc(BoardIdType::DGpu1)
    );
}

fn selftest(ec: &CrosEc) -> Option<()> {
    if let Some(platform) = smbios::get_platform() {
        println!("  SMBIOS Platform:     {:?}", platform);
    } else {
        println!("  SMBIOS Platform:     Unknown");
        println!();
        println!("Specify custom platform parameters with --pd-ports --pd-addrs");
        return None;
    };

    println!("  Dump EC memory region");
    if let Some(mem) = ec.dump_mem_region() {
        util::print_multiline_buffer(&mem, 0);
    } else {
        println!("    Failed to read EC memory region");
        return None;
    }

    println!("  Checking EC memory mapped magic bytes");
    print_err(ec.check_mem_magic())?;
    println!("  Verified that Framework EC is present!");

    println!("  Reading EC Build Version");
    print_err(ec.version_info())?;

    print!("  Reading EC Flash by EC");
    ec.flash_version()?;
    println!(" - OK");

    println!("  Reading EC Flash directly - See below");
    ec.test_ec_flash_read().ok()?;

    print!("  Getting power info from EC");
    power::power_info(ec)?;
    println!(" - OK");

    println!("  Getting AC info from EC");
    // All our laptops have at least 4 PD ports so far
    if power::get_pd_info(ec, 4).iter().any(|x| x.is_err()) {
        println!("    Failed to get PD Info from EC");
        return None;
    }

    print!("Reading PD Version from EC");
    if let Err(err) = power::read_pd_version(ec) {
        // TGL does not have this command, so we have to ignore it
        if err != EcError::Response(EcResponseStatus::InvalidCommand) {
            println!();
            println!("Err: {:?}", err);
        } else {
            println!(" - Skipped");
        }
    } else {
        println!(" - OK");
    }

    let pd_01 = PdController::new(PdPort::Right01, ec.clone());
    let pd_23 = PdController::new(PdPort::Left23, ec.clone());
    print!("  Getting PD01 info through I2C tunnel");
    print_err(pd_01.get_silicon_id())?;
    print_err(pd_01.get_device_info())?;
    print_err(pd_01.get_fw_versions())?;
    println!(" - OK");
    print!("  Getting PD23 info through I2C tunnel");
    print_err(pd_23.get_silicon_id())?;
    print_err(pd_23.get_device_info())?;
    print_err(pd_23.get_fw_versions())?;
    println!(" - OK");

    Some(())
}

// Platforms that have Retimers
// Retimer I2C is always connected to the CPU, except for the Framework 16 dGPU retimer.
//
// - Framework 12
//   - No Retimer, only retimer for both left ports (no firmware)
// - Framework 13 Intel
//   - One Intel retimer for each port (with firmware)
// - Framework 13 AMD 7040
//   - Kandou Retimer on top two ports (no firmware)
//   - Analogix Retimer on bottom two ports (no firmware)
// - Framework 13 AMD AI 300
//   - Parade Retimer on top two ports (with firmware)
//   - Analogix Retimer on bottom two ports (no firmware)
// - Framework 16 AMD 7040
//   - Kandou Retimer on top two ports (no firmware)
//   - Analogix Retimer on lower and middle left ports (no firmware)
// - Framework 16 AMD AI 300
//   - Parade Retimer on top two ports (with firmware)
// - Framework 16 AMD dGPU
//   - None
// - Framework 16 NVIDIA dGPU
//   - Parade Retimer
// - Framework Desktop
//   - Parade Retimer on both back ports (with firmware)
fn selftest_retimer(ec: &CrosEc) -> EcResult<()> {
    // TODO: Make sure that it can work for the NVIDIA dGPU retimer and increase to 3
    for i in 0..2 {
        let update_mode = ec.retimer_in_fwupd_mode(i);
        if update_mode == Err(EcError::Response(EcResponseStatus::InvalidParameter)) {
            println!("  Retimer status not supported on this platform. Cannot test");
            return Ok(());
        }
        println!("  Retimers on PD Controller {}", i);
        println!(
            "    In update mode: {:?}",
            ec.retimer_in_fwupd_mode(i).unwrap()
        );
        if update_mode? {
            println!("      Disabling it to start test.");
            ec.retimer_enable_fwupd(i, false)?;
        }

        println!("    Enabling update mode");
        let success = ec.retimer_enable_fwupd(i, true);
        println!(
            "    In update mode: {:?}",
            ec.retimer_in_fwupd_mode(i).unwrap()
        );

        println!("    Disabling update mode");
        ec.retimer_enable_fwupd(i, false)?;
        os_specific::sleep(100);
        println!(
            "    In update mode: {:?}",
            ec.retimer_in_fwupd_mode(i).unwrap()
        );
        success?;
    }
    Ok(())
}

fn smbios_info() {
    println!("Summary");
    println!("  Is Framework: {}", is_framework());
    if let Some(platform) = smbios::get_platform() {
        println!("  Platform:     {:?}", platform);
    } else {
        println!("  Platform:     Unknown",);
    }

    let smbios = get_smbios();
    if smbios.is_none() {
        error!("Failed to find SMBIOS");
        return;
    }
    for result in smbios.unwrap().structures() {
        match result {
            Ok(Structure::Bios(data)) => {
                println!("BIOS Information");
                if !data.vendor.is_empty() {
                    println!("  Vendor:       {}", data.vendor);
                }
                if !data.bios_version.is_empty() {
                    println!("  Version:      {}", data.bios_version);
                }
                if !data.bios_release_date.is_empty() {
                    println!("  Release Date: {}", data.bios_release_date);
                }
            }
            Ok(Structure::System(data)) => {
                println!("System Information");
                if !data.version.is_empty() {
                    let version = data.version;
                    // Assumes it's ASCII, which is guaranteed by SMBIOS
                    let config_digit0 = &version[0..1];
                    let config_digit0 = u8::from_str_radix(config_digit0, 16);
                    if let Ok(version_config) =
                        config_digit0.map(<ConfigDigit0 as FromPrimitive>::from_u8)
                    {
                        println!("  Version:      {:?} ({})", version_config, version);
                    } else {
                        println!("  Version:      '{}'", version);
                    }
                }
                if !data.manufacturer.is_empty() {
                    println!("  Manufacturer: {}", data.manufacturer);
                }
                if !data.product.is_empty() {
                    println!("  Product Name: {}", data.product);
                }
                if let Some(wakeup) = data.wakeup {
                    println!("  Wake-Up-Type: {:?}", wakeup);
                }
                if let Some(sku) = data.sku {
                    if !sku.is_empty() {
                        println!("  SKU Number:   {}", sku);
                    }
                }
                if !data.serial.is_empty() {
                    println!("  Serial Number:{}", data.serial);
                }
                if let Some(family) = data.family {
                    if !family.is_empty() {
                        println!("  Family:       {}", family);
                    }
                }
            }
            Ok(Structure::Enclosure(data)) => {
                println!("System Chassis Information");
                println!("  Type:         {}", data.enclosure_type);
            }
            Ok(Structure::BaseBoard(data)) => {
                println!("BaseBoard Information");
                if !data.version.is_empty() {
                    let version = data.version;
                    // Assumes it's ASCII, which is guaranteed by SMBIOS
                    let config_digit0 = &version[0..1];
                    let config_digit0 = u8::from_str_radix(config_digit0, 16);
                    if let Ok(version_config) =
                        config_digit0.map(<ConfigDigit0 as FromPrimitive>::from_u8)
                    {
                        println!("  Version:      {:?} ({})", version_config, version);
                    } else {
                        println!("  Version:      '{}'", version);
                    }
                }
                if !data.manufacturer.is_empty() {
                    println!("  Manufacturer: {}", data.manufacturer);
                }
                if !data.product.is_empty() {
                    println!("  Product:      {}", data.product);
                }
                if !data.serial.is_empty() {
                    println!("  Serial Number:{}", data.serial);
                }
            }
            _ => {}
        }
    }
}

fn me_info(verbose: bool, dump_path: Option<&str>) {
    let smbios = if let Some(path) = dump_path {
        #[cfg(feature = "uefi")]
        let data: Option<Vec<u8>> = crate::fw_uefi::fs::shell_read_file(path);
        #[cfg(not(feature = "uefi"))]
        let data = match std::fs::read(path) {
            Ok(data) => Some(data),
            Err(e) => {
                error!("Failed to read SMBIOS dump file '{}': {}", path, e);
                None
            }
        };
        data.and_then(|d| smbios::SmbiosStore::from_table_data(d, 3, 0))
    } else {
        get_smbios()
    };
    if smbios.is_none() {
        error!("Failed to get SMBIOS data");
        return;
    }
    let smbios = smbios.unwrap();

    // Track ME family for bootguard parsing
    let mut me_family: Option<csme::MeFamily> = None;

    // Try to get ME version from sysfs first (Linux only, live system only)
    #[cfg(target_os = "linux")]
    if dump_path.is_none() {
        if let Ok(csme_info) = csme::csme_from_sysfs() {
            println!("Intel ME Information (from sysfs)");
            println!("  Enabled:          {}", csme_info.enabled);
            println!("  Firmware Version: {}", csme_info.main_ver);
            if csme_info.main_ver != csme_info.recovery_ver
                || csme_info.main_ver != csme_info.fitc_ver
            {
                println!("  Recovery Version: {}", csme_info.recovery_ver);
                println!("  FITC Version:     {}", csme_info.fitc_ver);
            }
            let family = csme::MeFamily::from_version(csme_info.main_ver.major);
            println!("  ME Family:        {}", family);
            me_family = Some(family);
        }
    }

    // Get ME version from SMBIOS type 0xDD (FVI)
    let smbios_version = csme::me_version_from_smbios(&smbios);
    if let Some(ref fvi_version) = smbios_version {
        // If sysfs wasn't available, use SMBIOS version as primary
        if me_family.is_none() {
            println!("Intel ME Version (from SMBIOS Type 0xDD)");
            println!("  Firmware Version: {}", fvi_version);
            let family = csme::MeFamily::from_version(fvi_version.major as u32);
            println!("  ME Family:        {}", family);
            me_family = Some(family);
        } else if verbose {
            // In verbose mode, also show SMBIOS version for comparison
            println!("Intel ME Version (from SMBIOS Type 0xDD)");
            println!("  Firmware Version: {}", fvi_version);
        }
    }

    // Show handles found via Type 14 (Group Associations) - verbose only
    if verbose {
        let me_handles = csme::find_me_handles_from_type14(&smbios);
        if !me_handles.is_empty() {
            println!("ME Handles (from SMBIOS Type 14):");
            for handle in &me_handles {
                println!("  Handle: 0x{:04X}", handle);
            }
        }
    }

    // Parse SMBIOS type 0xDB for HFSTS registers
    if let Some(me_fwsts) = csme::me_fwsts_from_smbios(&smbios) {
        println!("Intel ME Status (SMBIOS Type 0xDB)");

        if let Some(record) = me_fwsts.mei1() {
            println!("  Working State:    {}", record.hfsts.working_state());
            println!("  Operation Mode:   {}", record.hfsts.operation_mode());

            // Parse bootguard status if we know the ME family
            if let Some(family) = me_family {
                if let Some(bootguard) = me_fwsts.bootguard_status(family) {
                    println!("  Bootguard:");
                    println!(
                        "    Enabled:        {}",
                        if bootguard.enabled { "Yes" } else { "No" }
                    );
                    if let Some(verified) = bootguard.verified_boot {
                        println!(
                            "    Verified Boot:  {}",
                            if verified { "Yes" } else { "No" }
                        );
                    }
                    println!(
                        "    ACM Active:     {}",
                        if bootguard.acm_active { "Yes" } else { "No" }
                    );
                    if let Some(done) = bootguard.acm_done {
                        println!("    ACM Done:       {}", if done { "Yes" } else { "No" });
                    }
                    if let Some(ref policy) = bootguard.policy {
                        println!("    Policy:         {}", policy);
                    }
                    println!(
                        "    FPF SOC Lock:   {}",
                        if bootguard.fpf_soc_lock { "Yes" } else { "No" }
                    );
                }
            }

            // Show raw HFSTS registers - verbose only
            if verbose {
                println!("  HFSTS Registers:");
                println!("    HFSTS1: 0x{:08X}", record.hfsts.hfsts1);
                println!("    HFSTS2: 0x{:08X}", record.hfsts.hfsts2);
                println!("    HFSTS3: 0x{:08X}", record.hfsts.hfsts3);
                println!("    HFSTS4: 0x{:08X}", record.hfsts.hfsts4);
                println!("    HFSTS5: 0x{:08X}", record.hfsts.hfsts5);
                println!("    HFSTS6: 0x{:08X}", record.hfsts.hfsts6);
            }
        }
    } else {
        error!("No Intel ME FWSTS table found in SMBIOS (type 0xDB)");
    }
}

fn analyze_ccgx_pd_fw(data: &[u8]) {
    if let Some(versions) = ccgx::binary::read_versions(data, Ccg3) {
        println!("Detected CCG3 firmware");
        println!("FW 1");
        ccgx::binary::print_fw(&versions.backup_fw);

        println!("FW 2");
        ccgx::binary::print_fw(&versions.main_fw);
    } else if let Some(versions) = ccgx::binary::read_versions(data, Ccg8) {
        println!("Detected CCG8 firmware");
        println!("FW 1");
        ccgx::binary::print_fw(&versions.backup_fw);

        println!("FW 2");
        ccgx::binary::print_fw(&versions.main_fw);
    } else if let Some(versions) = ccgx::binary::read_versions(data, Ccg5) {
        println!("Detected CCG5 firmware");
        println!("FW 1");
        ccgx::binary::print_fw(&versions.backup_fw);

        println!("FW 2");
        ccgx::binary::print_fw(&versions.main_fw);
    } else if let Some(versions) = ccgx::binary::read_versions(data, Ccg6) {
        println!("Detected CCG6 firmware");
        println!("FW 1 (Backup)");
        ccgx::binary::print_fw(&versions.backup_fw);

        println!("FW 2 (Main)");
        ccgx::binary::print_fw(&versions.main_fw);
    } else {
        println!("Failed to read PD versions")
    }
}

pub fn analyze_ec_fw(data: &[u8]) {
    // Readonly firmware
    if let Some(ver) = ec_binary::read_ec_version(data, true) {
        ec_binary::print_ec_version(&ver, true);
    } else {
        println!("Failed to read EC version")
    }
    // Readwrite firmware
    if let Some(ver) = ec_binary::read_ec_version(data, false) {
        ec_binary::print_ec_version(&ver, false);
    } else {
        println!("Failed to read EC version")
    }
}

pub fn analyze_capsule(data: &[u8]) -> Option<capsule::EfiCapsuleHeader> {
    let header = capsule::parse_capsule_header(data)?;
    capsule::print_capsule_header(&header);

    match GUID::from(header.capsule_guid) {
        esrt::TGL_BIOS_GUID => {
            println!("  Type:         Framework TGL Insyde BIOS");
        }
        esrt::ADL_BIOS_GUID => {
            println!("  Type:         Framework ADL Insyde BIOS");
        }
        esrt::RPL_BIOS_GUID => {
            println!("  Type:         Framework RPL Insyde BIOS");
        }
        esrt::TGL_RETIMER01_GUID => {
            println!("  Type:    Framework TGL Retimer01 (Right)");
        }
        esrt::TGL_RETIMER23_GUID => {
            println!("  Type:   Framework TGL Retimer23 (Left)");
        }
        esrt::ADL_RETIMER01_GUID => {
            println!("  Type:    Framework ADL Retimer01 (Right)");
        }
        esrt::ADL_RETIMER23_GUID => {
            println!("  Type:   Framework ADL Retimer23 (Left)");
        }
        esrt::RPL_RETIMER01_GUID => {
            println!("  Type:    Framework RPL Retimer01 (Right)");
        }
        esrt::RPL_RETIMER23_GUID => {
            println!("  Type:   Framework RPL Retimer23 (Left)");
        }
        esrt::WINUX_GUID => {
            println!("  Type:            Windows UX capsule");
            let ux_header = capsule::parse_ux_header(data);
            capsule::print_ux_header(&ux_header);
        }
        _ => {
            println!("  Type:                      Unknown");
        }
    }

    match esrt::match_guid_kind(&header.capsule_guid) {
        esrt::FrameworkGuidKind::TglRetimer01
        | esrt::FrameworkGuidKind::TglRetimer23
        | esrt::FrameworkGuidKind::AdlRetimer01
        | esrt::FrameworkGuidKind::AdlRetimer23
        | esrt::FrameworkGuidKind::RplRetimer01
        | esrt::FrameworkGuidKind::RplRetimer23 => {
            if let Some(ver) = find_retimer_version(data) {
                println!("  Version:      {:>18?}", ver);
            }
        }
        _ => {}
    }

    Some(header)
}

fn handle_charge_limit(ec: &CrosEc, maybe_limit: Option<u8>) -> EcResult<()> {
    let (cur_min, _cur_max) = ec.get_charge_limit()?;
    if let Some(limit) = maybe_limit {
        // Prevent setting unreasonable limits
        if limit < 25 {
            return Err(EcError::DeviceError(
                "Not recommended to set charge limit below 25%".to_string(),
            ));
        } else if limit > 100 {
            return Err(EcError::DeviceError(
                "Charge limit cannot be set above 100%".to_string(),
            ));
        }
        ec.set_charge_limit(cur_min, limit)?;
    }

    let (min, max) = ec.get_charge_limit()?;
    println!("Minimum {}%, Maximum {}%", min, max);

    Ok(())
}

fn handle_fp_led_level(ec: &CrosEc, maybe_led_level: Option<FpBrightnessArg>) -> EcResult<()> {
    if let Some(led_level) = maybe_led_level {
        ec.set_fp_led_level(led_level.into())?;
    }

    let (brightness, level) = ec.get_fp_led_level()?;
    // TODO: Rename to power button
    println!("Fingerprint LED Brightness");
    if let Some(level) = level {
        println!("  Requested:  {:?}", level);
    }
    println!("  Brightness: {}%", brightness);

    Ok(())
}

fn handle_fp_brightness(ec: &CrosEc, maybe_brightness: Option<u8>) -> EcResult<()> {
    if let Some(brightness) = maybe_brightness {
        ec.set_fp_led_percentage(brightness)?;
    }

    let (brightness, level) = ec.get_fp_led_level()?;
    // TODO: Rename to power button
    println!("Fingerprint LED Brightness");
    if let Some(level) = level {
        println!("  Requested:  {:?}", level);
    }
    println!("  Brightness: {}%", brightness);

    Ok(())
}