1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use {
    crate::{
        certificate::{
            create_self_signed_code_signing_certificate, AppleCertificate, CertificateProfile,
        },
        code_directory::{CodeDirectoryBlob, CodeSignatureFlags},
        code_requirement::CodeRequirements,
        cryptography::{parse_pfx_data, DigestType, InMemoryPrivateKey, PrivateKey},
        embedded_signature::{Blob, CodeSigningSlot, RequirementSetBlob},
        error::AppleCodesignError,
        macho::MachFile,
        reader::SignatureReader,
        remote_signing::{
            session_negotiation::{
                create_session_joiner, PublicKeyInitiator, SessionInitiatePeer, SessionJoinState,
                SharedSecretInitiator,
            },
            RemoteSignError, UnjoinedSigningClient,
        },
        signing::UnifiedSigner,
        signing_settings::{SettingsScope, SigningSettings},
    },
    base64::{engine::general_purpose::STANDARD as STANDARD_ENGINE, Engine},
    clap::{ArgAction, Args, Parser, Subcommand, ValueEnum},
    cryptographic_message_syntax::SignedData,
    difference::{Changeset, Difference},
    log::{error, warn, LevelFilter},
    spki::EncodePublicKey,
    std::{
        io::Write,
        ops::Deref,
        path::{Path, PathBuf},
        str::FromStr,
    },
    x509_certificate::{CapturedX509Certificate, EcdsaCurve, KeyAlgorithm, X509CertificateBuilder},
};

#[cfg(feature = "notarize")]
use crate::notarization::Notarizer;

#[cfg(feature = "yubikey")]
use {
    crate::yubikey::YubiKey,
    yubikey::{PinPolicy, TouchPolicy},
};

#[cfg(target_os = "macos")]
use crate::macos::{
    keychain_find_code_signing_certificates, macos_keychain_find_certificate_chain, KeychainDomain,
};

const GENERATE_SELF_SIGNED_CERTIFICATE_ABOUT: &str = "\
Generate a self-signed certificate that can be used for code signing.

This command will generate a new key pair using the algorithm of choice
then create an X.509 certificate wrapper for it that is signed with the
just-generated private key. The created X.509 certificate has extensions
that mark it as appropriate for code signing.

Certificates generated with this command can be useful for local testing.
However, because it is a self-signed certificate and isn't signed by a
trusted certificate authority, Apple operating systems may refuse to
load binaries signed with it.

By default the command prints 2 PEM encoded blocks. One block is for the
X.509 public certificate. The other is for the PKCS#8 private key (which
can include the public key).

The `--pem-filename` argument can be specified to write the generated
certificate pair to a pair of files. The destination files will have
`.crt` and `.key` appended to the value provided.

When the certificate is written to a file, it isn't printed to stdout.
";

const PARSE_CODE_SIGNING_REQUIREMENT_ABOUT: &str = "\
Parse code signing requirement data into human readable text.

This command can be used to parse binary code signing requirement data and
print it in various formats.

The source input format is the binary code requirement serialization. This
is the format generated by Apple's `csreq` tool via `csreq -b`. The binary
data begins with header magic `0xfade0c00`.

The default output format is the Code Signing Requirement Language. But the
output format can be changed via the --format argument.

Our Code Signing Requirement Language output may differ from Apple's. For
example, `and` and `or` expressions always have their sub-expressions surrounded
by parentheses (e.g. `(a) and (b)` instead of `a and b`) and strings are always
quoted. The differences, however, should not matter to the parser or result
in a different binary serialization.
";

const SIGN_ABOUT: &str = "\
Adds code signatures to a signable entity.

This command can sign the following entities:

* A single Mach-O binary (specified by its file path)
* A bundle (specified by its directory path)
* A DMG disk image (specified by its path)
* A XAR archive (commonly a .pkg installer file)

If the input is Mach-O binary, it can be a single or multiple/fat/universal
Mach-O binary. If a fat binary is given, each Mach-O within that binary will
be signed.

If the input is a bundle, the bundle will be recursively signed. If the
bundle contains nested bundles or Mach-O binaries, those will be signed
automatically.

# Settings Scope

The following signing settings are global and apply to all signed entities:

* --digest
* --pem-source
* --team-name
* --timestamp-url

The following signing settings can be scoped so they only apply to certain
entities:

* --binary-identifier
* --code-requirements-path
* --code-resources-path
* --code-signature-flags
* --entitlements-xml-path
* --info-plist-path

Scoped settings take the form <value> or <scope>:<value>. If the 2nd form
is used, the string before the first colon is parsed as a \"scoping string\".
It can have the following values:

* `main` - Applies to the main entity being signed and all nested entities.
* `@<integer>` - e.g. `@0`. Applies to a Mach-O within a fat binary at the
  specified index. 0 means the first Mach-O in a fat binary.
* `@[cpu_type=<int>` - e.g. `@[cpu_type=7]`. Applies to a Mach-O within a fat
  binary targeting a numbered CPU architecture (using numeric constants
  as defined by Mach-O).
* `@[cpu_type=<string>` - e.g. `@[cpu_type=x86_64]`. Applies to a Mach-O within
  a fat binary targeting a CPU architecture identified by a string. See below
  for the list of recognized values.
* `<string>` - e.g. `path/to/file`. Applies to content at a given path. This
  should be the bundle-relative path to a Mach-O binary, a nested bundle, or
  a Mach-O binary within a nested bundle. If a nested bundle is referenced,
  settings apply to everything within that bundle.
* `<string>@<int>` - e.g. `path/to/file@0`. Applies to a Mach-O within a
  fat binary at the given path. If the path is to a bundle, the setting applies
  to all Mach-O binaries in that bundle.
* `<string>@[cpu_type=<int|string>]` e.g. `Contents/MacOS/binary@[cpu_type=7]`
  or `Contents/MacOS/binary@[cpu_type=arm64]`. Applies to a Mach-O within a
  fat binary targeting a CPU architecture identified by its integer constant
  or string name. If the path is to a bundle, the setting applies to all
  Mach-O binaries in that bundle.

The following named CPU architectures are recognized:

* arm
* arm64
* arm64_32
* x86_64

Signing will traverse into nested entities:

* A fat Mach-O binary will traverse into the multiple Mach-O binaries within.
* A bundle will traverse into nested bundles.
* A bundle will traverse non-code \"resource\" files and sign their digests.
* A bundle will traverse non-main Mach-O binaries and sign them, adding their
  metadata to the signed resources file.

# Bundle Signing Overrides Settings

When signing bundles, some settings specified on the command line will be
ignored. This is to ensure that the produced signing data is correct. The
settings ignored include (but may not be limited to):

* --binary-identifier for the main executable. The `CFBundleIdentifier` value
  from the bundle's `Info.plist` will be used instead.
* --code-resources-path. The code resources data will be computed automatically
  as part of signing the bundle.
* --info-plist-path. The `Info.plist` from the bundle will be used instead.
* --digest and --extra-digest

# Designated Code Requirements

When using Apple issued code signing certificates, we will attempt to apply
an appropriate designated requirement automatically during signing which
matches the behavior of what `codesign` would do. We do not yet support all
signing certificates and signing targets for this, however. So you may
need to provide your own requirements.

Designated code requirements can be specified via --code-requirements-path.

This file MUST contain a binary/compiled code requirements expression. We do
not (yet) support parsing the human-friendly code requirements DSL. A
binary/compiled file can be produced via Apple's `csreq` tool. e.g.
`csreq -r '=<expression>' -b /output/path`. If code requirements data is
specified, it will be parsed and displayed as part of signing to ensure it
is well-formed.

# Code Signing Key Pair

By default, the embedded code signature will only contain digests of the
binary and other important entities (such as entitlements and resources).
This is often referred to as \"ad-hoc\" signing.

To use a code signing key/certificate to derive a cryptographic signature,
you must specify a source certificate to use. This can be done in the following
ways:

* The --p12-file denotes the location to a PFX formatted file. These are
  often .pfx or .p12 files. A password is required to open these files.
  Specify one via --p12-password or --p12-password-file or enter a password
  when prompted.
* The --pem-source argument defines paths to files containing PEM encoded
  certificate/key data. (e.g. files with \"===== BEGIN CERTIFICATE =====\").
* The --source-source argument defines paths to files containiner DER
  encoded certificate/key data.
* The --keychain-domain and --keychain-fingerprint arguments can be used to
  load code signing certificates from macOS keychains. These arguments are
  ignored on non-macOS platforms.
* The --smartcard-slot argument defines the name of a slot in a connected
  smartcard device to read from. `9c` is common.
* Arguments beginning with --remote activate *remote signing mode* and can
  be used to delegate cryptographic signing operations to a separate machine.
  It is strongly advised to read the user documentation on remote signing
  mode at https://gregoryszorc.com/docs/apple-codesign/main/.

If you export a code signing certificate from the macOS keychain via the
`Keychain Access` application as a .p12 file, we should be able to read these
files via --p12-file.

When using --pem-source, certificates and public keys are parsed from
`BEGIN CERTIFICATE` and `BEGIN PRIVATE KEY` sections in the files.

The way certificate discovery works is that --p12-file is read followed by
all values to --pem-source. The seen signing keys and certificates are
collected. After collection, there must be 0 or 1 signing keys present, or
an error occurs. The first encountered public certificate is assigned
to be paired with the signing key. All remaining certificates are assumed
to constitute the CA issuing chain and will be added to the signature
data to facilitate validation.

If you are using an Apple-issued code signing certificate, we detect this
and automatically register the Apple CA certificate chain so it is included
in the digital signature. This matches the behavior of the `codesign` tool.

For best results, put your private key and its corresponding X.509 certificate
in a single file, either a PFX or PEM formatted file. Then add any additional
certificates constituting the signing chain in a separate PEM file.

When using a code signing key/certificate, a Time-Stamp Protocol server URL
can be specified via --timestamp-url. By default, Apple's server is used. The
special value \"none\" can disable using a timestamp server.

# Selecting What to Sign

By default, this command attempts to recursively sign everything in the source
path. This applies to:

* Bundles. If the specified bundle has nested bundles, those nested bundles
  will be signed automatically.

It is possible to exclude nested items from signing using --exclude. This
argument takes a glob expression that matches *relative paths* from the
source path. Glob expressions can be literal string compares. Or the
following special syntax is recognized:

* `?` matches any single character.
* `*` matches any (possibly empty) sequence of characters.
* `**` matches the current directory and arbitrary subdirectories. This sequence
  must form a single path component, so both **a and b** are invalid and will
  result in an error. A sequence of more than two consecutive * characters is
  also invalid.
* `[...]` matches any character inside the brackets. Character sequences can also
  specify ranges of characters, as ordered by Unicode, so e.g. [0-9] specifies any
  character between 0 and 9 inclusive. An unclosed bracket is invalid.
* `[!...]` is the negation of `[...]`, i.e. it matches any characters not in the
  brackets.
* The metacharacters `?`, `*`, `[`, `]` can be matched by using brackets (e.g.
  `[?]`). When a `]` occurs immediately following `[` or `[!` then it is
  interpreted as being part of, rather then ending, the character set, so `]` and
  `NOT ]` can be matched by `[]]` and `[!]]` respectively. The `-` character can
  be specified inside a character sequence pattern by placing it at the start or
  the end, e.g. `[abc-]`.

Currently, --exclude only applies to the relative path of nested bundles within
the main bundle to sign. e.g. if you sign `MyApp.app` and it has a
`Contents/Frameworks/MyFramework.framework` that you wish to exclude, you would
`--exclude Contents/Frameworks/MyFramework.framework` or even
`--exclude Contents/Frameworks/**` to exclude the entire directory tree.

Exclusions will still be copied and parents that need to reference exclude
entities will continue to do so. If you wish to make a file or directory
disappear, create a new directory without the file(s) and sign that.

To exclude all nested bundles from being signed and only sign the main bundle
(the default behavior of ``codesign`` without ``--deep``), use `--exclude '**'`.
";

const APPLE_TIMESTAMP_URL: &str = "http://timestamp.apple.com/ts01";

const SUPPORTED_HASHES: [&str; 6] = [
    "none",
    "sha1",
    "sha256",
    "sha256-truncated",
    "sha384",
    "sha512",
];

const KEYCHAIN_DOMAINS: [&str; 4] = ["user", "system", "common", "dynamic"];

fn parse_scoped_value(s: &str) -> Result<(SettingsScope, &str), AppleCodesignError> {
    let parts = s.splitn(2, ':').collect::<Vec<_>>();

    match parts.len() {
        1 => Ok((SettingsScope::Main, s)),
        2 => Ok((SettingsScope::try_from(parts[0])?, parts[1])),
        _ => Err(AppleCodesignError::CliBadArgument),
    }
}

fn get_pkcs12_password(
    password: Option<impl ToString>,
    password_file: Option<impl AsRef<Path>>,
) -> Result<String, AppleCodesignError> {
    if let Some(password) = password {
        Ok(password.to_string())
    } else if let Some(path) = password_file {
        Ok(std::fs::read_to_string(path.as_ref())?
            .lines()
            .next()
            .ok_or_else(|| {
                AppleCodesignError::CliGeneralError("password file appears to be empty".into())
            })?
            .to_string())
    } else {
        Ok(dialoguer::Password::new()
            .with_prompt("Please enter password for p12 file")
            .interact()?)
    }
}

#[derive(Args, Clone)]
struct CertificateSource {
    /// Smartcard slot number of signing certificate to use (9c is common)
    #[arg(long)]
    smartcard_slot: Option<String>,

    /// Environment variable holding the smartcard PIN
    #[arg(long)]
    smartcard_pin_env: Option<String>,

    /// (macOS only) Keychain domain to operate on
    #[arg(long, group = "keychain", value_parser = KEYCHAIN_DOMAINS)]
    keychain_domain: Vec<String>,

    /// (macOS only) SHA-256 fingerprint of certificate in Keychain to use
    #[arg(long, group = "keychain")]
    keychain_fingerprint: Option<String>,

    /// Path to file containing PEM encoded certificate/key data
    #[arg(long)]
    pem_source: Vec<String>,

    /// Path to file containing DER encoded certificate data
    #[arg(long)]
    der_source: Vec<String>,

    /// Path to a .p12/PFX file containing a certificate key pair
    #[arg(long = "p12-file", alias = "pfx-file")]
    p12_path: Option<PathBuf>,

    /// The password to use to open the --p12-file file
    #[arg(long, alias = "pfx-password", group = "p12-password")]
    p12_password: Option<String>,

    // TODO conflicts with p12_password
    /// Path to file containing password for opening --p12-file file
    #[arg(long, alias = "pfx-password-file", group = "p12-password")]
    p12_password_file: Option<String>,

    /// Send signing requests to a remote signer
    #[arg(long)]
    remote_signer: bool,

    /// Base64 encoded public key data describing the signer
    #[arg(long, group = "remote-initialization")]
    remote_public_key: Option<String>,

    /// PEM encoded public key data describing the signer
    #[arg(long, group = "remote-initialization", group = "remote-initialization")]
    remote_public_key_pem_file: Option<String>,

    /// Shared secret used for remote signing
    #[arg(long, group = "remote-initialization")]
    remote_shared_secret: Option<String>,

    /// Environment variable holding the shared secret used for remote signing
    #[arg(long, group = "remote-initialization")]
    remote_shared_secret_env: Option<String>,

    /// URL of a remote code signing server
    #[arg(long, default_value = crate::remote_signing::DEFAULT_SERVER_URL)]
    remote_signing_url: String,
}

impl CertificateSource {
    fn resolve_certificates(
        &self,
        scan_smartcard: bool,
    ) -> Result<(Vec<Box<dyn PrivateKey>>, Vec<CapturedX509Certificate>), AppleCodesignError> {
        let mut keys: Vec<Box<dyn PrivateKey>> = vec![];
        let mut certs = vec![];

        if let Some(p12_path) = &self.p12_path {
            let p12_data = std::fs::read(p12_path)?;

            let p12_password =
                get_pkcs12_password(self.p12_password.clone(), self.p12_password_file.clone())?;

            let (cert, key) = parse_pfx_data(&p12_data, &p12_password)?;

            keys.push(Box::new(key));
            certs.push(cert);
        }

        for pem_source in &self.pem_source {
            warn!("reading PEM data from {}", pem_source);
            let pem_data = std::fs::read(pem_source)?;

            for pem in pem::parse_many(pem_data).map_err(AppleCodesignError::CertificatePem)? {
                match pem.tag() {
                    "CERTIFICATE" => {
                        certs.push(CapturedX509Certificate::from_der(pem.contents())?);
                    }
                    "PRIVATE KEY" => {
                        keys.push(Box::new(InMemoryPrivateKey::from_pkcs8_der(
                            pem.contents(),
                        )?));
                    }
                    "RSA PRIVATE KEY" => {
                        keys.push(Box::new(InMemoryPrivateKey::from_pkcs1_der(
                            pem.contents(),
                        )?));
                    }
                    tag => warn!("(unhandled PEM tag {}; ignoring)", tag),
                }
            }
        }

        for der_source in &self.der_source {
            warn!("reading DER file {}", der_source);
            let der_data = std::fs::read(der_source)?;

            certs.push(CapturedX509Certificate::from_der(der_data)?);
        }

        self.find_certificates_in_keychain(&mut keys, &mut certs)?;

        if scan_smartcard {
            if let Some(slot) = &self.smartcard_slot {
                handle_smartcard_sign_slot(
                    slot,
                    self.smartcard_pin_env.as_deref(),
                    &mut keys,
                    &mut certs,
                )?;
            }
        }

        let remote_signing_url = if self.remote_signer {
            Some(self.remote_signing_url.clone())
        } else {
            None
        };

        if let Some(remote_signing_url) = remote_signing_url {
            let initiator = self.get_remote_signing_initiator()?;

            let client = UnjoinedSigningClient::new_initiator(
                remote_signing_url,
                initiator,
                Some(print_session_join),
            )?;

            // As part of the handshake we obtained the public certificates from the signer.
            // So make them the canonical set.
            if !certs.is_empty() {
                warn!(
                    "ignoring {} local certificates and using remote signer's certificate(s)",
                    certs.len()
                );
            }

            certs = vec![client.signing_certificate().clone()];
            certs.extend(client.certificate_chain().iter().cloned());

            // The client implements Sign, so we just use it as the private key.
            keys = vec![Box::new(client)];
        }

        Ok((keys, certs))
    }

    #[cfg(target_os = "macos")]
    fn find_certificates_in_keychain(
        &self,
        private_keys: &mut Vec<Box<dyn PrivateKey>>,
        public_certificates: &mut Vec<CapturedX509Certificate>,
    ) -> Result<(), AppleCodesignError> {
        // No arguments pertinent to keychains. Don't even speak to the
        // keychain API since this could only error.
        if self.keychain_domain.is_empty() && self.keychain_fingerprint.is_none() {
            return Ok(());
        }

        // Collect all the keychain domains to search.
        let domains = if self.keychain_domain.is_empty() {
            vec!["user".to_string()]
        } else {
            self.keychain_domain.clone()
        };

        let domains = domains
            .into_iter()
            .map(|domain| {
                KeychainDomain::try_from(domain.as_str())
                    .expect("clap should have validated domain values")
            })
            .collect::<Vec<_>>();

        // Now iterate all the keychains and try to find requested certificates.

        for domain in domains {
            for cert in keychain_find_code_signing_certificates(domain, None)? {
                let matches = if let Some(wanted_fingerprint) = &self.keychain_fingerprint {
                    let got_fingerprint = hex::encode(cert.sha256_fingerprint()?.as_ref());

                    wanted_fingerprint.to_ascii_lowercase() == got_fingerprint.to_ascii_lowercase()
                } else {
                    false
                };

                if matches {
                    public_certificates.push(cert.as_captured_x509_certificate());
                    private_keys.push(Box::new(cert));
                }
            }
        }

        Ok(())
    }

    #[cfg(not(target_os = "macos"))]
    fn find_certificates_in_keychain(
        &self,
        _private_keys: &mut [Box<dyn PrivateKey>],
        _public_certificates: &mut [CapturedX509Certificate],
    ) -> Result<(), AppleCodesignError> {
        if !self.keychain_domain.is_empty() || self.keychain_fingerprint.is_some() {
            error!(
                "--keychain* arguments only supported on macOS and will be ignored on this platform"
            );
        }

        Ok(())
    }

    fn get_remote_signing_initiator(
        &self,
    ) -> Result<Box<dyn SessionInitiatePeer>, RemoteSignError> {
        let server_url = self.remote_signing_url.clone();

        if let Some(public_key_data) = &self.remote_public_key {
            let public_key_data = STANDARD_ENGINE.decode(public_key_data)?;

            Ok(Box::new(PublicKeyInitiator::new(
                public_key_data,
                Some(server_url),
            )?))
        } else if let Some(path) = &self.remote_public_key_pem_file {
            let pem_data = std::fs::read(path)?;
            let doc = pem::parse(pem_data)?;

            let spki_der = match doc.tag() {
                "PUBLIC KEY" => doc.contents().to_vec(),
                "CERTIFICATE" => {
                    let cert = CapturedX509Certificate::from_der(doc.contents())?;
                    cert.to_public_key_der()?.as_ref().to_vec()
                }
                tag => {
                    error!(
                        "unknown PEM format: {}; only `PUBLIC KEY` and `CERTIFICATE` are parsed",
                        tag
                    );
                    return Err(RemoteSignError::Crypto("invalid public key data".into()));
                }
            };

            Ok(Box::new(PublicKeyInitiator::new(
                spki_der,
                Some(server_url),
            )?))
        } else if let Some(env) = &self.remote_shared_secret_env {
            let secret = std::env::var(env).map_err(|_| {
                RemoteSignError::ClientState(
                    "failed reading from shared secret environment variable",
                )
            })?;

            Ok(Box::new(SharedSecretInitiator::new(
                secret.as_bytes().to_vec(),
            )?))
        } else if let Some(value) = &self.remote_shared_secret {
            Ok(Box::new(SharedSecretInitiator::new(
                value.as_bytes().to_vec(),
            )?))
        } else {
            error!("no arguments provided to establish session with remote signer");
            error!(
            "specify --remote-public-key, --remote-shared-secret-env, or --remote-shared-secret"
        );
            Err(RemoteSignError::ClientState(
                "unable to initiate remote signing",
            ))
        }
    }
}

#[cfg(feature = "notarize")]
#[derive(Args)]
struct NotaryApi {
    /// Path to a JSON file containing the API Key
    #[arg(long, group = "source")]
    api_key_path: Option<PathBuf>,

    /// App Store Connect Issuer ID (likely a UUID)
    #[arg(long, requires = "api_key")]
    api_issuer: Option<String>,

    #[arg(long, requires = "api_issuer")]
    /// App Store Connect API Key ID
    api_key: Option<String>,
}

#[cfg(feature = "notarize")]
impl NotaryApi {
    /// Resolve a notarizer from arguments.
    fn notarizer(&self) -> Result<Notarizer, AppleCodesignError> {
        if let Some(api_key_path) = &self.api_key_path {
            Notarizer::from_api_key(api_key_path)
        } else if let (Some(issuer), Some(key)) = (&self.api_issuer, &self.api_key) {
            Notarizer::from_api_key_id(issuer, key)
        } else {
            Err(AppleCodesignError::NotarizeNoAuthCredentials)
        }
    }
}

#[derive(Args)]
struct YubikeyPolicy {
    /// Smartcard touch policy to protect key access
    #[arg(long, value_parser = ["default", "always", "never", "cached"], default_value = "default")]
    touch_policy: String,

    /// Smartcard pin prompt policy to protect key access
    #[arg(long, value_parser = ["default", "never", "once", "always"], default_value = "default")]
    pin_policy: String,
}

#[cfg(feature = "yubikey")]
fn str_to_touch_policy(s: &str) -> Result<TouchPolicy, AppleCodesignError> {
    match s {
        "default" => Ok(TouchPolicy::Default),
        "never" => Ok(TouchPolicy::Never),
        "always" => Ok(TouchPolicy::Always),
        "cached" => Ok(TouchPolicy::Cached),
        _ => Err(AppleCodesignError::CliBadArgument),
    }
}

#[cfg(feature = "yubikey")]
fn str_to_pin_policy(s: &str) -> Result<PinPolicy, AppleCodesignError> {
    match s {
        "default" => Ok(PinPolicy::Default),
        "never" => Ok(PinPolicy::Never),
        "once" => Ok(PinPolicy::Once),
        "always" => Ok(PinPolicy::Always),
        _ => Err(AppleCodesignError::CliBadArgument),
    }
}

fn print_certificate_info(cert: &CapturedX509Certificate) -> Result<(), AppleCodesignError> {
    println!(
        "Subject CN:                  {}",
        cert.subject_common_name()
            .unwrap_or_else(|| "<missing>".to_string())
    );
    println!(
        "Issuer CN:                   {}",
        cert.issuer_common_name()
            .unwrap_or_else(|| "<missing>".to_string())
    );
    println!("Subject is Issuer?:          {}", cert.subject_is_issuer());
    println!(
        "Team ID:                     {}",
        cert.apple_team_id()
            .unwrap_or_else(|| "<missing>".to_string())
    );
    println!(
        "SHA-1 fingerprint:           {}",
        hex::encode(cert.sha1_fingerprint()?)
    );
    println!(
        "SHA-256 fingerprint:         {}",
        hex::encode(cert.sha256_fingerprint()?)
    );
    if let Some(alg) = cert.key_algorithm() {
        println!("Key Algorithm:               {alg}");
    }
    if let Some(alg) = cert.signature_algorithm() {
        println!("Signature Algorithm:         {alg}");
    }
    println!(
        "Public Key Data:             {}",
        STANDARD_ENGINE.encode(
            cert.to_public_key_der()
                .map_err(|e| AppleCodesignError::X509Parse(format!(
                    "error constructing SPKI: {e}"
                )))?
        )
    );
    println!(
        "Signed by Apple?:            {}",
        cert.chains_to_apple_root_ca()
    );
    if cert.chains_to_apple_root_ca() {
        println!("Apple Issuing Chain:");
        for signer in cert.apple_issuing_chain() {
            println!(
                "  - {}",
                signer
                    .subject_common_name()
                    .unwrap_or_else(|| "<unknown>".to_string())
            );
        }
    }

    println!(
        "Guessed Certificate Profile: {}",
        if let Some(profile) = cert.apple_guess_profile() {
            format!("{profile:?}")
        } else {
            "none".to_string()
        }
    );
    println!("Is Apple Root CA?:           {}", cert.is_apple_root_ca());
    println!(
        "Is Apple Intermediate CA?:   {}",
        cert.is_apple_intermediate_ca()
    );

    if !cert.apple_ca_extensions().is_empty() {
        println!("Apple CA Extensions:");
        for ext in cert.apple_ca_extensions() {
            println!("  - {} ({:?})", ext.as_oid(), ext);
        }
    }

    println!("Apple Extended Key Usage Purpose Extensions:");
    for purpose in cert.apple_extended_key_usage_purposes() {
        println!("  - {} ({:?})", purpose.as_oid(), purpose);
    }
    println!("Apple Code Signing Extensions:");
    for ext in cert.apple_code_signing_extensions() {
        println!("  - {} ({:?})", ext.as_oid(), ext);
    }
    print!(
        "\n{}",
        cert.to_public_key_pem(Default::default())
            .map_err(|e| AppleCodesignError::X509Parse(format!("error constructing SPKI: {e}")))?
    );
    print!("\n{}", cert.encode_pem());

    Ok(())
}

fn print_session_join(sjs_base64: &str, sjs_pem: &str) -> Result<(), RemoteSignError> {
    error!("");
    error!("Run the following command to join this signing session:");
    error!("");
    error!("    rcodesign remote-sign {}", sjs_base64);
    error!("");
    error!("Or if this output is too long, paste the following output:");
    error!("");
    for line in sjs_pem.lines() {
        error!("{}", line);
    }
    error!("");
    error!("Into an interactive editor using:");
    error!("");
    error!("    rcodesign remote-sign --editor");
    error!("");
    error!("Or into a new file whose path you define with:");
    error!("");
    error!("    rcodesign remote-sign --sjs-path /path/to/file/you/just/saved");
    error!("");
    error!("(waiting for remote signer to join)");

    Ok(())
}

#[allow(unused)]
fn prompt_smartcard_pin() -> Result<Vec<u8>, AppleCodesignError> {
    let pin = dialoguer::Password::new()
        .with_prompt("Please enter device PIN")
        .interact()?;

    Ok(pin.as_bytes().to_vec())
}

#[cfg(feature = "yubikey")]
fn handle_smartcard_sign_slot(
    slot: &str,
    pin_env_var: Option<&str>,
    private_keys: &mut Vec<Box<dyn PrivateKey>>,
    public_certificates: &mut Vec<CapturedX509Certificate>,
) -> Result<(), AppleCodesignError> {
    let slot_id = ::yubikey::piv::SlotId::from_str(slot)?;
    let formatted = hex::encode([u8::from(slot_id)]);
    let mut yk = YubiKey::new()?;

    if let Some(pin_var) = pin_env_var {
        let pin_var = pin_var.to_owned();

        yk.set_pin_callback(move || {
            if let Ok(pin) = std::env::var(&pin_var) {
                eprintln!("using PIN from {} environment variable", &pin_var);
                Ok(pin.as_bytes().to_vec())
            } else {
                prompt_smartcard_pin()
            }
        });
    } else {
        yk.set_pin_callback(prompt_smartcard_pin);
    }

    if let Some(cert) = yk.get_certificate_signer(slot_id)? {
        warn!("using certificate in smartcard slot {}", formatted);
        public_certificates.push(cert.certificate().clone());
        private_keys.push(Box::new(cert));

        Ok(())
    } else {
        Err(AppleCodesignError::SmartcardNoCertificate(formatted))
    }
}

#[cfg(not(feature = "yubikey"))]
fn handle_smartcard_sign_slot(
    _slot: &str,
    _pin_env_var: Option<&str>,
    _private_keys: &mut [Box<dyn PrivateKey>],
    _public_certificates: &mut [CapturedX509Certificate],
) -> Result<(), AppleCodesignError> {
    error!("smartcard support not available; ignoring --smartcard-slot");

    Ok(())
}

#[derive(Parser)]
struct AnalyzeCertificate {
    #[command(flatten)]
    certificate: CertificateSource,
}

fn command_analyze_certificate(args: &AnalyzeCertificate) -> Result<(), AppleCodesignError> {
    let certs = args.certificate.resolve_certificates(true)?.1;

    for (i, cert) in certs.into_iter().enumerate() {
        println!("# Certificate {i}");
        println!();
        print_certificate_info(&cert)?;
        println!();
    }

    Ok(())
}

#[derive(Parser)]
struct ComputeCodeHashes {
    /// Path to Mach-O binary to examine.
    path: PathBuf,

    /// Hashing algorithm to use.
    #[arg(long, default_value_t = DigestType::Sha256)]
    hash: DigestType,

    /// Chunk size to digest over.
    #[arg(long, default_value = "4096")]
    page_size: usize,

    /// Index of Mach-O binary to operate on within a universal/fat binary
    #[arg(long, default_value = "0")]
    universal_index: usize,
}

fn command_compute_code_hashes(args: &ComputeCodeHashes) -> Result<(), AppleCodesignError> {
    let data = std::fs::read(&args.path)?;
    let mach = MachFile::parse(&data)?;
    let macho = mach.nth_macho(args.universal_index)?;

    let hashes = macho.code_digests(args.hash, args.page_size)?;

    for hash in hashes {
        println!("{}", hex::encode(hash));
    }

    Ok(())
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
enum MachOArch {
    Aarch64,
    X86_64,
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
enum MachOFileType {
    Executable,
    Dylib,
}

impl MachOFileType {
    fn to_header_filetype(&self) -> u32 {
        match self {
            Self::Executable => object::macho::MH_EXECUTE,
            Self::Dylib => object::macho::MH_DYLIB,
        }
    }
}

#[derive(Parser)]
struct DebugCreateCodeRequirements {
    /// Code requirement expression to emit.
    #[arg(long, value_enum)]
    code_requirement: crate::policy::ExecutionPolicy,

    /// Path to write binary requirements to.
    path: PathBuf,
}

impl DebugCreateCodeRequirements {
    fn run(&self) -> Result<(), AppleCodesignError> {
        let expression = self.code_requirement.deref();

        let mut reqs = CodeRequirements::default();
        reqs.push(expression.clone());

        let data = reqs.to_blob_data()?;

        println!("writing code requirements to {}", self.path.display());

        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(&self.path, data)?;

        Ok(())
    }
}

#[derive(Parser)]
struct DebugCreateEntitlements {
    /// Add the `get-task-allow` entitlement.
    #[arg(long)]
    get_task_allow: bool,

    /// Add the `run-unsigned-code` entitlement.
    #[arg(long)]
    run_unsigned_code: bool,

    /// Add the `com.apple.private.cs.debugger` entitlement.
    #[arg(long)]
    debugger: bool,

    /// Add the `dynamic-codesigning` entitlement.
    #[arg(long)]
    dynamic_code_signing: bool,

    /// Add the `com.apple.private.skip-library-validation` entitlement.
    #[arg(long)]
    skip_library_validation: bool,

    /// Add the `com.apple.private.amfi.can-load-cdhash` entitlement.
    #[arg(long)]
    can_load_cd_hash: bool,

    /// Add the `com.apple.private.amfi.can-execute-cdhash` entitlement.
    #[arg(long)]
    can_execute_cd_hash: bool,

    /// Path to write entitlements to.
    output_path: PathBuf,
}

impl DebugCreateEntitlements {
    fn run(&self) -> Result<(), AppleCodesignError> {
        let mut d = plist::Dictionary::default();

        if self.get_task_allow {
            d.insert("get-task-allow".into(), true.into());
        }
        if self.run_unsigned_code {
            d.insert("run-unsigned-code".into(), true.into());
        }
        if self.debugger {
            d.insert("com.apple.private.cs.debugger".into(), true.into());
        }
        if self.dynamic_code_signing {
            d.insert("dynamic-codesigning".into(), true.into());
        }
        if self.skip_library_validation {
            d.insert(
                "com.apple.private.skip-library-validation".into(),
                true.into(),
            );
        }
        if self.can_load_cd_hash {
            d.insert("com.apple.private.amfi.can-load-cdhash".into(), true.into());
        }
        if self.can_execute_cd_hash {
            d.insert(
                "com.apple.private.amfi.can-execute-cdhash".into(),
                true.into(),
            );
        }

        let value = plist::Value::from(d);
        let mut xml = vec![];
        value.to_writer_xml(&mut xml)?;

        warn!("writing {}", self.output_path.display());
        if let Some(parent) = self.output_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(&self.output_path, &xml)?;

        Ok(())
    }
}

#[derive(Parser)]
struct DebugCreateInfoPlist {
    /// Name of the bundle.
    #[arg(long)]
    bundle_name: String,

    /// Bundle package type.
    #[arg(long, default_value = "APPL")]
    package_type: String,

    /// CFBundleExecutable value.
    #[arg(long)]
    bundle_executable: Option<String>,

    /// Bundle identifier.
    #[arg(long, default_value = "com.example.mybundle")]
    bundle_identifier: String,

    /// Bundle version.
    #[arg(long, default_value = "1.0.0")]
    bundle_version: String,

    /// Path to write Info.plist to.
    output_path: PathBuf,
}

impl DebugCreateInfoPlist {
    fn run(&self) -> Result<(), AppleCodesignError> {
        let mut d = plist::Dictionary::default();

        d.insert("CFBundleName".into(), self.bundle_name.clone().into());
        d.insert(
            "CFBundlePackageType".into(),
            self.package_type.clone().into(),
        );
        d.insert(
            "CFBundleDisplayName".into(),
            self.bundle_name.clone().into(),
        );
        if let Some(exe) = &self.bundle_executable {
            d.insert("CFBundleExecutable".into(), exe.clone().into());
        }
        d.insert(
            "CFBundleIdentifier".into(),
            self.bundle_identifier.clone().into(),
        );
        d.insert("CFBundleVersion".into(), self.bundle_version.clone().into());
        d.insert("CFBundleSignature".into(), "sig".into());
        d.insert("CFBundleExecutable".into(), self.bundle_name.clone().into());

        let value = plist::Value::from(d);

        let mut xml = vec![];
        value.to_writer_xml(&mut xml)?;

        println!("writing {}", self.output_path.display());
        if let Some(parent) = self.output_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(&self.output_path, &xml)?;

        Ok(())
    }
}

#[derive(Parser)]
struct DebugCreateMachO {
    /// Architecture of Mach-O binary.
    #[arg(long, value_enum, default_value_t = MachOArch::Aarch64)]
    architecture: MachOArch,

    /// The Mach-O file type.
    #[arg(long, value_enum, default_value_t = MachOFileType::Executable)]
    file_type: MachOFileType,

    /// Do not write platform targeting to Mach-O binary.
    #[arg(long)]
    no_targeting: bool,

    /// The minimum operating system version the binary will run on.
    #[arg(long)]
    minimum_os_version: Option<semver::Version>,

    /// The platform SDK version used to build the binary.
    #[arg(long)]
    sdk_version: Option<semver::Version>,

    /// Set the file start offset of the __TEXT segment.
    #[arg(long)]
    text_segment_start_offset: Option<usize>,

    /// Filename of Mach-O binary to write.
    output_path: PathBuf,
}

impl DebugCreateMachO {
    fn run(&self) -> Result<(), AppleCodesignError> {
        let mut builder = match self.architecture {
            MachOArch::Aarch64 => {
                crate::macho_builder::MachOBuilder::new_aarch64(self.file_type.to_header_filetype())
            }
            MachOArch::X86_64 => {
                crate::macho_builder::MachOBuilder::new_x86_64(self.file_type.to_header_filetype())
            }
        };

        let target = match (
            self.no_targeting,
            &self.minimum_os_version,
            &self.sdk_version,
        ) {
            (true, _, _) => None,
            (false, None, None) => {
                warn!("assuming default minimum version 11.0.0");

                Some(crate::macho::MachoTarget {
                    platform: crate::Platform::MacOs,
                    minimum_os_version: semver::Version::new(11, 0, 0),
                    sdk_version: semver::Version::new(11, 0, 0),
                })
            }
            (false, _, _) => {
                let minimum_os_version = self
                    .minimum_os_version
                    .clone()
                    .unwrap_or_else(|| self.sdk_version.clone().unwrap());
                let sdk_version = self
                    .sdk_version
                    .clone()
                    .unwrap_or_else(|| self.minimum_os_version.clone().unwrap());

                Some(crate::macho::MachoTarget {
                    platform: crate::Platform::MacOs,
                    minimum_os_version,
                    sdk_version,
                })
            }
        };

        if let Some(target) = target {
            builder = builder.macho_target(target);
        }

        if let Some(offset) = self.text_segment_start_offset {
            builder = builder.text_segment_start_offset(offset);
        }

        let data = builder.write_macho()?;

        warn!("writing Mach-O to {}", self.output_path.display());
        if let Some(parent) = self.output_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(&self.output_path, data)?;

        Ok(())
    }
}

#[derive(Parser)]
struct DebugFileTree {
    /// Directory to walk.
    path: PathBuf,
}

impl DebugFileTree {
    fn run(&self) -> Result<(), AppleCodesignError> {
        let root = self
            .path
            .components()
            .last()
            .expect("should have final component")
            .as_os_str()
            .to_string_lossy()
            .to_string();

        for entry in walkdir::WalkDir::new(&self.path).sort_by_file_name() {
            let entry = entry?;

            let path = entry.path();

            let rel_path = if let Ok(p) = path.strip_prefix(&self.path) {
                format!("{}/{}", root, p.to_string_lossy().replace('\\', "/"))
            } else {
                root.clone()
            };

            let metadata = entry.metadata()?;

            let entry_type = if metadata.is_symlink() {
                'l'
            } else if metadata.is_dir() {
                'd'
            } else if metadata.is_file() {
                'f'
            } else {
                'u'
            };

            let sha256 = if entry_type == 'f' {
                let data = std::fs::read(path)?;
                hex::encode(DigestType::Sha256.digest_data(&data)?)[0..20].to_string()
            } else {
                " ".repeat(20)
            };

            let link_target = if entry_type == 'l' {
                format!(" -> {}", std::fs::read_link(path)?.to_string_lossy())
            } else {
                "".to_string()
            };

            println!("{} {} {}{}", entry_type, sha256, rel_path, link_target);
        }

        Ok(())
    }
}

#[derive(Parser)]
struct DiffSignatures {
    /// The first path to compare
    path0: PathBuf,

    /// The second path to compare
    path1: PathBuf,
}

fn command_diff_signatures(args: &DiffSignatures) -> Result<(), AppleCodesignError> {
    let reader = SignatureReader::from_path(&args.path0)?;

    let a_entities = reader.entities()?;

    let reader = SignatureReader::from_path(&args.path1)?;
    let b_entities = reader.entities()?;

    let a = serde_yaml::to_string(&a_entities)?;
    let b = serde_yaml::to_string(&b_entities)?;

    let Changeset { diffs, .. } = Changeset::new(&a, &b, "\n");

    for item in diffs {
        match item {
            Difference::Same(ref x) => {
                for line in x.lines() {
                    println!(" {line}");
                }
            }
            Difference::Add(ref x) => {
                for line in x.lines() {
                    println!("+{line}");
                }
            }
            Difference::Rem(ref x) => {
                for line in x.lines() {
                    println!("-{line}");
                }
            }
        }
    }

    Ok(())
}

#[cfg(feature = "notarize")]
const ENCODE_APP_STORE_CONNECT_API_KEY_ABOUT: &str = "\
Encode an App Store Connect API Key to JSON.

App Store Connect API Keys
(https://developer.apple.com/documentation/appstoreconnectapi/creating_api_keys_for_app_store_connect_api)
are defined by 3 components:

* The Issuer ID (likely a UUID)
* A Key ID (an alphanumeric value like `DEADBEEF42`)
* A PEM encoded ECDSA private key (typically a file beginning with
  `-----BEGIN PRIVATE KEY-----`).

This command is used to encode all API Key components into a single JSON
object so you only have to refer to a single entity when performing
operations (like notarization) using these API Keys.

The API Key components are specified as positional arguments.

By default, the JSON encoded unified representation is printed to stdout.
You can write to a file instead by passing `--output-path <path>`.

# Security Considerations

The App Store Connect API Key contains a private key and its value should be
treated as sensitive: if an unwanted party obtains your private key, they
effectively have access to your App Store Connect account.

When this command writes JSON files, an attempt is made to limit access
to the file. However, file access restrictions may not be as secure as you
want. Security conscious individuals should audit the permissions of the
file and adjust accordingly.
";

#[cfg(feature = "notarize")]
#[derive(Parser)]
struct EncodeAppStoreConnectApiKey {
    /// Path to a JSON file to create the output to
    #[arg(short = 'o', long)]
    output_path: Option<PathBuf>,

    /// The issuer of the API Token. Likely a UUID
    issuer_id: String,

    /// The Key ID. A short alphanumeric string like DEADBEEF42
    key_id: String,

    /// Path to a file containing the private key downloaded from Apple
    private_key_path: PathBuf,
}

#[cfg(feature = "notarize")]
fn command_encode_app_store_connect_api_key(
    args: &EncodeAppStoreConnectApiKey,
) -> Result<(), AppleCodesignError> {
    let unified = app_store_connect::UnifiedApiKey::from_ecdsa_pem_path(
        &args.issuer_id,
        &args.key_id,
        &args.private_key_path,
    )?;

    if let Some(output_path) = &args.output_path {
        eprintln!("writing unified key JSON to {}", output_path.display());
        unified.write_json_file(output_path)?;
        eprintln!(
            "consider auditing the file's access permissions to ensure its content remains secure"
        );
    } else {
        println!("{}", unified.to_json_string()?);
    }

    Ok(())
}

fn print_signed_data(
    prefix: &str,
    signed_data: &SignedData,
    external_content: Option<Vec<u8>>,
) -> Result<(), AppleCodesignError> {
    println!(
        "{}signed content (embedded): {:?}",
        prefix,
        signed_data.signed_content().map(hex::encode)
    );
    println!(
        "{}signed content (external): {:?}... ({} bytes)",
        prefix,
        external_content.as_ref().map(|x| hex::encode(&x[0..40])),
        external_content.as_ref().map(|x| x.len()).unwrap_or(0),
    );

    let content = if let Some(v) = signed_data.signed_content() {
        Some(v)
    } else {
        external_content.as_ref().map(|v| v.as_ref())
    };

    if let Some(content) = content {
        println!(
            "{}signed content SHA-1:   {}",
            prefix,
            hex::encode(DigestType::Sha1.digest_data(content)?)
        );
        println!(
            "{}signed content SHA-256: {}",
            prefix,
            hex::encode(DigestType::Sha256.digest_data(content)?)
        );
        println!(
            "{}signed content SHA-384: {}",
            prefix,
            hex::encode(DigestType::Sha384.digest_data(content)?)
        );
        println!(
            "{}signed content SHA-512: {}",
            prefix,
            hex::encode(DigestType::Sha512.digest_data(content)?)
        );
    }
    println!(
        "{}certificate count: {}",
        prefix,
        signed_data.certificates().count()
    );
    for (i, cert) in signed_data.certificates().enumerate() {
        println!(
            "{}certificate #{}: subject CN={}; self signed={}",
            prefix,
            i,
            cert.subject_common_name()
                .unwrap_or_else(|| "<unknown>".to_string()),
            cert.subject_is_issuer()
        );
    }
    println!("{}signer count: {}", prefix, signed_data.signers().count());
    for (i, signer) in signed_data.signers().enumerate() {
        println!(
            "{}signer #{}: digest algorithm: {:?}",
            prefix,
            i,
            signer.digest_algorithm()
        );
        println!(
            "{}signer #{}: signature algorithm: {:?}",
            prefix,
            i,
            signer.signature_algorithm()
        );

        if let Some(sa) = signer.signed_attributes() {
            println!(
                "{}signer #{}: content type: {}",
                prefix,
                i,
                sa.content_type()
            );
            println!(
                "{}signer #{}: message digest: {}",
                prefix,
                i,
                hex::encode(sa.message_digest())
            );
            println!(
                "{}signer #{}: signing time: {:?}",
                prefix,
                i,
                sa.signing_time()
            );
        }

        let digested_data = signer.signed_content_with_signed_data(signed_data);

        println!(
            "{}signer #{}: signature content SHA-1:   {}",
            prefix,
            i,
            hex::encode(DigestType::Sha1.digest_data(&digested_data)?)
        );
        println!(
            "{}signer #{}: signature content SHA-256: {}",
            prefix,
            i,
            hex::encode(DigestType::Sha256.digest_data(&digested_data)?)
        );
        println!(
            "{}signer #{}: signature content SHA-384: {}",
            prefix,
            i,
            hex::encode(DigestType::Sha384.digest_data(&digested_data)?)
        );
        println!(
            "{}signer #{}: signature content SHA-512: {}",
            prefix,
            i,
            hex::encode(DigestType::Sha512.digest_data(&digested_data)?)
        );

        if signed_data.signed_content().is_some() {
            println!(
                "{}signer #{}: digest valid: {}",
                prefix,
                i,
                signer
                    .verify_message_digest_with_signed_data(signed_data)
                    .is_ok()
            );
        }
        println!(
            "{}signer #{}: signature valid: {}",
            prefix,
            i,
            signer
                .verify_signature_with_signed_data(signed_data)
                .is_ok()
        );

        println!(
            "{}signer #{}: time-stamp token present: {}",
            prefix,
            i,
            signer.time_stamp_token_signed_data()?.is_some()
        );

        if let Some(tsp_signed_data) = signer.time_stamp_token_signed_data()? {
            let prefix = format!("{prefix}signer #{i}: time-stamp token: ");

            print_signed_data(&prefix, &tsp_signed_data, None)?;
        }
    }

    Ok(())
}

#[derive(Clone, Parser)]
struct ExtractCommon {
    /// Path to Mach-O binary to examine
    path: PathBuf,
}

#[derive(Clone, Subcommand)]
enum ExtractData {
    /// Code directory blobs.
    Blobs(ExtractCommon),
    /// Information about cryptographic message syntax signature.
    CmsInfo(ExtractCommon),
    /// PEM encoded cryptographic message syntax signature.
    CmsPem(ExtractCommon),
    /// Binary cryptographic message syntax signature. Should be BER encoded ASN.1 data.
    CmsRaw(ExtractCommon),
    /// ASN.1 decoded cryptographic message syntax data.
    Cms(ExtractCommon),
    /// Information from the main code directory data structure.
    CodeDirectory(ExtractCommon),
    /// Raw binary data composing the code directory data structure.
    CodeDirectoryRaw(ExtractCommon),
    /// Reserialize the parsed code directory, parse it again, and then print it like `code-directory` would.
    CodeDirectorySerialized(ExtractCommon),
    /// Reserialize the parsed code directory and emit its binary.
    ///
    /// Useful for comparing round-tripping of code directory data.
    CodeDirectorySerializedRaw(ExtractCommon),
    /// Information about the __LINKEDIT Mach-O segment.
    LinkeditInfo(ExtractCommon),
    /// Complete content of the __LINKEDIT Mach-O segment.
    LinkeditSegmentRaw(ExtractCommon),
    /// Mach-O file header data.
    MachoHeader(ExtractCommon),
    /// High-level information about Mach-O load commands.
    MachoLoadCommands(ExtractCommon),
    /// Debug formatted Mach-O load command data structures.
    MachoLoadCommandsRaw(ExtractCommon),
    /// Information about Mach-O segments.
    MachoSegments(ExtractCommon),
    /// Mach-O targeting info.
    MachoTarget(ExtractCommon),
    /// Parsed code requirement statement/expression.
    Requirements(ExtractCommon),
    /// Raw binary data composing the requirements blob/slot.
    RequirementsRaw(ExtractCommon),
    /// Dump the internal Rust data structures representing the requirements expressions.
    RequirementsRust(ExtractCommon),
    /// Reserialize the code requirements blob, parse it again, and then print it like `requirements` would.
    RequirementsSerialized(ExtractCommon),
    /// Like `requirements-serialized` except emit the binary data representation.
    RequirementsSerializedRaw(ExtractCommon),
    /// Raw binary data constituting the signature data embedded in the binary.
    SignatureRaw(ExtractCommon),
    /// Show information about the SuperBlob record and high-level details of embedded Blob records.
    Superblob(ExtractCommon),
}

impl ExtractData {
    fn common_args(&self) -> &ExtractCommon {
        match self {
            ExtractData::Blobs(x) => x,
            ExtractData::CmsInfo(x) => x,
            ExtractData::CmsPem(x) => x,
            ExtractData::CmsRaw(x) => x,
            ExtractData::Cms(x) => x,
            ExtractData::CodeDirectoryRaw(x) => x,
            ExtractData::CodeDirectorySerializedRaw(x) => x,
            ExtractData::CodeDirectorySerialized(x) => x,
            ExtractData::CodeDirectory(x) => x,
            ExtractData::LinkeditInfo(x) => x,
            ExtractData::LinkeditSegmentRaw(x) => x,
            ExtractData::MachoHeader(x) => x,
            ExtractData::MachoLoadCommands(x) => x,
            ExtractData::MachoLoadCommandsRaw(x) => x,
            ExtractData::MachoSegments(x) => x,
            ExtractData::MachoTarget(x) => x,
            ExtractData::RequirementsRaw(x) => x,
            ExtractData::RequirementsRust(x) => x,
            ExtractData::RequirementsSerializedRaw(x) => x,
            ExtractData::RequirementsSerialized(x) => x,
            ExtractData::Requirements(x) => x,
            ExtractData::SignatureRaw(x) => x,
            ExtractData::Superblob(x) => x,
        }
    }
}

#[derive(Parser)]
struct Extract {
    /// Index of Mach-O binary to operate on within a universal/fat binary
    #[arg(long, global = true, default_value = "0")]
    universal_index: usize,

    /// Which data to extract and how to format it
    #[command(subcommand)]
    data: ExtractData,
}

impl Extract {
    fn run(&self) -> Result<(), AppleCodesignError> {
        let common = self.data.common_args();

        let data = std::fs::read(&common.path)?;
        let mach = MachFile::parse(&data)?;
        let macho = mach.nth_macho(self.universal_index)?;

        match self.data {
            ExtractData::Blobs(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                for blob in embedded.blobs {
                    let parsed = blob.into_parsed_blob()?;
                    println!("{parsed:#?}");
                }
            }
            ExtractData::CmsInfo(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(cms) = embedded.signature_data()? {
                    let signed_data = SignedData::parse_ber(cms)?;

                    let cd_data = if let Ok(Some(blob)) = embedded.code_directory() {
                        Some(blob.to_blob_bytes()?)
                    } else {
                        None
                    };

                    print_signed_data("", &signed_data, cd_data)?;
                } else {
                    eprintln!("no CMS data");
                }
            }
            ExtractData::CmsPem(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(cms) = embedded.signature_data()? {
                    print!("{}", pem::encode(&pem::Pem::new("PKCS7", cms.to_vec())));
                } else {
                    eprintln!("no CMS data");
                }
            }
            ExtractData::CmsRaw(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(cms) = embedded.signature_data()? {
                    std::io::stdout().write_all(cms)?;
                } else {
                    eprintln!("no CMS data");
                }
            }
            ExtractData::Cms(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(signed_data) = embedded.signed_data()? {
                    println!("{signed_data:#?}");
                } else {
                    eprintln!("no CMS data");
                }
            }
            ExtractData::CodeDirectoryRaw(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(blob) = embedded.find_slot(CodeSigningSlot::CodeDirectory) {
                    std::io::stdout().write_all(blob.data)?;
                } else {
                    eprintln!("no code directory");
                }
            }
            ExtractData::CodeDirectorySerializedRaw(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Ok(Some(cd)) = embedded.code_directory() {
                    std::io::stdout().write_all(&cd.to_blob_bytes()?)?;
                } else {
                    eprintln!("no code directory");
                }
            }
            ExtractData::CodeDirectorySerialized(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Ok(Some(cd)) = embedded.code_directory() {
                    let serialized = cd.to_blob_bytes()?;
                    println!("{:#?}", CodeDirectoryBlob::from_blob_bytes(&serialized)?);
                }
            }
            ExtractData::CodeDirectory(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(cd) = embedded.code_directory()? {
                    println!("{cd:#?}");
                } else {
                    eprintln!("no code directory");
                }
            }
            ExtractData::LinkeditInfo(_) => {
                let sig = macho
                    .find_signature_data()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
                println!("__LINKEDIT segment index: {}", sig.linkedit_segment_index);
                println!(
                    "__LINKEDIT segment start offset: {}",
                    sig.linkedit_segment_start_offset
                );
                println!(
                    "__LINKEDIT segment end offset: {}",
                    sig.linkedit_segment_end_offset
                );
                println!(
                    "__LINKEDIT segment size: {}",
                    sig.linkedit_segment_data.len()
                );
                println!(
                    "__LINKEDIT signature global start offset: {}",
                    sig.signature_file_start_offset
                );
                println!(
                    "__LINKEDIT signature global end offset: {}",
                    sig.signature_file_end_offset
                );
                println!(
                    "__LINKEDIT signature local segment start offset: {}",
                    sig.signature_segment_start_offset
                );
                println!(
                    "__LINKEDIT signature local segment end offset: {}",
                    sig.signature_segment_end_offset
                );
                println!("__LINKEDIT signature size: {}", sig.signature_data.len());
            }
            ExtractData::LinkeditSegmentRaw(_) => {
                let sig = macho
                    .find_signature_data()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
                std::io::stdout().write_all(sig.linkedit_segment_data)?;
            }
            ExtractData::MachoHeader(_) => {
                println!("{:#?}", macho.macho.header);
            }
            ExtractData::MachoLoadCommands(_) => {
                println!("load command count: {}", macho.macho.load_commands.len());

                for command in &macho.macho.load_commands {
                    println!(
                        "{}; offsets=0x{:x}-0x{:x} ({}-{}); size={}",
                        goblin::mach::load_command::cmd_to_str(command.command.cmd()),
                        command.offset,
                        command.offset + command.command.cmdsize(),
                        command.offset,
                        command.offset + command.command.cmdsize(),
                        command.command.cmdsize(),
                    );
                }
            }
            ExtractData::MachoLoadCommandsRaw(_) => {
                for command in &macho.macho.load_commands {
                    println!("{:?}", command);
                }
            }
            ExtractData::MachoSegments(_) => {
                println!("segments count: {}", macho.macho.segments.len());
                for (segment_index, segment) in macho.macho.segments.iter().enumerate() {
                    let sections = segment.sections()?;

                    println!(
                    "segment #{}; {}; offsets=0x{:x}-0x{:x} ({}-{}); addresses=0x{:x}-0x{:x}; vm/file size {}/{}; section count {}",
                    segment_index,
                    segment.name()?,
                    segment.fileoff,
                    segment.fileoff as usize + segment.data.len(),
                    segment.fileoff,
                    segment.fileoff as usize + segment.data.len(),
                    segment.vmaddr,
                    segment.vmaddr + segment.vmsize,
                    segment.vmsize,
                    segment.filesize,
                    sections.len()
                );
                    for (section_index, (section, _)) in sections.into_iter().enumerate() {
                        println!(
                        "segment #{}; section #{}: {}; offsets=0x{:x}-0x{:x} ({}-{}); addresses=0x{:x}-0x{:x}; size {}; align={}; flags={}",
                        segment_index,
                        section_index,
                        section.name()?,
                        section.offset,
                        section.offset as u64 + section.size,
                        section.offset,
                        section.offset as u64 + section.size,
                        section.addr,
                        section.addr + section.size,
                        section.size,
                        section.align,
                        section.flags,
                    );
                    }
                }
            }
            ExtractData::MachoTarget(_) => {
                if let Some(target) = macho.find_targeting()? {
                    println!("Platform: {}", target.platform);
                    println!("Minimum OS: {}", target.minimum_os_version);
                    println!("SDK: {}", target.sdk_version);
                } else {
                    println!("Unable to resolve Mach-O targeting from load commands");
                }
            }
            ExtractData::RequirementsRaw(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(blob) = embedded.find_slot(CodeSigningSlot::RequirementSet) {
                    std::io::stdout().write_all(blob.data)?;
                } else {
                    eprintln!("no requirements");
                }
            }
            ExtractData::RequirementsRust(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(reqs) = embedded.code_requirements()? {
                    for (typ, req) in &reqs.requirements {
                        for expr in req.parse_expressions()?.iter() {
                            println!("{typ} => {expr:#?}");
                        }
                    }
                } else {
                    eprintln!("no requirements");
                }
            }
            ExtractData::RequirementsSerializedRaw(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(reqs) = embedded.code_requirements()? {
                    std::io::stdout().write_all(&reqs.to_blob_bytes()?)?;
                } else {
                    eprintln!("no requirements");
                }
            }
            ExtractData::RequirementsSerialized(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(reqs) = embedded.code_requirements()? {
                    let serialized = reqs.to_blob_bytes()?;
                    println!("{:#?}", RequirementSetBlob::from_blob_bytes(&serialized)?);
                } else {
                    eprintln!("no requirements");
                }
            }
            ExtractData::Requirements(_) => {
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                if let Some(reqs) = embedded.code_requirements()? {
                    for (typ, req) in &reqs.requirements {
                        for expr in req.parse_expressions()?.iter() {
                            println!("{typ} => {expr}");
                        }
                    }
                } else {
                    eprintln!("no requirements");
                }
            }
            ExtractData::SignatureRaw(_) => {
                let sig = macho
                    .find_signature_data()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
                std::io::stdout().write_all(sig.signature_data)?;
            }
            ExtractData::Superblob(_) => {
                let sig = macho
                    .find_signature_data()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
                let embedded = macho
                    .code_signature()?
                    .ok_or(AppleCodesignError::BinaryNoCodeSignature)?;

                println!("file start offset: {}", sig.signature_file_start_offset);
                println!("file end offset: {}", sig.signature_file_end_offset);
                println!(
                    "__LINKEDIT start offset: {}",
                    sig.signature_segment_start_offset
                );
                println!(
                    "__LINKEDIT end offset: {}",
                    sig.signature_segment_end_offset
                );
                println!("length: {}", embedded.length);
                println!("blob count: {}", embedded.count);
                println!("blobs:");
                for blob in embedded.blobs {
                    println!("- index: {}", blob.index);
                    println!(
                        "  offsets: 0x{:x}-0x{:x} ({}-{})",
                        blob.offset,
                        blob.offset + blob.length - 1,
                        blob.offset,
                        blob.offset + blob.length - 1
                    );
                    println!("  length: {}", blob.length);
                    println!("  slot: {:?}", blob.slot);
                    println!("  magic: {:?} (0x{:x})", blob.magic, u32::from(blob.magic));
                    println!(
                        "  sha1: {}",
                        hex::encode(blob.digest_with(DigestType::Sha1)?)
                    );
                    println!(
                        "  sha256: {}",
                        hex::encode(blob.digest_with(DigestType::Sha256)?)
                    );
                    println!(
                        "  sha256-truncated: {}",
                        hex::encode(blob.digest_with(DigestType::Sha256Truncated)?)
                    );
                    println!(
                        "  sha384: {}",
                        hex::encode(blob.digest_with(DigestType::Sha384)?),
                    );
                    println!(
                        "  sha512: {}",
                        hex::encode(blob.digest_with(DigestType::Sha512)?),
                    );
                    println!(
                        "  sha1-base64: {}",
                        STANDARD_ENGINE.encode(blob.digest_with(DigestType::Sha1)?)
                    );
                    println!(
                        "  sha256-base64: {}",
                        STANDARD_ENGINE.encode(blob.digest_with(DigestType::Sha256)?)
                    );
                    println!(
                        "  sha256-truncated-base64: {}",
                        STANDARD_ENGINE.encode(blob.digest_with(DigestType::Sha256Truncated)?)
                    );
                    println!(
                        "  sha384-base64: {}",
                        STANDARD_ENGINE.encode(blob.digest_with(DigestType::Sha384)?)
                    );
                    println!(
                        "  sha512-base64: {}",
                        STANDARD_ENGINE.encode(blob.digest_with(DigestType::Sha512)?)
                    );
                }
            }
        }

        Ok(())
    }
}

#[derive(Parser)]
struct GenerateCertificateSigningRequest {
    /// Path to file to write PEM encoded CSR to
    #[arg(long)]
    csr_pem_path: Option<PathBuf>,

    #[command(flatten)]
    certificate: CertificateSource,
}

fn command_generate_certificate_signing_request(
    args: &GenerateCertificateSigningRequest,
) -> Result<(), AppleCodesignError> {
    let private_keys = args.certificate.resolve_certificates(true)?.0;

    let private_key = if private_keys.is_empty() {
        error!("no private keys found; a private key is required to sign a certificate signing request");
        return Err(AppleCodesignError::CliBadArgument);
    } else if private_keys.len() > 1 {
        error!(
            "at most 1 private key can be present (found {}); aborting",
            private_keys.len()
        );
        return Err(AppleCodesignError::CliBadArgument);
    } else {
        private_keys.into_iter().next().expect("checked size above")
    };

    let mut builder = X509CertificateBuilder::default();
    builder
        .subject()
        .append_common_name_utf8_string("Apple Code Signing CSR")
        .map_err(|e| AppleCodesignError::CertificateBuildError(format!("{e:?}")))?;

    warn!("generating CSR; you may be prompted to enter credentials to unlock the signing key");
    let pem = builder
        .create_certificate_signing_request(private_key.as_key_info_signer())?
        .encode_pem()?;

    if let Some(dest_path) = &args.csr_pem_path {
        if let Some(parent) = dest_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        warn!("writing PEM encoded CSR to {}", dest_path.display());
        std::fs::write(dest_path, pem.as_bytes())?;
    }

    print!("{pem}");

    Ok(())
}

#[derive(Parser)]
struct GenerateSelfSignedCertificate {
    /// Which key type to use
    #[arg(long, value_parser = ["ecdsa", "ed25519", "rsa"], default_value = "rsa")]
    algorithm: String,

    #[arg(long, value_parser = CertificateProfile::str_names(), default_value = "apple-development")]
    profile: String,

    /// Team ID (this is a short string attached to your Apple Developer account)
    #[arg(long, default_value = "unset")]
    team_id: String,

    /// The name of the person this certificate is for
    #[arg(long)]
    person_name: String,

    /// Country Name (C) value for certificate identifier
    #[arg(long, default_value = "XX")]
    country_name: String,

    /// How many days the certificate should be valid for
    #[arg(long, default_value = "365")]
    validity_days: i64,

    /// Base name of files to write PEM encoded certificate to
    #[arg(long)]
    pem_filename: Option<String>,

    /// Filename to write PEM encoded private key and public certificate to.
    #[arg(long)]
    pem_unified_filename: Option<PathBuf>,

    /// Filename to write a PKCS#12 / p12 / PFX encoded certificate to.
    #[arg(long = "p12-file", alias = "pfx-file")]
    p12_path: Option<PathBuf>,

    /// Password to use to encrypt --p12-path.
    ///
    /// If not provided you will be prompted for a password.
    #[arg(long)]
    p12_password: Option<String>,
}

impl GenerateSelfSignedCertificate {
    fn run(&self) -> Result<(), AppleCodesignError> {
        let algorithm = match self.algorithm.as_str() {
            "ecdsa" => KeyAlgorithm::Ecdsa(EcdsaCurve::Secp256r1),
            "ed25519" => KeyAlgorithm::Ed25519,
            "rsa" => KeyAlgorithm::Rsa,
            value => panic!("algorithm values should have been validated by arg parser: {value}"),
        };

        let profile = CertificateProfile::from_str(self.profile.as_str())?;

        let validity_duration = chrono::Duration::days(self.validity_days);

        let (cert, key_pair) = create_self_signed_code_signing_certificate(
            algorithm,
            profile,
            &self.team_id,
            &self.person_name,
            &self.country_name,
            validity_duration,
        )?;

        let cert_pem = cert.encode_pem();
        let key_pem = pem::encode(&pem::Pem::new(
            "PRIVATE KEY",
            key_pair.to_pkcs8_one_asymmetric_key_der().to_vec(),
        ));

        let mut wrote_file = false;

        if let Some(pem_filename) = &self.pem_filename {
            let cert_path = PathBuf::from(format!("{pem_filename}.crt"));
            let key_path = PathBuf::from(format!("{pem_filename}.key"));

            if let Some(parent) = cert_path.parent() {
                std::fs::create_dir_all(parent)?;
            }

            println!("writing public certificate to {}", cert_path.display());
            std::fs::write(&cert_path, cert_pem.as_bytes())?;
            println!("writing private signing key to {}", key_path.display());
            std::fs::write(&key_path, key_pem.as_bytes())?;

            wrote_file = true;
        }

        if let Some(path) = &self.pem_unified_filename {
            let content = format!("{}{}", key_pem, cert_pem);

            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }

            println!("writing unified PEM to {}", path.display());
            std::fs::write(path, content.as_bytes())?;

            wrote_file = true;
        }

        if let Some(path) = &self.p12_path {
            let password = get_pkcs12_password(self.p12_password.clone(), None::<PathBuf>)?;

            let pfx = p12::PFX::new(
                &cert.encode_der()?,
                &key_pair.to_pkcs8_one_asymmetric_key_der(),
                None,
                &password,
                "code-signing",
            )
            .ok_or_else(|| {
                AppleCodesignError::CliGeneralError("failed to create PFX structure".into())
            })?;

            println!("writing PKCS#12 certificate to {}", path.display());

            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(path, pfx.to_der())?;

            wrote_file = true;
        }

        if !wrote_file {
            print!("{cert_pem}");
            print!("{key_pem}");
        }

        Ok(())
    }
}

#[derive(Parser)]
struct KeychainExportCertificateChain {
    /// Keychain domain to operate on
    #[arg(long, value_parser = KEYCHAIN_DOMAINS, default_value = "user")]
    domain: String,

    /// Password to unlock the Keychain
    #[arg(long, group = "unlock-password")]
    password: Option<String>,

    /// File containing password to use to unlock the Keychain
    #[arg(long, group = "unlock-password")]
    password_file: Option<PathBuf>,

    /// Print only the issuing certificate chain, not the subject certificate
    #[arg(long)]
    no_print_self: bool,

    /// User ID value of code signing certificate to find and whose CA chain to export
    #[arg(long)]
    user_id: String,
}

#[cfg(target_os = "macos")]
fn command_keychain_export_certificate_chain(
    args: &KeychainExportCertificateChain,
) -> Result<(), AppleCodesignError> {
    let domain = KeychainDomain::try_from(args.domain.as_str())
        .expect("clap should have validated domain values");

    let password = if let Some(path) = &args.password_file {
        let data = std::fs::read_to_string(path)?;

        Some(
            data.lines()
                .next()
                .expect("should get a single line")
                .to_string(),
        )
    } else {
        args.password.as_ref().map(|password| password.to_string())
    };

    let certs = macos_keychain_find_certificate_chain(domain, password.as_deref(), &args.user_id)?;

    for (i, cert) in certs.iter().enumerate() {
        if args.no_print_self && i == 0 {
            continue;
        }

        print!("{}", cert.encode_pem());
    }

    Ok(())
}

#[cfg(not(target_os = "macos"))]
fn command_keychain_export_certificate_chain(
    _args: &KeychainExportCertificateChain,
) -> Result<(), AppleCodesignError> {
    Err(AppleCodesignError::CliGeneralError(
        "macOS Keychain export only supported on macOS".to_string(),
    ))
}

#[derive(Parser)]
struct KeychainPrintCertificates {
    /// Keychain domain to operate on
    #[arg(long, value_parser = KEYCHAIN_DOMAINS, default_value = "user")]
    domain: String,
}

#[cfg(target_os = "macos")]
fn command_keychain_print_certificates(
    args: &KeychainPrintCertificates,
) -> Result<(), AppleCodesignError> {
    let domain = KeychainDomain::try_from(args.domain.as_str())
        .expect("clap should have validated domain values");

    let certs = keychain_find_code_signing_certificates(domain, None)?;

    for (i, cert) in certs.into_iter().enumerate() {
        println!("# Certificate {}", i);
        println!();
        print_certificate_info(&cert)?;
        println!();
    }

    Ok(())
}

#[cfg(not(target_os = "macos"))]
fn command_keychain_print_certificates(
    _args: &KeychainPrintCertificates,
) -> Result<(), AppleCodesignError> {
    Err(AppleCodesignError::CliGeneralError(
        "macOS Keychain integration supported on macOS".to_string(),
    ))
}

#[derive(Parser)]
struct MachoUniversalCreate {
    /// Input Mach-O binaries to combine.
    input: Vec<PathBuf>,

    /// Output file to write.
    #[arg(short = 'o', long)]
    output: PathBuf,
}

impl MachoUniversalCreate {
    fn run(&self) -> Result<(), AppleCodesignError> {
        let mut builder = crate::macho_universal::UniversalBinaryBuilder::default();

        for path in &self.input {
            eprintln!("adding {}", path.display());
            let data = std::fs::read(path)?;
            builder.add_binary(data)?;
        }

        eprintln!("writing {}", self.output.display());

        if let Some(parent) = self.output.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let mut fh = std::fs::File::create(&self.output)?;
        simple_file_manifest::set_executable(&mut fh)?;
        builder.write(&mut fh)?;

        Ok(())
    }
}

#[cfg(feature = "notarize")]
const NOTARIZE_ABOUT: &str = "\
Submit a notarization request to Apple.

This command is used to submit an asset to Apple for notarization. Given
a path to an asset with a code signature, this command will connect to Apple's
Notary API and upload the asset. It will then optionally wait on the submission
to finish processing (which typically takes a few dozen seconds). If the
asset validates Apple's requirements, Apple will issue a *notarization ticket*
as proof that they approved of it. This ticket is then added to the asset in a
process called *stapling*, which this command can do automatically if the
`--staple` argument is passed.

# App Store Connect API Key

In order to communicate with Apple's servers, you need an App Store Connect
API Key. This requires an Apple Developer account. You can generate an
API Key at https://appstoreconnect.apple.com/access/api.

The recommended mechanism to define the API Key is via `--api-key-path`,
which takes the path to a file containing JSON produced by the
`encode-app-store-connect-api-key` command. See that command's help for
more details.

If you don't wish to use `--api-key-path`, you can define the key components
via the `--api-issuer` and `--api-key` arguments. You will need a file named
`AuthKey_<ID>.p8` in one of the following locations: `$(pwd)/private_keys/`,
`~/private_keys/`, '~/.private_keys/`, and `~/.appstoreconnect/private_keys/`
(searched in that order). The name of the file is derived from the value of
`--api-key`.

In all cases, App Store Connect API Keys can be managed at
https://appstoreconnect.apple.com/access/api.

# Modes of Operation

By default, the `notarize` command will initiate an upload to Apple and exit
once the upload is complete.

Once an upload is performed, Apple will asynchronously process the uploaded
content. This can take seconds to minutes.

To poll Apple's servers and wait on the server-side processing to finish,
specify `--wait`. This will query the state of the processing every few seconds
until it is finished, the max wait time is reached, or an error occurs.

To automatically staple an asset after server-side processing has finished,
specify `--staple`. This implies `--wait`.
";

#[cfg(feature = "notarize")]
#[derive(Parser)]
struct NotaryLog {
    /// The ID of the previous submission to wait on
    submission_id: String,

    #[command(flatten)]
    api: NotaryApi,
}

#[cfg(feature = "notarize")]
fn command_notary_log(args: &NotaryLog) -> Result<(), AppleCodesignError> {
    let notarizer = args.api.notarizer()?;

    let log = notarizer.fetch_notarization_log(&args.submission_id)?;

    for line in serde_json::to_string_pretty(&log)?.lines() {
        println!("{line}");
    }

    Ok(())
}

#[cfg(feature = "notarize")]
#[derive(Parser)]
struct NotarySubmit {
    /// Whether to wait for upload processing to complete
    #[arg(long)]
    wait: bool,

    /// Maximum time in seconds to wait for the upload result
    #[arg(long, default_value = "600")]
    max_wait_seconds: u64,

    /// Staple the notarization ticket after successful upload (implies --wait)
    #[arg(long)]
    staple: bool,

    /// Path to asset to upload
    path: PathBuf,

    #[command(flatten)]
    api: NotaryApi,
}

#[cfg(feature = "notarize")]
fn command_notary_submit(args: &NotarySubmit) -> Result<(), AppleCodesignError> {
    let wait = args.wait || args.staple;

    let wait_limit = if wait {
        Some(std::time::Duration::from_secs(args.max_wait_seconds))
    } else {
        None
    };
    let notarizer = args.api.notarizer()?;

    let upload = notarizer.notarize_path(&args.path, wait_limit)?;

    if args.staple {
        match upload {
            crate::notarization::NotarizationUpload::UploadId(_) => {
                panic!(
                    "NotarizationUpload::UploadId should not be returned if we waited successfully"
                );
            }
            crate::notarization::NotarizationUpload::NotaryResponse(_) => {
                let stapler = crate::stapling::Stapler::new()?;
                stapler.staple_path(&args.path)?;
            }
        }
    }

    Ok(())
}

#[cfg(feature = "notarize")]
#[derive(Parser)]
struct NotaryWait {
    /// Maximum time in seconds to wait for the upload result
    #[arg(long, default_value = "600")]
    max_wait_seconds: u64,

    /// The ID of the previous submission to wait on
    submission_id: String,

    #[command(flatten)]
    api: NotaryApi,
}

#[cfg(feature = "notarize")]
fn command_notary_wait(args: &NotaryWait) -> Result<(), AppleCodesignError> {
    let wait_duration = std::time::Duration::from_secs(args.max_wait_seconds);
    let notarizer = args.api.notarizer()?;

    notarizer.wait_on_notarization_and_fetch_log(&args.submission_id, wait_duration)?;

    Ok(())
}

#[derive(Parser)]
struct ParseCodeSigningRequirement {
    /// Output format
    #[arg(long, value_parser = ["csrl", "expression-tree"], default_value = "csrl")]
    format: String,

    /// Path to file to parse
    input_path: PathBuf,
}

fn command_parse_code_signing_requirement(
    args: &ParseCodeSigningRequirement,
) -> Result<(), AppleCodesignError> {
    let data = std::fs::read(&args.input_path)?;

    let requirements = CodeRequirements::parse_blob(&data)?.0;

    for requirement in requirements.iter() {
        match args.format.as_str() {
            "csrl" => {
                println!("{requirement}");
            }
            "expression-tree" => {
                println!("{requirement:#?}");
            }
            format => panic!("unhandled format: {format}"),
        }
    }

    Ok(())
}

#[derive(Parser)]
struct PrintSignatureInfo {
    /// Filesystem path to entity whose info to print
    path: PathBuf,
}

fn command_print_signature_info(args: &PrintSignatureInfo) -> Result<(), AppleCodesignError> {
    let reader = SignatureReader::from_path(&args.path)?;

    let entities = reader.entities()?;
    serde_yaml::to_writer(std::io::stdout(), &entities)?;

    Ok(())
}

#[derive(Args)]
#[group(required = true, multiple = false)]
struct SessionJoinString {
    /// Open an editor to input the session join string
    #[arg(long = "editor")]
    session_join_string_editor: bool,

    /// Path to file containing session join string
    #[arg(long = "sjs-path")]
    session_join_string_path: Option<String>,

    /// Session join string (provided by the signing initiator)
    session_join_string: Option<String>,
}

#[derive(Parser)]
struct RemoteSign {
    #[command(flatten)]
    session_join_string: SessionJoinString,

    #[command(flatten)]
    certificate: CertificateSource,
}

fn command_remote_sign(args: &RemoteSign) -> Result<(), AppleCodesignError> {
    let session_join_string = if args.session_join_string.session_join_string_editor {
        let mut value = None;

        for _ in 0..3 {
            if let Some(content) = dialoguer::Editor::new()
                .require_save(true)
                .edit("# Please enter the -----BEGIN SESSION JOIN STRING---- content below.\n# Remember to save the file!")?
            {
                value = Some(content);
                break;
            }
        }

        value.ok_or_else(|| {
            AppleCodesignError::CliGeneralError("session join string not entered in editor".into())
        })?
    } else if let Some(path) = &args.session_join_string.session_join_string_path {
        std::fs::read_to_string(path)?
    } else if let Some(value) = &args.session_join_string.session_join_string {
        value.to_string()
    } else {
        return Err(AppleCodesignError::CliGeneralError(
            "session join string argument parsing failure".into(),
        ));
    };

    let mut joiner = create_session_joiner(session_join_string)?;

    if let Some(env) = &args.certificate.remote_shared_secret_env {
        let secret = std::env::var(env).map_err(|_| AppleCodesignError::CliBadArgument)?;
        joiner.register_state(SessionJoinState::SharedSecret(secret.as_bytes().to_vec()))?;
    } else if let Some(secret) = &args.certificate.remote_shared_secret {
        joiner.register_state(SessionJoinState::SharedSecret(secret.as_bytes().to_vec()))?;
    }

    let (private_keys, mut public_certificates) = args.certificate.resolve_certificates(true)?;

    let private = private_keys
        .into_iter()
        .next()
        .ok_or(AppleCodesignError::NoSigningCertificate)?;

    let cert = public_certificates.remove(0);

    let certificates = if let Some(chain) = cert.apple_root_certificate_chain() {
        // The chain starts with self.
        chain.into_iter().skip(1).collect::<Vec<_>>()
    } else {
        public_certificates
    };

    joiner.register_state(SessionJoinState::PublicKeyDecrypt(
        private.to_public_key_peer_decrypt()?,
    ))?;

    let client = UnjoinedSigningClient::new_signer(
        joiner,
        private.as_key_info_signer(),
        cert,
        certificates,
        args.certificate.remote_signing_url.clone(),
    )?;
    client.run()?;

    Ok(())
}

#[derive(Parser)]
struct Sign {
    /// Identifier string for binary. The value normally used by CFBundleIdentifier
    #[arg(long)]
    binary_identifier: Vec<String>,

    /// Path to a file containing binary code requirements data to be used as designated requirements
    #[arg(long)]
    code_requirements_path: Vec<String>,

    /// Path to an XML plist file containing code resources
    #[arg(long)]
    code_resources: Vec<String>,

    /// Code signature flags to set
    #[arg(long, value_parser = CodeSignatureFlags::all_user_configurable())]
    code_signature_flags: Vec<String>,

    /// Digest algorithm to use
    ///
    /// This typically doesn't need to be set as the OS targeting information
    /// from signed binaries implicitly derives appropriate digests to sign
    /// with.
    #[arg(long)]
    digest: Option<DigestType>,

    /// Extra digests to include in signatures
    ///
    /// This typically doesn't need to be set as the OS targeting information
    /// from signed binaries implicitly derives appropriate digests to sign
    /// with.
    #[arg(long, value_parser = SUPPORTED_HASHES)]
    extra_digest: Vec<String>,

    /// Path to a plist file containing entitlements
    #[arg(short = 'e', long)]
    entitlements_xml_path: Vec<String>,

    /// Hardened runtime version to use (defaults to SDK version used to build binary)
    #[arg(long)]
    runtime_version: Vec<String>,

    /// Path to an Info.plist file whose digest to include in Mach-O signature
    #[arg(long)]
    info_plist_path: Vec<String>,

    /// Team name/identifier to include in code signature
    #[arg(long)]
    team_name: Option<String>,

    /// An RFC 3339 date and time string to be used in signatures.
    ///
    /// e.g. 2023-11-05T10:42:00Z.
    ///
    /// If not specified, the current time will be used.
    ///
    /// Setting is only used when signing with a signing certificate.
    ///
    /// This setting is typically not necessary. It was added to facilitate
    /// deterministic signing behavior.
    #[arg(long)]
    signing_time: Option<String>,

    /// URL of time-stamp server to use to obtain a token of the CMS signature
    ///
    /// Can be set to the special value `none` to disable the generation of time-stamp
    /// tokens and use of a time-stamp server.
    #[arg(long, default_value = APPLE_TIMESTAMP_URL)]
    timestamp_url: String,

    /// Glob expression of paths to exclude from signing
    #[arg(long)]
    exclude: Vec<String>,

    /// Path to Mach-O binary to sign
    input_path: PathBuf,

    /// Path to signed Mach-O binary to write
    output_path: Option<PathBuf>,

    #[command(flatten)]
    certificate: CertificateSource,
}

fn command_sign(args: &Sign) -> Result<(), AppleCodesignError> {
    let mut settings = SigningSettings::default();

    let (private_keys, mut public_certificates) = args.certificate.resolve_certificates(true)?;

    if private_keys.len() > 1 {
        error!("at most 1 PRIVATE KEY can be present; aborting");
        return Err(AppleCodesignError::CliBadArgument);
    }

    let private = if private_keys.is_empty() {
        None
    } else {
        Some(&private_keys[0])
    };

    if let Some(signing_key) = &private {
        if public_certificates.is_empty() {
            error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
            return Err(AppleCodesignError::CliBadArgument);
        }

        let cert = public_certificates.remove(0);

        warn!("registering signing key");
        settings.set_signing_key(signing_key.as_key_info_signer(), cert);
        if let Some(certs) = settings.chain_apple_certificates() {
            for cert in certs {
                warn!(
                    "automatically registered Apple CA certificate: {}",
                    cert.subject_common_name()
                        .unwrap_or_else(|| "default".into())
                );
            }
        }

        if args.timestamp_url != "none" {
            warn!("using time-stamp protocol server {}", args.timestamp_url);
            settings.set_time_stamp_url(&args.timestamp_url)?;
        }
    }

    if let Some(time) = &args.signing_time {
        let time = chrono::DateTime::parse_from_rfc3339(time).map_err(|e| {
            AppleCodesignError::CliGeneralError(format!("invalid signing time format: {}", e))
        })?;
        let time = time.with_timezone(&chrono::Utc);
        settings.set_signing_time(time);
    }

    if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
        warn!(
            "automatically setting team ID from signing certificate: {}",
            team_id
        );
    }

    for cert in public_certificates {
        warn!("registering extra X.509 certificate");
        settings.chain_certificate(cert);
    }

    if let Some(team_name) = &args.team_name {
        settings.set_team_id(team_name);
    }

    if let Some(value) = &args.digest {
        settings.set_digest_type(*value);
    }

    for value in &args.extra_digest {
        let (scope, digest_type) = parse_scoped_value(value)?;
        let digest_type = DigestType::try_from(digest_type)?;
        settings.add_extra_digest(scope, digest_type);
    }

    for pattern in &args.exclude {
        settings.add_path_exclusion(pattern)?;
    }

    for value in &args.binary_identifier {
        let (scope, identifier) = parse_scoped_value(value)?;
        settings.set_binary_identifier(scope, identifier);
    }

    for value in &args.code_requirements_path {
        let (scope, path) = parse_scoped_value(value)?;

        let code_requirements_data = std::fs::read(path)?;
        let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
        for expr in reqs.iter() {
            warn!(
                "setting designated code requirements for {}: {}",
                scope, expr
            );
            settings.set_designated_requirement_expression(scope.clone(), expr)?;
        }
    }

    for value in &args.code_resources {
        let (scope, path) = parse_scoped_value(value)?;

        warn!(
            "setting code resources data for {} from path {}",
            scope, path
        );
        let code_resources_data = std::fs::read(path)?;
        settings.set_code_resources_data(scope, code_resources_data);
    }

    // If code signature flags are specified, they overwrite defaults. Do
    // a pass over scopes to reset all flags then re-add the flags.
    for value in &args.code_signature_flags {
        let scope = parse_scoped_value(value)?.0;
        if let Some(existing) = settings.code_signature_flags(&scope) {
            if existing != CodeSignatureFlags::empty() {
                warn!(
                    "removing code signature flags {:?} from {}",
                    existing, scope
                );
            }
        }
        settings.set_code_signature_flags(scope, CodeSignatureFlags::empty());
    }

    for value in &args.code_signature_flags {
        let (scope, value) = parse_scoped_value(value)?;
        let flags = CodeSignatureFlags::from_str(value)?;
        warn!("adding code signature flag {:?} to {}", flags, scope);
        settings.add_code_signature_flags(scope, flags);
    }

    for value in &args.entitlements_xml_path {
        let (scope, path) = parse_scoped_value(value)?;

        warn!("setting entitlements XML for {} from path {}", scope, path);
        let entitlements_data = std::fs::read_to_string(path)?;
        settings.set_entitlements_xml(scope, entitlements_data)?;
    }

    for value in &args.runtime_version {
        let (scope, value) = parse_scoped_value(value)?;

        let version = semver::Version::parse(value)?;
        settings.set_runtime_version(scope, version);
    }

    for value in &args.info_plist_path {
        let (scope, value) = parse_scoped_value(value)?;

        let content = std::fs::read(value)?;
        settings.set_info_plist_data(scope, content);
    }

    let signer = UnifiedSigner::new(settings);

    if let Some(output_path) = &args.output_path {
        warn!(
            "signing {} to {}",
            args.input_path.display(),
            output_path.display()
        );
        signer.sign_path(&args.input_path, output_path)?;
    } else {
        warn!("signing {} in place", args.input_path.display());
        signer.sign_path_in_place(&args.input_path)?;
    }

    if let Some(private) = &private {
        private.finish()?;
    }

    Ok(())
}

#[cfg(feature = "yubikey")]
fn command_smartcard_scan() -> Result<(), AppleCodesignError> {
    let mut ctx = ::yubikey::reader::Context::open()?;
    for (index, reader) in ctx.iter()?.enumerate() {
        println!("Device {}: {}", index, reader.name());

        if let Ok(yk) = reader.open() {
            let mut yk = crate::yubikey::YubiKey::from(yk);
            println!("Device {}: Serial: {}", index, yk.inner()?.serial());
            println!("Device {}: Version: {}", index, yk.inner()?.version());

            for (slot, cert) in yk.find_certificates()? {
                println!(
                    "Device {}: Certificate in slot {:?} / {}",
                    index,
                    slot,
                    hex::encode([u8::from(slot)])
                );
                print_certificate_info(&cert)?;
                println!();
            }
        }
    }

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_scan() -> Result<(), AppleCodesignError> {
    eprintln!("smartcard reading requires the `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[derive(Parser)]
struct SmartcardGenerateKey {
    /// Smartcard slot number to store key in (9c is common)
    #[arg(long)]
    smartcard_slot: String,

    #[command(flatten)]
    policy: YubikeyPolicy,
}

#[cfg(feature = "yubikey")]
fn command_smartcard_generate_key(args: &SmartcardGenerateKey) -> Result<(), AppleCodesignError> {
    let slot_id = ::yubikey::piv::SlotId::from_str(&args.smartcard_slot)?;

    let touch_policy = str_to_touch_policy(args.policy.touch_policy.as_str())?;
    let pin_policy = str_to_pin_policy(args.policy.pin_policy.as_str())?;

    let mut yk = YubiKey::new()?;
    yk.set_pin_callback(prompt_smartcard_pin);

    yk.generate_key(slot_id, touch_policy, pin_policy)?;

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_generate_key(_args: &SmartcardGenerateKey) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard integration requires the `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[derive(Parser)]
struct SmartcardImport {
    /// Re-use the existing private key in the smartcard slot
    #[arg(long)]
    existing_key: bool,

    /// Don't actually perform the import
    #[arg(long)]
    dry_run: bool,

    #[command(flatten)]
    certificate: CertificateSource,

    #[command(flatten)]
    policy: YubikeyPolicy,
}

#[cfg(feature = "yubikey")]
fn command_smartcard_import(args: &SmartcardImport) -> Result<(), AppleCodesignError> {
    let (keys, certs) = args.certificate.resolve_certificates(false)?;

    let slot_id = ::yubikey::piv::SlotId::from_str(
        args.certificate.smartcard_slot.as_ref().ok_or_else(|| {
            error!("--smartcard-slot is required");
            AppleCodesignError::CliBadArgument
        })?,
    )?;
    let touch_policy = str_to_touch_policy(args.policy.touch_policy.as_str())?;
    let pin_policy = str_to_pin_policy(args.policy.pin_policy.as_str())?;

    println!(
        "found {} private keys and {} public certificates",
        keys.len(),
        certs.len()
    );

    let key = if args.existing_key {
        println!("using existing private key in smartcard");

        if !keys.is_empty() {
            println!(
                "ignoring {} private keys specified via arguments",
                keys.len()
            );
        }

        None
    } else {
        Some(keys.into_iter().next().ok_or_else(|| {
            println!("no private key found");
            AppleCodesignError::CliBadArgument
        })?)
    };

    let cert = certs.into_iter().next().ok_or_else(|| {
        println!("no public certificates found");
        AppleCodesignError::CliBadArgument
    })?;

    println!(
        "Will import the following certificate into slot {}",
        hex::encode([u8::from(slot_id)])
    );
    print_certificate_info(&cert)?;

    let mut yk = YubiKey::new()?;
    yk.set_pin_callback(prompt_smartcard_pin);

    if args.dry_run {
        println!("dry run mode enabled; stopping");
        return Ok(());
    }

    if let Some(key) = key {
        yk.import_key(
            slot_id,
            key.as_key_info_signer(),
            &cert,
            touch_policy,
            pin_policy,
        )?;
    } else {
        yk.import_certificate(slot_id, &cert)?;
    }

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_import(_args: &SmartcardImport) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard import requires `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[derive(Parser)]
struct Staple {
    /// Path to entity to attempt to staple
    path: PathBuf,
}

fn command_staple(args: &Staple) -> Result<(), AppleCodesignError> {
    let stapler = crate::stapling::Stapler::new()?;
    stapler.staple_path(&args.path)?;

    Ok(())
}

#[derive(Parser)]
struct Verify {
    /// Path of Mach-O binary to examine
    path: PathBuf,
}

fn command_verify(args: &Verify) -> Result<(), AppleCodesignError> {
    let path_type = crate::PathType::from_path(&args.path)?;

    if path_type != crate::PathType::MachO {
        return Err(AppleCodesignError::CliGeneralError(format!(
            "verify command only works on Mach-O binaries; provided path is a {:?}",
            path_type
        )));
    }

    warn!("(the verify command is known to be buggy and gives misleading results; we highly recommend using Apple's tooling until this message is removed)");
    let data = std::fs::read(&args.path)?;

    let problems = crate::verify::verify_macho_data(data);

    for problem in &problems {
        println!("{problem}");
    }

    if problems.is_empty() {
        eprintln!("no problems detected!");
        eprintln!("(we do not verify everything so please do not assume that the signature meets Apple standards)");
        Ok(())
    } else {
        Err(AppleCodesignError::VerificationProblems)
    }
}

fn command_x509_oids() -> Result<(), AppleCodesignError> {
    println!("# Extended Key Usage (EKU) Extension OIDs");
    println!();
    for ekup in crate::certificate::ExtendedKeyUsagePurpose::all() {
        println!("{}\t{:?}", ekup.as_oid(), ekup);
    }
    println!();
    println!("# Code Signing Certificate Extension OIDs");
    println!();
    for ext in crate::certificate::CodeSigningCertificateExtension::all() {
        println!("{}\t{:?}", ext.as_oid(), ext);
    }
    println!();
    println!("# Certificate Authority Certificate Extension OIDs");
    println!();
    for ext in crate::certificate::CertificateAuthorityExtension::all() {
        println!("{}\t{:?}", ext.as_oid(), ext);
    }

    Ok(())
}

#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum Subcommands {
    /// Analyze an X.509 certificate for Apple code signing properties.
    ///
    /// Given the path to a PEM encoded X.509 certificate, this command will read
    /// the certificate and print information about it relevant to Apple code
    /// signing.
    ///
    /// The output of the command can be useful to learn about X.509 certificate
    /// extensions used by code signing certificates and to debug low-level
    /// properties related to certificates.
    AnalyzeCertificate(AnalyzeCertificate),

    /// Compute code hashes for a binary
    ComputeCodeHashes(ComputeCodeHashes),

    /// Create a binary code requirements file.
    #[command(hide = true)]
    DebugCreateCodeRequirements(DebugCreateCodeRequirements),

    /// Create an entitlements file.
    #[command(hide = true)]
    DebugCreateEntitlements(DebugCreateEntitlements),

    /// Create an Info.plist file.
    #[command(hide = true)]
    DebugCreateInfoPlist(DebugCreateInfoPlist),

    /// Create a Mach-O binary from parameters.
    #[command(hide = true)]
    DebugCreateMacho(DebugCreateMachO),

    /// Print a filesystem tree with basic metadata.
    #[command(hide = true)]
    DebugFileTree(DebugFileTree),

    /// Print a diff between the signature content of two paths
    DiffSignatures(DiffSignatures),

    /// Encode App Store Connect API Key metadata to a single file
    #[cfg(feature = "notarize")]
    #[command(long_about = ENCODE_APP_STORE_CONNECT_API_KEY_ABOUT)]
    EncodeAppStoreConnectApiKey(EncodeAppStoreConnectApiKey),

    /// Print/extract various information from a Mach-O binary.
    ///
    /// Given the path to a Mach-O binary (including fat/universal binaries), this
    /// command will attempt to locate and format the requested data.
    #[command(override_usage = "rcodesign extract [OPTIONS] <COMMAND> <INPUT_PATH>")]
    Extract(Extract),

    /// Generates a certificate signing request that can be sent to Apple and exchanged for a signing certificate
    GenerateCertificateSigningRequest(GenerateCertificateSigningRequest),

    /// Generate a self-signed certificate for code signing
    #[command(long_about = GENERATE_SELF_SIGNED_CERTIFICATE_ABOUT)]
    GenerateSelfSignedCertificate(GenerateSelfSignedCertificate),

    /// Export Apple CA certificates from the macOS Keychain
    KeychainExportCertificateChain(KeychainExportCertificateChain),

    /// Print information about certificates in the macOS keychain
    KeychainPrintCertificates(KeychainPrintCertificates),

    /// Create a universal ("fat") Mach-O binary.
    ///
    /// This is similar to the `lipo -create` command. Use it to stitch
    /// multiple single architecture Mach-O binaries into a single multi-arch
    /// binary.
    MachoUniversalCreate(MachoUniversalCreate),

    #[cfg(feature = "notarize")]
    /// Fetch the notarization log for a previous submission
    NotaryLog(NotaryLog),

    /// Upload an asset to Apple for notarization and possibly staple it
    #[cfg(feature = "notarize")]
    #[command(long_about = NOTARIZE_ABOUT, alias = "notarize")]
    NotarySubmit(NotarySubmit),

    /// Wait for completion of a previous submission
    #[cfg(feature = "notarize")]
    NotaryWait(NotaryWait),

    /// Parse binary Code Signing Requirement data into a human readable string
    #[command(long_about = PARSE_CODE_SIGNING_REQUIREMENT_ABOUT)]
    ParseCodeSigningRequirement(ParseCodeSigningRequirement),

    /// Print signature information for a filesystem path
    PrintSignatureInfo(PrintSignatureInfo),

    /// Create signatures initiated from a remote signing operation
    RemoteSign(RemoteSign),

    /// Sign a Mach-O binary or bundle
    #[command(long_about = SIGN_ABOUT)]
    Sign(Sign),

    /// Generate a new private key on a smartcard
    SmartcardGenerateKey(SmartcardGenerateKey),

    /// Import a code signing certificate and key into a smartcard
    SmartcardImport(SmartcardImport),

    /// Show information about available smartcard (SC) devices
    SmartcardScan,

    /// Staples a notarization ticket to an entity
    Staple(Staple),

    /// Verifies code signature data
    Verify(Verify),

    /// Print information about X.509 OIDs related to Apple code signing
    X509Oids,
}

/// Sign and notarize Apple programs. See https://gregoryszorc.com/docs/apple-codesign/main/ for more docs
#[derive(Parser)]
#[command(author, version, arg_required_else_help = true)]
struct Cli {
    /// Increase logging verbosity. Can be specified multiple times
    #[arg(short = 'v', long, global = true, action = ArgAction::Count)]
    verbose: u8,

    #[command(subcommand)]
    command: Subcommands,
}

pub fn main_impl() -> Result<(), AppleCodesignError> {
    let cli = Cli::parse();

    let log_level = match cli.verbose {
        0 => LevelFilter::Warn,
        1 => LevelFilter::Info,
        2 => LevelFilter::Debug,
        _ => LevelFilter::Trace,
    };

    let mut builder = env_logger::Builder::from_env(
        env_logger::Env::default().default_filter_or(log_level.as_str()),
    );

    // Disable log context except at higher log levels.
    if log_level <= LevelFilter::Info {
        builder
            .format_timestamp(None)
            .format_level(false)
            .format_target(false);
    }

    // This spews unwanted output at default level. Nerf it by default.
    if log_level == LevelFilter::Info {
        builder.filter_module("rustls", LevelFilter::Error);
    }

    builder.init();

    match &cli.command {
        Subcommands::AnalyzeCertificate(args) => command_analyze_certificate(args),
        Subcommands::ComputeCodeHashes(args) => command_compute_code_hashes(args),
        Subcommands::DiffSignatures(args) => command_diff_signatures(args),
        #[cfg(feature = "notarize")]
        Subcommands::EncodeAppStoreConnectApiKey(args) => {
            command_encode_app_store_connect_api_key(args)
        }
        Subcommands::DebugCreateCodeRequirements(args) => args.run(),
        Subcommands::DebugCreateEntitlements(args) => args.run(),
        Subcommands::DebugCreateInfoPlist(args) => args.run(),
        Subcommands::DebugCreateMacho(args) => args.run(),
        Subcommands::DebugFileTree(args) => args.run(),
        Subcommands::Extract(args) => args.run(),
        Subcommands::GenerateCertificateSigningRequest(args) => {
            command_generate_certificate_signing_request(args)
        }
        Subcommands::GenerateSelfSignedCertificate(args) => args.run(),
        Subcommands::KeychainExportCertificateChain(args) => {
            command_keychain_export_certificate_chain(args)
        }
        Subcommands::KeychainPrintCertificates(args) => command_keychain_print_certificates(args),
        Subcommands::MachoUniversalCreate(args) => args.run(),
        #[cfg(feature = "notarize")]
        Subcommands::NotaryLog(args) => command_notary_log(args),
        #[cfg(feature = "notarize")]
        Subcommands::NotarySubmit(args) => command_notary_submit(args),
        #[cfg(feature = "notarize")]
        Subcommands::NotaryWait(args) => command_notary_wait(args),
        Subcommands::ParseCodeSigningRequirement(args) => {
            command_parse_code_signing_requirement(args)
        }
        Subcommands::PrintSignatureInfo(args) => command_print_signature_info(args),
        Subcommands::RemoteSign(args) => command_remote_sign(args),
        Subcommands::Sign(args) => command_sign(args),
        Subcommands::SmartcardGenerateKey(args) => command_smartcard_generate_key(args),
        Subcommands::SmartcardImport(args) => command_smartcard_import(args),
        Subcommands::SmartcardScan => command_smartcard_scan(),
        Subcommands::Staple(args) => command_staple(args),
        Subcommands::Verify(args) => command_verify(args),
        Subcommands::X509Oids => command_x509_oids(),
    }
}

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

    #[test]
    fn verify_cli() {
        Cli::command().debug_assert();
    }
}