krill 0.9.0

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

use std::convert::TryFrom;
use std::path::PathBuf;
use std::str::{from_utf8_unchecked, FromStr};
use std::{env, fmt};

use bytes::Bytes;
use clap::{App, Arg, ArgMatches, SubCommand};

use rpki::crypto::KeyIdentifier;
use rpki::uri;
use rpki::x509::Time;

use crate::commons::crypto::{IdCert, SignSupport};
use crate::commons::remote::rfc8183;
use crate::commons::util::file;
use crate::commons::{
    api::{
        AddChildRequest, AuthorizationFmtError, CertAuthInit, ChildHandle, Handle, ParentCaContact, ParentCaReq,
        ParentHandle, PublicationServerUris, PublisherHandle, ResourceSet, ResourceSetError, RoaDefinition,
        RoaDefinitionUpdates, RtaName, Token, UpdateChildRequest,
    },
    error::KrillIoError,
};
use crate::constants::*;
use crate::daemon::ca::{ResourceTaggedAttestation, RtaContentRequest, RtaPrepareRequest};
use crate::{
    cli::report::{ReportError, ReportFormat},
    commons::api::RepositoryContact,
};

struct GeneralArgs {
    server: uri::Https,
    token: Token,
    format: ReportFormat,
    api: bool,
}

impl GeneralArgs {
    fn from_matches(matches: &ArgMatches) -> Result<Self, Error> {
        let server = {
            let mut server = match env::var(KRILL_CLI_SERVER_ENV) {
                Ok(server_str) => Some(uri::Https::try_from(server_str)?),
                Err(_) => None,
            };

            if let Some(server_str) = matches.value_of(KRILL_CLI_SERVER_ARG) {
                server = Some(uri::Https::from_str(server_str)?);
            }

            server.unwrap_or_else(|| uri::Https::from_str(KRILL_CLI_SERVER_DFLT).unwrap())
        };

        let token = {
            let mut token = env::var(KRILL_CLI_TOKEN_ENV).ok().map(Token::from);

            if let Some(token_str) = matches.value_of(KRILL_CLI_ADMIN_TOKEN_ARG) {
                token = Some(Token::from(token_str));
            }

            token.ok_or_else(|| Error::missing_arg_with_env(KRILL_CLI_ADMIN_TOKEN_ARG, KRILL_CLI_TOKEN_ENV))?
        };

        let format = {
            let mut format = match env::var(KRILL_CLI_FORMAT_ENV) {
                Ok(fmt_str) => Some(ReportFormat::from_str(&fmt_str)?),
                Err(_) => None,
            };

            if let Some(fmt_str) = matches.value_of(KRILL_CLI_FORMAT_ARG) {
                format = Some(ReportFormat::from_str(fmt_str)?);
            }

            format.unwrap_or(ReportFormat::Text)
        };

        let api = env::var(KRILL_CLI_API_ENV).is_ok() || matches.is_present(KRILL_CLI_API_ARG);

        Ok(GeneralArgs {
            server,
            token,
            format,
            api,
        })
    }
}

impl Default for GeneralArgs {
    fn default() -> Self {
        GeneralArgs {
            server: uri::Https::from_str(KRILL_CLI_SERVER_DFLT).unwrap(),
            token: Token::from(""),
            format: ReportFormat::Text,
            api: false,
        }
    }
}

/// This type holds all the necessary data to connect to a Krill daemon, and
/// authenticate, and perform a specific action.
pub struct Options {
    pub server: uri::Https,
    pub token: Token,
    pub format: ReportFormat,
    pub api: bool,
    pub command: Command,
}

impl Options {
    fn make(general: GeneralArgs, command: Command) -> Self {
        Options {
            server: general.server,
            token: general.token,
            format: general.format,
            api: general.api,
            command,
        }
    }

    pub fn format(&self) -> ReportFormat {
        self.format
    }

    /// Creates a new Options explicitly (useful for testing)
    pub fn new(server: uri::Https, token: &str, format: ReportFormat, command: Command) -> Self {
        Options {
            server,
            token: Token::from(token),
            format,
            api: false,
            command,
        }
    }

    fn add_general_args<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        app.arg(
            Arg::with_name(KRILL_CLI_SERVER_ARG)
                .short("s")
                .long(KRILL_CLI_SERVER_ARG)
                .value_name("URI")
                .help("The full URI to the krill server. Or set env: KRILL_CLI_SERVER")
                .required(false),
        )
        .arg(
            Arg::with_name(KRILL_CLI_ADMIN_TOKEN_ARG)
                .short("t")
                .long(KRILL_CLI_ADMIN_TOKEN_ARG)
                .value_name("string")
                .help("The secret token for the krill server. Or set env: KRILL_CLI_TOKEN")
                .required(false),
        )
        .arg(
            Arg::with_name(KRILL_CLI_FORMAT_ARG)
                .short("f")
                .long(KRILL_CLI_FORMAT_ARG)
                .value_name("type")
                .help("Report format: none|json|text (default). Or set env: KRILL_CLI_FORMAT")
                .required(false),
        )
        .arg(
            Arg::with_name(KRILL_CLI_API_ARG)
                .long(KRILL_CLI_API_ARG)
                .help("Only show the API call and exit. Or set env: KRILL_CLI_API=1")
                .required(false),
        )
    }

    fn add_my_ca_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        app.arg(
            Arg::with_name(KRILL_CLI_MY_CA_ARG)
                .value_name("name")
                .short("c")
                .long(KRILL_CLI_MY_CA_ARG)
                .help("The name of the CA you wish to control. Or set env: KRILL_CLI_MY_CA")
                .required(false),
        )
    }

    fn add_child_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        app.arg(
            Arg::with_name("child")
                .value_name("name")
                .long("child")
                .help("The name of the child CA you wish to control")
                .required(true),
        )
    }

    fn add_resource_args<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        app.arg(
            Arg::with_name("asn")
                .short("a")
                .long("asn")
                .value_name("AS resources")
                .help("The AS resources: e.g. AS1, AS3-4")
                .required(false),
        )
        .arg(
            Arg::with_name("ipv4")
                .short("4")
                .long("ipv4")
                .value_name("IPv4 resources")
                .help("The IPv4 resources: e.g. 192.168.0.0/16")
                .required(false),
        )
        .arg(
            Arg::with_name("ipv6")
                .short("6")
                .long("ipv6")
                .value_name("IPv6 resources")
                .help("The IPv6 resources: e.g. 2001:db8::/32")
                .required(false),
        )
    }

    fn add_parent_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        app.arg(
            Arg::with_name("parent")
                .long("parent")
                .short("p")
                .value_name("name")
                .help("The local name by which the CA refers to this parent")
                .required(true),
        )
    }

    fn make_config_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut config_sub =
            SubCommand::with_name("config").about("Creates a configuration file for krill and prints it to STDOUT");

        fn add_data_dir_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
            app.arg(
                Arg::with_name("data")
                    .long("data")
                    .short("d")
                    .value_name("path")
                    .help("Override the default path (./data/) for the data directory (must end with '/')")
                    .required(false),
            )
        }

        fn add_log_file_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
            app.arg(
                Arg::with_name("logfile")
                    .long("logfile")
                    .short("l")
                    .value_name("path")
                    .help("Override the default path (./krill.log) for the log file")
                    .required(false),
            )
        }

        #[cfg(feature = "multi-user")]
        fn add_id_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
            app.arg(
                Arg::with_name("id")
                    .long("id")
                    .value_name("id")
                    .help("Specify the id (e.g. username, email) to generate configuration for")
                    .required(true),
            )
        }

        #[cfg(feature = "multi-user")]
        fn add_attr_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
            app.arg(
                Arg::with_name("attr")
                    .short("a")
                    .long("attribute")
                    .value_name("attr")
                    .help("Specify key=value pair attributes to give the user")
                    .required(false)
                    .multiple(true),
            )
        }

        let mut simple = SubCommand::with_name("simple").about("Use a 3rd party repository for publishing");

        simple = Self::add_general_args(simple);
        simple = add_data_dir_arg(simple);
        simple = add_log_file_arg(simple);

        config_sub = config_sub.subcommand(simple);

        #[cfg(feature = "multi-user")]
        {
            let mut with_user =
                SubCommand::with_name("user").about("Generate a user authentication configuration file fragment");

            with_user = Self::add_general_args(with_user);
            with_user = add_id_arg(with_user);
            with_user = add_attr_arg(with_user);

            config_sub = config_sub.subcommand(with_user);
        }

        app.subcommand(config_sub)
    }

    fn make_cas_list_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let sub = SubCommand::with_name("list").about("List the current CAs");

        let sub = Self::add_general_args(sub);

        app.subcommand(sub)
    }

    fn make_cas_show_ca_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("show").about("Show details of a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_show_history_details_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("details").about("Show details for a command in the history of a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        sub = sub.arg(
            Arg::with_name("key")
                .long("key")
                .value_name("command key string")
                .help("The command key as shown in 'history commands'")
                .required(true),
        );

        app.subcommand(sub)
    }

    fn make_cas_show_history_list_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("commands").about("Show the commands sent to a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        sub = sub.arg(
            Arg::with_name("rows")
                .long("rows")
                .help("Number of rows (max 250)")
                .value_name("<number>")
                .required(false),
        );

        sub = sub.arg(
            Arg::with_name("offset")
                .long("offset")
                .help("Number of results to skip")
                .value_name("<number>")
                .required(false),
        );

        sub = sub.arg(
            Arg::with_name("after")
                .long("after")
                .help("Show commands issued after date/time in RFC 3339 format, e.g. 2020-04-09T19:37:02Z")
                .value_name("<RFC 3339 DateTime>")
                .required(false),
        );

        sub = sub.arg(
            Arg::with_name("before")
                .long("before")
                .help("Show commands issued after date/time in RFC 3339 format, e.g. 2020-04-09T19:37:02Z")
                .value_name("<RFC 3339 DateTime>")
                .required(false),
        );

        app.subcommand(sub)
    }

    fn make_cas_show_history_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("history").about("Show the history of a CA");

        sub = Self::make_cas_show_history_list_sc(sub);
        sub = Self::make_cas_show_history_details_sc(sub);

        app.subcommand(sub)
    }

    fn make_cas_add_ca_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("add").about("Add a new CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_delete_ca_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("delete")
            .about("Delete a CA and let it withdraw its objects and request revocation. WARNING: Irreversible!");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_children_add_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("add").about("Add a child to a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = Self::add_child_arg(sub);
        sub = Self::add_resource_args(sub);
        let sub = sub.arg(
            Arg::with_name("request")
                .long("request")
                .short("r")
                .help("The location of the RFC8183 Child Request XML file")
                .value_name("<XML file>")
                .required(true),
        );

        app.subcommand(sub)
    }

    fn make_cas_children_update_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("update").about("Update an existing child of a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = Self::add_child_arg(sub);
        sub = Self::add_resource_args(sub);
        sub = sub.arg(
            Arg::with_name("idcert")
                .long("idcert")
                .help("The child's updated ID certificate")
                .value_name("DER encoded certificate")
                .required(false),
        );

        app.subcommand(sub)
    }

    fn make_cas_children_response_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("response").about("Show the RFC8183 Parent Response XML");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = Self::add_child_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_children_info_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("info").about("Show info for a child (id and resources)");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = Self::add_child_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_children_remove_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("remove").about("Remove an existing child from a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = Self::add_child_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_children_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("children").about("Manage children for a CA");

        sub = Self::make_cas_children_add_sc(sub);
        sub = Self::make_cas_children_update_sc(sub);
        sub = Self::make_cas_children_info_sc(sub);
        sub = Self::make_cas_children_remove_sc(sub);
        sub = Self::make_cas_children_response_sc(sub);

        app.subcommand(sub)
    }

    fn make_cas_parents_request_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("request").about("Show RFC8183 Child Request XML");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_parents_add_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("add").about("Add a parent to, or update a parent of a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = Self::add_parent_arg(sub);
        sub = sub.arg(
            Arg::with_name("response")
                .long("response")
                .short("r")
                .help("The location of the RFC8183 Parent Response XML file")
                .value_name("<XML file>")
                .required(true),
        );

        app.subcommand(sub)
    }

    fn make_cas_parents_statuses_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("statuses").about("Show overview of all parent statuses of a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_parents_contact_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("contact").about("Show contact information for a parent of a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = Self::add_parent_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_parents_remove_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("remove").about("Remove an existing parent from a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = Self::add_parent_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_parents_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("parents").about("Manage parents for a CA");

        sub = Self::make_cas_parents_request_sc(sub);
        sub = Self::make_cas_parents_add_sc(sub);
        sub = Self::make_cas_parents_contact_sc(sub);
        sub = Self::make_cas_parents_statuses_sc(sub);
        sub = Self::make_cas_parents_remove_sc(sub);

        app.subcommand(sub)
    }

    fn make_cas_keyroll_init_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("init").about("Initialize roll for all keys held by a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_keyroll_activate_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("activate").about("Finish roll for all keys held by a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_keyroll_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("keyroll").about("Perform a manual key rollover for a CA");

        sub = Self::make_cas_keyroll_init_sc(sub);
        sub = Self::make_cas_keyroll_activate_sc(sub);

        app.subcommand(sub)
    }

    fn make_cas_routes_list_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("list").about("Show current authorizations");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_routes_update_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("update").about("Update authorizations");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        sub = sub.arg(
            Arg::with_name("delta")
                .long("delta")
                .help(concat!(
                    "Provide a delta file using the following format:\n",
                    "# Some comment\n",
                    "  # Indented comment\n",
                    "\n", // empty line
                    "A: 192.168.0.0/16 => 64496 # inline comment\n",
                    "A: 192.168.1.0/24 => 64496\n",
                    "R: 192.168.3.0/24 => 64496\n",
                ))
                .value_name("<file>")
                .required(false),
        );

        sub = sub.arg(
            Arg::with_name("add")
                .long("add")
                .help("One or more ROAs to add, e.g.: 192.168.0.0/16 => 64496")
                .value_name("<roa definition>")
                .multiple(true)
                .required(false),
        );

        sub = sub.arg(
            Arg::with_name("remove")
                .long("remove")
                .help("One or more ROAs to remove, e.g.: 192.168.0.0/16 => 64496")
                .value_name("<roa definition>")
                .multiple(true)
                .required(false),
        );

        sub = sub.arg(
            Arg::with_name("dryrun")
                .long("dryrun")
                .help("Perform a dry run of the update and return the BGP analysis for the scoped to the update")
                .required(false),
        );

        sub = sub.arg(
            Arg::with_name("try")
                .long("try")
                .help("Try to perform the update, advice in case it would result in errors or invalids")
                .required(false),
        );

        app.subcommand(sub)
    }

    fn make_cas_routes_bgp_full_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("analyze").about("Show full report of ROAs vs known BGP announcements");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        app.subcommand(sub)
    }

    fn make_cas_routes_bgp_suggestions_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("suggest").about("Show ROA suggestions based on known BGP announcements");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        sub = sub
            .arg(
                Arg::with_name("ipv4")
                    .short("4")
                    .long("ipv4")
                    .value_name("IPv4 resources")
                    .help("Scope to these IPv4 resources")
                    .required(false),
            )
            .arg(
                Arg::with_name("ipv6")
                    .short("6")
                    .long("ipv6")
                    .value_name("IPv6 resources")
                    .help("Scope to these IPv6 resources")
                    .required(false),
            );

        app.subcommand(sub)
    }

    fn make_cas_routes_bgp_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub =
            SubCommand::with_name("bgp").about("Show current authorizations in relation to known announcements");

        sub = Self::make_cas_routes_bgp_full_sc(sub);
        sub = Self::make_cas_routes_bgp_suggestions_sc(sub);

        app.subcommand(sub)
    }

    fn make_cas_routes_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("roas").about("Manage ROAs for a CA");

        sub = Self::make_cas_routes_list_sc(sub);
        sub = Self::make_cas_routes_update_sc(sub);
        sub = Self::make_cas_routes_bgp_sc(sub);

        app.subcommand(sub)
    }

    fn make_cas_repo_request_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("request").about("Show RFC8183 Publisher Request XML");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_repo_show_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("show").about("Show current repo config");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_repo_status_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("status").about("Show current repo status");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    fn make_cas_repo_configure_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("configure").about("Configure which repository a CA uses");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);
        sub = sub.arg(
            Arg::with_name("response")
                .value_name("file")
                .long("response")
                .short("r")
                .help("The location of the RFC8183 Publisher Response XML file")
                .required(true),
        );

        app.subcommand(sub)
    }

    fn make_cas_repo_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("repo").about("Manage the repository for a CA");

        sub = Self::make_cas_repo_request_sc(sub);
        sub = Self::make_cas_repo_show_sc(sub);
        sub = Self::make_cas_repo_status_sc(sub);
        sub = Self::make_cas_repo_configure_sc(sub);

        app.subcommand(sub)
    }

    fn make_cas_issues_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("issues").about("Show issues for a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    #[cfg(feature = "rta")]
    fn make_cas_rta_list<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("list").about("List RTAs");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        app.subcommand(sub)
    }

    #[cfg(feature = "rta")]
    fn make_cas_rta_show<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("show").about("Show RTA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        sub = sub.arg(
            Arg::with_name("name")
                .long("name")
                .short("n")
                .value_name("string")
                .help("Your local name for this RTA")
                .required(true),
        );

        sub = sub.arg(
            Arg::with_name("out")
                .long("out")
                .short("o")
                .value_name("path")
                .help("File to write RTA to")
                .required(true),
        );

        app.subcommand(sub)
    }

    #[cfg(feature = "rta")]
    fn make_cas_rta_sign_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("sign").about("Create an RTA signed by a CA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        sub = Self::add_resource_args(sub);

        sub = sub.arg(
            Arg::with_name("days")
                .long("days")
                .short("d")
                .value_name("number of days")
                .help("Validity time of the RTA in days")
                .required(true),
        );

        sub = sub.arg(
            Arg::with_name("in")
                .long("in")
                .short("i")
                .value_name("path")
                .help("Content which needs to be signed")
                .required(true),
        );

        sub = sub.arg(
            Arg::with_name("name")
                .long("name")
                .short("n")
                .value_name("string")
                .help("Your local name for this RTA")
                .required(true),
        );

        sub = sub.arg(
            Arg::with_name("keys")
                .long("keys")
                .short("k")
                .value_name("hex encoded key identifiers")
                .multiple(true)
                .help("Optional additional keys to include in this RTA")
                .required(false),
        );

        app.subcommand(sub)
    }

    #[cfg(feature = "rta")]
    fn make_cas_rta_multi_prep_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("prep").about("Prepare keys for multi-signed RTA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        sub = Self::add_resource_args(sub);

        sub = sub.arg(
            Arg::with_name("days")
                .long("days")
                .short("d")
                .value_name("number of days")
                .help("Validity time of the RTA in days")
                .required(true),
        );

        sub = sub.arg(
            Arg::with_name("name")
                .long("name")
                .short("n")
                .value_name("string")
                .help("Your local name for this RTA")
                .required(true),
        );

        app.subcommand(sub)
    }

    #[cfg(feature = "rta")]
    fn make_cas_rta_multi_sign_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("cosign").about("Co-sign an existing (prepared) RTA");

        sub = Self::add_general_args(sub);
        sub = Self::add_my_ca_arg(sub);

        sub = sub.arg(
            Arg::with_name("name")
                .long("name")
                .short("n")
                .value_name("string")
                .help("Your local name for this RTA")
                .required(true),
        );

        sub = sub.arg(
            Arg::with_name("in")
                .long("in")
                .short("i")
                .value_name("path")
                .help("RTA which needs to be co-signed")
                .required(true),
        );

        app.subcommand(sub)
    }

    #[cfg(feature = "rta")]
    fn make_cas_rta_multi_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("multi").about("Manage RTA signed by multiple parties");

        sub = Self::make_cas_rta_multi_prep_sc(sub);
        sub = Self::make_cas_rta_multi_sign_sc(sub);

        app.subcommand(sub)
    }

    #[cfg(feature = "rta")]
    fn make_cas_rta_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("rta").about("Manage Resource Tagged Attestations");
        sub = Self::make_cas_rta_list(sub);
        sub = Self::make_cas_rta_show(sub);
        sub = Self::make_cas_rta_sign_sc(sub);
        sub = Self::make_cas_rta_multi_sc(sub);
        app.subcommand(sub)
    }

    fn make_bulk_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("bulk").about("Manually trigger refresh/republish/resync for all CAs");

        let mut refresh =
            SubCommand::with_name("refresh").about("Force that all CAs ask their parents for updated certificates");
        refresh = Self::add_general_args(refresh);

        let mut republish = SubCommand::with_name("publish")
            .about("Force that all CAs create new objects if needed (in which case they will also sync)");
        republish = Self::add_general_args(republish);

        let mut resync = SubCommand::with_name("sync").about("Force that all CAs sync with their repo server");
        resync = Self::add_general_args(resync);

        sub = sub.subcommand(refresh).subcommand(republish).subcommand(resync);

        app.subcommand(sub)
    }

    fn make_health_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let health = SubCommand::with_name("health").about("Perform an authenticated health check");
        let health = Self::add_general_args(health);
        app.subcommand(health)
    }

    fn make_info_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let info = SubCommand::with_name("info").about("Show server info");
        let info = Self::add_general_args(info);
        app.subcommand(info)
    }

    fn make_publishers_list_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("list").about("List all publishers");
        sub = Options::add_general_args(sub);
        app.subcommand(sub)
    }

    fn make_publishers_stale_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("stale").about("List all publishers which have not published in a while");
        sub = Options::add_general_args(sub);
        sub = sub.arg(
            Arg::with_name("seconds")
                .value_name("seconds")
                .long("seconds")
                .help("The number of seconds since last publication")
                .required(true),
        );
        app.subcommand(sub)
    }

    fn add_publisher_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        app.arg(
            Arg::with_name("publisher")
                .value_name("handle")
                .short("p")
                .long("publisher")
                .help("The handle (name) of the publisher")
                .required(true),
        )
    }

    fn add_rsync_base_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        app.arg(
            Arg::with_name("rsync")
                .long("rsync")
                .value_name("uri")
                .help("Specify the base rsync URI for the repository, must end with '/'")
                .required(true),
        )
    }

    fn add_rrdp_base_uri_arg<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        app.arg(
            Arg::with_name("rrdp")
                .long("rrdp")
                .value_name("uri")
                .help(
                    "Specify the base https URI for the RRDP (excluding notification.xml), \
                    must \
                    end with '/'",
                )
                .required(true),
        )
    }

    fn make_publishers_add_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("add").about("Add a publisher");
        sub = Options::add_general_args(sub);

        sub = sub
            .arg(
                Arg::with_name("request")
                    .value_name("file")
                    .long("request")
                    .short("r")
                    .help("The location of the RFC8183 Publisher Request XML file")
                    .required(true),
            )
            .arg(
                Arg::with_name("publisher")
                    .value_name("handle")
                    .short("p")
                    .long("publisher")
                    .help("Override the publisher handle in the XML")
                    .required(false),
            );

        app.subcommand(sub)
    }

    fn make_publishers_remove_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("remove").about("Remove a publisher");
        sub = Options::add_general_args(sub);
        sub = Self::add_publisher_arg(sub);
        app.subcommand(sub)
    }

    fn make_publishers_show_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("show").about("Show details for a publisher");
        sub = Options::add_general_args(sub);
        sub = Self::add_publisher_arg(sub);
        app.subcommand(sub)
    }

    fn make_publishers_response_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("response").about("Show RFC8183 Repository Response XML");
        sub = Options::add_general_args(sub);
        sub = Self::add_publisher_arg(sub);
        app.subcommand(sub)
    }

    fn make_publication_server_stats_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("stats").about("Show publication server stats");
        sub = Options::add_general_args(sub);
        app.subcommand(sub)
    }

    fn make_publication_server_init_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("init").about("Initialize publication server");
        sub = Options::add_general_args(sub);

        sub = Self::add_rsync_base_arg(sub);
        sub = Self::add_rrdp_base_uri_arg(sub);

        app.subcommand(sub)
    }

    fn make_publication_server_clear_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("clear").about("Clear the publication server so it can re-initialized");
        sub = Options::add_general_args(sub);
        app.subcommand(sub)
    }

    fn make_publication_server_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("server").about("Manage the Publication Server (init/stats)");
        sub = Self::make_publication_server_stats_sc(sub);
        sub = Self::make_publication_server_init_sc(sub);
        sub = Self::make_publication_server_clear_sc(sub);
        app.subcommand(sub)
    }

    fn make_publishers_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("publishers").about("Manage the publishers in your Publication Server");

        sub = Self::make_publishers_list_sc(sub);
        sub = Self::make_publishers_stale_sc(sub);
        sub = Self::make_publishers_add_sc(sub);
        sub = Self::make_publishers_remove_sc(sub);
        sub = Self::make_publishers_show_sc(sub);
        sub = Self::make_publishers_response_sc(sub);

        app.subcommand(sub)
    }

    fn make_pubserver_sc<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
        let mut sub = SubCommand::with_name("pubserver")
            .about("Manage your Publication Server (only needed if you run your own)");

        sub = Self::make_publishers_sc(sub);
        sub = Self::make_publication_server_sc(sub);

        app.subcommand(sub)
    }

    fn make_matches<'a>() -> ArgMatches<'a> {
        let mut app = App::new(KRILL_CLIENT_APP).version(KRILL_VERSION);

        app = Self::make_config_sc(app);
        app = Self::make_cas_list_sc(app);
        app = Self::make_cas_show_ca_sc(app);
        app = Self::make_cas_show_history_sc(app);
        app = Self::make_cas_add_ca_sc(app);
        app = Self::make_cas_delete_ca_sc(app);
        app = Self::make_cas_children_sc(app);
        app = Self::make_cas_parents_sc(app);
        app = Self::make_cas_keyroll_sc(app);
        app = Self::make_cas_routes_sc(app);
        app = Self::make_cas_repo_sc(app);
        app = Self::make_cas_issues_sc(app);
        app = Self::make_pubserver_sc(app);

        #[cfg(feature = "rta")]
        {
            app = Self::make_cas_rta_sc(app);
        }

        app = Self::make_health_sc(app);

        app = Self::make_info_sc(app);

        app = Self::make_bulk_sc(app);

        app.get_matches()
    }

    //---------------------- Parsing

    fn read_file_arg(path: &str) -> Result<Bytes, Error> {
        let path = PathBuf::from(path);
        file::read(&path).map_err(Error::IoError)
    }

    fn parse_my_ca(matches: &ArgMatches) -> Result<Handle, Error> {
        let my_ca = {
            let mut my_ca = None;

            if let Ok(my_ca_env) = env::var(KRILL_CLI_MY_CA_ENV) {
                my_ca = Some(Handle::from_str(&my_ca_env).map_err(|_| Error::InvalidHandle)?);
            }

            if let Some(my_ca_str) = matches.value_of(KRILL_CLI_MY_CA_ARG) {
                my_ca = Some(Handle::from_str(my_ca_str).map_err(|_| Error::InvalidHandle)?);
            }

            my_ca.ok_or_else(|| Error::missing_arg_with_env(KRILL_CLI_MY_CA_ARG, KRILL_CLI_MY_CA_ENV))?
        };

        Ok(my_ca)
    }

    fn parse_resource_args(matches: &ArgMatches) -> Result<Option<ResourceSet>, Error> {
        let asn = matches.value_of("asn");
        let v4 = matches.value_of("ipv4");
        let v6 = matches.value_of("ipv6");

        if asn.is_some() || v4.is_some() || v6.is_some() {
            let asn = asn.unwrap_or("");
            let v4 = v4.unwrap_or("");
            let v6 = v6.unwrap_or("");

            Ok(Some(ResourceSet::from_strs(asn, v4, v6)?))
        } else {
            Ok(None)
        }
    }

    fn parse_matches_simple_config(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;

        #[cfg(not(feature = "multi-user"))]
        let mut details = KrillInitDetails::default();

        #[cfg(feature = "multi-user")]
        let mut details = KrillInitDetails::multi_user_dflt();

        if let Some(data) = matches.value_of("data") {
            if !data.ends_with('/') {
                return Err(Error::general("Path for --data MUST end with a '/'"));
            }
            details.with_data_dir(data);
        }
        if let Some(log_file) = matches.value_of("logfile") {
            details.with_log_file(log_file);
        }

        let command = Command::Init(details);
        Ok(Options::make(general_args, command))
    }

    #[cfg(feature = "multi-user")]
    fn parse_matches_user_config(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::default();
        let mut details = KrillUserDetails::default();
        if let Some(id) = matches.value_of("id") {
            details.with_id(id.to_string());
        }
        if let Some(attr_iter) = matches.values_of("attr") {
            for attr in attr_iter {
                let mut iter = attr.split('=');
                let k = iter
                    .next()
                    .ok_or_else(|| Error::general(&format!("attribute '{}' must be of the form key=value", attr)))?;
                let v = iter
                    .next()
                    .ok_or_else(|| Error::general(&format!("attribute '{}' must be of the form key=value", attr)))?;
                details.with_attr(k.to_string(), v.to_string());
            }
        }
        let command = Command::User(details);
        Ok(Options::make(general_args, command))
    }

    #[cfg(not(feature = "multi-user"))]
    fn parse_matches_user_config(_: &ArgMatches) -> Result<Options, Error> {
        Err(Error::UnrecognizedSubCommand)
    }

    fn parse_matches_config(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("simple") {
            Self::parse_matches_simple_config(m)
        } else if let Some(m) = matches.subcommand_matches("user") {
            Self::parse_matches_user_config(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_list(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let command = Command::CertAuth(CaCommand::List);
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_add(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let init = CertAuthInit::new(my_ca);

        let command = Command::CertAuth(CaCommand::Init(init));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_delete(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::Delete(my_ca));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_show(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::Show(my_ca));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_history_details(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;
        let key = matches.value_of("key").unwrap();

        let command = Command::CertAuth(CaCommand::ShowHistoryDetails(my_ca, key.to_string()));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_history_commands(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let mut options = HistoryOptions::default();

        if let Some(offset) = matches.value_of("offset") {
            let offset =
                u64::from_str(offset).map_err(|e| Error::general(&format!("invalid number: {}", e.to_string())))?;
            options.offset = offset
        }

        if let Some(rows) = matches.value_of("rows") {
            let rows =
                u64::from_str(rows).map_err(|e| Error::general(&format!("invalid number: {}", e.to_string())))?;
            if rows > 250 {
                return Err(Error::general("No more than 250 rows allowed in history"));
            }
            options.rows = rows
        }

        if let Some(after) = matches.value_of("after") {
            let time = Time::from_str(after)
                .map_err(|e| Error::general(&format!("invalid date format: {}", e.to_string())))?;
            options.after = Some(time);
        }

        if let Some(after) = matches.value_of("before") {
            let time = Time::from_str(after)
                .map_err(|e| Error::general(&format!("invalid date format: {}", e.to_string())))?;
            options.before = Some(time);
        }

        let command = Command::CertAuth(CaCommand::ShowHistoryCommands(my_ca, options));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_history(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("commands") {
            Self::parse_matches_cas_history_commands(m)
        } else if let Some(m) = matches.subcommand_matches("details") {
            Self::parse_matches_cas_history_details(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_children_add(matches: &ArgMatches) -> Result<Options, Error> {
        let path = matches.value_of("request").unwrap();
        let bytes = Self::read_file_arg(path)?;
        let child_request = rfc8183::ChildRequest::validate(bytes.as_ref())?;

        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let child = matches.value_of("child").unwrap();
        let child = Handle::from_str(child).map_err(|_| Error::InvalidHandle)?;

        let resources = Self::parse_resource_args(matches)?.ok_or(Error::MissingResources)?;

        let (_, _, id_cert) = child_request.unpack();
        let add_child_request = AddChildRequest::new(child, resources, id_cert);
        let command = Command::CertAuth(CaCommand::ChildAdd(my_ca, add_child_request));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_children_update(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let child = matches.value_of("child").unwrap();
        let child = Handle::from_str(child).map_err(|_| Error::InvalidHandle)?;

        let id_cert = {
            if let Some(path) = matches.value_of("idcert") {
                let bytes = Self::read_file_arg(path)?;
                let id_cert = IdCert::decode(bytes).map_err(|_| Error::InvalidChildIdCert)?;
                Some(id_cert)
            } else {
                None
            }
        };
        let resources = Self::parse_resource_args(matches)?;

        let update = UpdateChildRequest::new(id_cert, resources);

        let command = Command::CertAuth(CaCommand::ChildUpdate(my_ca, child, update));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_children_info(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let child = matches.value_of("child").unwrap();
        let child = Handle::from_str(child).map_err(|_| Error::InvalidHandle)?;

        let command = Command::CertAuth(CaCommand::ChildInfo(my_ca, child));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_children_response(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let child = matches.value_of("child").unwrap();
        let child = Handle::from_str(child).map_err(|_| Error::InvalidHandle)?;

        let command = Command::CertAuth(CaCommand::ParentResponse(my_ca, child));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_children_remove(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let child = matches.value_of("child").unwrap();
        let child = Handle::from_str(child).map_err(|_| Error::InvalidHandle)?;

        let command = Command::CertAuth(CaCommand::ChildDelete(my_ca, child));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_children(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("add") {
            Self::parse_matches_cas_children_add(m)
        } else if let Some(m) = matches.subcommand_matches("response") {
            Self::parse_matches_cas_children_response(m)
        } else if let Some(m) = matches.subcommand_matches("info") {
            Self::parse_matches_cas_children_info(m)
        } else if let Some(m) = matches.subcommand_matches("update") {
            Self::parse_matches_cas_children_update(m)
        } else if let Some(m) = matches.subcommand_matches("remove") {
            Self::parse_matches_cas_children_remove(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_parents_request(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::ChildRequest(my_ca));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_parents_add(matches: &ArgMatches) -> Result<Options, Error> {
        let path = matches.value_of("response").unwrap();
        let bytes = Self::read_file_arg(path)?;
        let response = rfc8183::ParentResponse::validate(bytes.as_ref())?;

        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let parent = matches.value_of("parent").unwrap();
        let parent = Handle::from_str(parent).map_err(|_| Error::InvalidHandle)?;
        let contact = ParentCaContact::for_rfc6492(response);
        let parent_req = ParentCaReq::new(parent, contact);

        let command = Command::CertAuth(CaCommand::AddParent(my_ca, parent_req));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_parents_info(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;
        let parent = matches.value_of("parent").unwrap();
        let parent = Handle::from_str(parent).map_err(|_| Error::InvalidHandle)?;

        let command = Command::CertAuth(CaCommand::MyParentCaContact(my_ca, parent));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_parents_statuses(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::ParentStatuses(my_ca));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_parents_remove(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;
        let parent = matches.value_of("parent").unwrap();
        let parent = Handle::from_str(parent).map_err(|_| Error::InvalidHandle)?;

        let command = Command::CertAuth(CaCommand::RemoveParent(my_ca, parent));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_parents(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("request") {
            Self::parse_matches_cas_parents_request(m)
        } else if let Some(m) = matches.subcommand_matches("add") {
            Self::parse_matches_cas_parents_add(m)
        } else if let Some(m) = matches.subcommand_matches("contact") {
            Self::parse_matches_cas_parents_info(m)
        } else if let Some(m) = matches.subcommand_matches("statuses") {
            Self::parse_matches_cas_parents_statuses(m)
        } else if let Some(m) = matches.subcommand_matches("remove") {
            Self::parse_matches_cas_parents_remove(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_keyroll_init(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::KeyRollInit(my_ca));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_keyroll_activate(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::KeyRollActivate(my_ca));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_keyroll(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("init") {
            Self::parse_matches_cas_keyroll_init(m)
        } else if let Some(m) = matches.subcommand_matches("activate") {
            Self::parse_matches_cas_keyroll_activate(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_routes_list(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::RouteAuthorizationsList(my_ca));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_routes_update(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let updates = if let Some(path) = matches.value_of("delta") {
            if matches.is_present("add") || matches.is_present("remove") {
                return Err(Error::general("Cannot use --add or --remove if --delta is specified"));
            }

            let bytes = Self::read_file_arg(path)?;
            let updates_str = unsafe { from_utf8_unchecked(&bytes) };
            RoaDefinitionUpdates::from_str(updates_str)?
        } else {
            let mut added = vec![];
            let mut removed = vec![];

            if let Some(add) = matches.values_of("add") {
                for roa_str in add {
                    let roa: RoaDefinition = RoaDefinition::from_str(roa_str)?;
                    added.push(roa);
                }
            }

            if let Some(remove) = matches.values_of("remove") {
                for roa_str in remove {
                    let roa: RoaDefinition = RoaDefinition::from_str(roa_str)?;
                    removed.push(roa);
                }
            }

            if added.is_empty() && removed.is_empty() {
                return Err(Error::general(
                    "You MUST specify either --delta, or --add and/or --remove",
                ));
            }

            RoaDefinitionUpdates::new(added, removed)
        };

        if matches.is_present("dryrun") && matches.is_present("try") {
            return Err(Error::general("You cannot use both --dryrun and --try"));
        }

        let command = if matches.is_present("dryrun") {
            Command::CertAuth(CaCommand::RouteAuthorizationsDryRunUpdate(my_ca, updates))
        } else if matches.is_present("try") {
            Command::CertAuth(CaCommand::RouteAuthorizationsTryUpdate(my_ca, updates))
        } else {
            Command::CertAuth(CaCommand::RouteAuthorizationsUpdate(my_ca, updates))
        };

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_routes_bgp_full(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;
        Ok(Options::make(
            general_args,
            Command::CertAuth(CaCommand::BgpAnalysisFull(my_ca)),
        ))
    }

    fn parse_matches_cas_routes_bgp_suggest(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let v4 = matches.value_of("ipv4").unwrap_or("");
        let v6 = matches.value_of("ipv6").unwrap_or("");

        let resources = ResourceSet::from_strs("", v4, v6)
            .map_err(|e| Error::GeneralArgumentError(format!("Could not parse IP resources: {}", e)))?;

        let resources = if resources.is_empty() { None } else { Some(resources) };

        Ok(Options::make(
            general_args,
            Command::CertAuth(CaCommand::BgpAnalysisSuggest(my_ca, resources)),
        ))
    }

    fn parse_matches_cas_routes_bgp(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("analyze") {
            Self::parse_matches_cas_routes_bgp_full(m)
        } else if let Some(m) = matches.subcommand_matches("suggest") {
            Self::parse_matches_cas_routes_bgp_suggest(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_routes(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("list") {
            Self::parse_matches_cas_routes_list(m)
        } else if let Some(m) = matches.subcommand_matches("update") {
            Self::parse_matches_cas_routes_update(m)
        } else if let Some(m) = matches.subcommand_matches("bgp") {
            Self::parse_matches_cas_routes_bgp(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_repo_request(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::RepoPublisherRequest(my_ca));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_repo_details(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::RepoDetails(my_ca));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_repo_status(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let command = Command::CertAuth(CaCommand::RepoStatus(my_ca));

        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_repo_configure(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let my_ca = Self::parse_my_ca(matches)?;

        let path = matches.value_of("response").unwrap();
        let bytes = Self::read_file_arg(path)?;
        let response = rfc8183::RepositoryResponse::validate(bytes.as_ref())?;

        let repo_contact = RepositoryContact::new(response);
        let command = Command::CertAuth(CaCommand::RepoUpdate(my_ca, repo_contact));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_repo(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("request") {
            Self::parse_matches_cas_repo_request(m)
        } else if let Some(m) = matches.subcommand_matches("show") {
            Self::parse_matches_cas_repo_details(m)
        } else if let Some(m) = matches.subcommand_matches("status") {
            Self::parse_matches_cas_repo_status(m)
        } else if let Some(m) = matches.subcommand_matches("configure") {
            Self::parse_matches_cas_repo_configure(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_issues(matches: &ArgMatches) -> Result<Options, Error> {
        let general = GeneralArgs::from_matches(matches)?;
        let command = if let Ok(ca) = Self::parse_my_ca(matches) {
            Command::CertAuth(CaCommand::Issues(Some(ca)))
        } else {
            Command::CertAuth(CaCommand::Issues(None))
        };
        Ok(Options::make(general, command))
    }

    fn parse_matches_cas_rta_list(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let ca = Self::parse_my_ca(matches)?;
        let command = Command::CertAuth(CaCommand::RtaList(ca));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_rta_show(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let ca = Self::parse_my_ca(matches)?;
        let name = matches.value_of("name").unwrap().to_string();

        let out_file = matches.value_of("out").unwrap();
        let out_file = PathBuf::from_str(out_file)
            .map_err(|_| Error::GeneralArgumentError(format!("Invalid filename: {}", out_file)))?;

        file::save(&[], &out_file).map_err(|e| {
            Error::GeneralArgumentError(format!(
                "Cannot save to file: {}, error: {}",
                out_file.to_string_lossy(),
                e
            ))
        })?;

        let command = Command::CertAuth(CaCommand::RtaShow(ca, name, Some(out_file)));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_rta_sign(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let ca = Self::parse_my_ca(matches)?;

        let days = matches.value_of("days").unwrap();
        let days =
            i64::from_str(days).map_err(|e| Error::GeneralArgumentError(format!("Invalid number of days: {}", e)))?;

        let in_file = matches.value_of("in").unwrap();
        let in_file = PathBuf::from_str(in_file)
            .map_err(|_| Error::GeneralArgumentError(format!("Invalid filename: {}", in_file)))?;

        let content = file::read(&in_file).map_err(|e| {
            Error::GeneralArgumentError(format!(
                "Can't read file '{}', error: {}",
                in_file.to_string_lossy().to_string(),
                e,
            ))
        })?;

        let name = matches.value_of("name").unwrap().to_string();

        let validity = SignSupport::sign_validity_days(days);

        let resources = Self::parse_resource_args(matches)?
            .ok_or_else(|| Error::general("You must specify at least one of --ipv4, --ipv6 or --asn"))?;

        let keys = if let Some(keys) = matches.values_of("keys") {
            let mut res = vec![];
            for key_str in keys {
                let ki = KeyIdentifier::from_str(key_str).map_err(|_| Error::general("Invalid key identifier"))?;
                res.push(ki)
            }
            res
        } else {
            vec![]
        };

        let request = RtaContentRequest::new(resources, validity, keys, content);
        let command = Command::CertAuth(CaCommand::RtaSign(ca, name, request));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_rta_multi_sign(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let ca = Self::parse_my_ca(matches)?;
        let name = matches.value_of("name").unwrap().to_string();

        let in_file = matches.value_of("in").unwrap();
        let in_file = PathBuf::from_str(in_file)
            .map_err(|_| Error::GeneralArgumentError(format!("Invalid filename: {}", in_file)))?;

        let content = file::read(&in_file).map_err(|e| {
            Error::GeneralArgumentError(format!(
                "Can't read file '{}', error: {}",
                in_file.to_string_lossy().to_string(),
                e,
            ))
        })?;

        let rta = ResourceTaggedAttestation::new(content);

        let command = Command::CertAuth(CaCommand::RtaMultiCoSign(ca, name, rta));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_rta_multi_prep(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let ca = Self::parse_my_ca(matches)?;

        let name = matches.value_of("name").unwrap().to_string();
        let resources = Self::parse_resource_args(matches)?
            .ok_or_else(|| Error::general("You must specify at least one of --ipv4, --ipv6 or --asn"))?;

        let days = matches.value_of("days").unwrap();
        let days =
            i64::from_str(days).map_err(|e| Error::GeneralArgumentError(format!("Invalid number of days: {}", e)))?;
        let validity = SignSupport::sign_validity_days(days);

        let request = RtaPrepareRequest::new(resources, validity);

        let command = Command::CertAuth(CaCommand::RtaMultiPrep(ca, name, request));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_cas_rta_multi(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("prep") {
            Self::parse_matches_cas_rta_multi_prep(m)
        } else if let Some(m) = matches.subcommand_matches("cosign") {
            Self::parse_matches_cas_rta_multi_sign(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_cas_rta(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("list") {
            Self::parse_matches_cas_rta_list(m)
        } else if let Some(m) = matches.subcommand_matches("show") {
            Self::parse_matches_cas_rta_show(m)
        } else if let Some(m) = matches.subcommand_matches("sign") {
            Self::parse_matches_cas_rta_sign(m)
        } else if let Some(m) = matches.subcommand_matches("multi") {
            Self::parse_matches_cas_rta_multi(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_bulk(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("publish") {
            let general_args = GeneralArgs::from_matches(m)?;
            let command = Command::Bulk(BulkCaCommand::Publish);
            Ok(Options::make(general_args, command))
        } else if let Some(m) = matches.subcommand_matches("refresh") {
            let general_args = GeneralArgs::from_matches(m)?;
            let command = Command::Bulk(BulkCaCommand::Refresh);
            Ok(Options::make(general_args, command))
        } else if let Some(m) = matches.subcommand_matches("sync") {
            let general_args = GeneralArgs::from_matches(m)?;
            let command = Command::Bulk(BulkCaCommand::Sync);
            Ok(Options::make(general_args, command))
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_health(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let command = Command::Health;
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_info(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let command = Command::Info;
        Ok(Options::make(general_args, command))
    }

    fn parse_publisher_arg(matches: &ArgMatches) -> Result<PublisherHandle, Error> {
        let publisher_str = matches.value_of("publisher").unwrap();
        PublisherHandle::from_str(publisher_str).map_err(|_| Error::InvalidHandle)
    }

    fn parse_matches_publishers_list(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let command = Command::PubServer(PubServerCommand::PublisherList);
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publishers_stale(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let seconds = i64::from_str(matches.value_of("seconds").unwrap()).map_err(|_| Error::InvalidSeconds)?;
        let command = Command::PubServer(PubServerCommand::StalePublishers(seconds));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publishers_add(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;

        let path = matches.value_of("request").unwrap();
        let path = PathBuf::from(path);
        let bytes = file::read(&path)?;
        let mut req = rfc8183::PublisherRequest::validate(bytes.as_ref())?;

        if let Some(publisher_str) = matches.value_of("publisher") {
            let publisher = PublisherHandle::from_str(publisher_str).map_err(|_| Error::InvalidHandle)?;
            let (tag, _, cert) = req.unpack();
            req = rfc8183::PublisherRequest::new(tag, publisher, cert);
        }

        let command = Command::PubServer(PubServerCommand::AddPublisher(req));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publishers_remove(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let publisher = Self::parse_publisher_arg(matches)?;
        let command = Command::PubServer(PubServerCommand::RemovePublisher(publisher));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publishers_show(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let publisher = Self::parse_publisher_arg(matches)?;
        let command = Command::PubServer(PubServerCommand::ShowPublisher(publisher));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publishers_repo_response(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let publisher = Self::parse_publisher_arg(matches)?;
        let command = Command::PubServer(PubServerCommand::RepositoryResponse(publisher));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publication_server_stats(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let command = Command::PubServer(PubServerCommand::RepositoryStats);
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publication_server_init(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;

        let rsync_str = matches.value_of("rsync").unwrap();
        let rrdp_str = matches.value_of("rrdp").unwrap();

        if !rsync_str.ends_with('/') {
            return Err(Error::general("rsync base URI must end with '/'"));
        }

        if !rrdp_str.ends_with('/') {
            return Err(Error::general("RRDP base URI must end with '/'"));
        }

        let rsync = uri::Rsync::from_str(rsync_str)
            .map_err(|e| Error::GeneralArgumentError(format!("Invalid rsync URI: {}", e)))?;

        let rrdp = uri::Https::from_str(rrdp_str)
            .map_err(|e| Error::GeneralArgumentError(format!("Invalid RRDP URI: {}", e)))?;

        let uris = PublicationServerUris::new(rrdp, rsync);

        let command = Command::PubServer(PubServerCommand::RepositoryInit(uris));
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publication_server_clear(matches: &ArgMatches) -> Result<Options, Error> {
        let general_args = GeneralArgs::from_matches(matches)?;
        let command = Command::PubServer(PubServerCommand::RepositoryClear);
        Ok(Options::make(general_args, command))
    }

    fn parse_matches_publication_server(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("stats") {
            Self::parse_matches_publication_server_stats(m)
        } else if let Some(m) = matches.subcommand_matches("init") {
            Self::parse_matches_publication_server_init(m)
        } else if let Some(m) = matches.subcommand_matches("clear") {
            Self::parse_matches_publication_server_clear(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_publishers(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("list") {
            Self::parse_matches_publishers_list(m)
        } else if let Some(m) = matches.subcommand_matches("stale") {
            Self::parse_matches_publishers_stale(m)
        } else if let Some(m) = matches.subcommand_matches("add") {
            Self::parse_matches_publishers_add(m)
        } else if let Some(m) = matches.subcommand_matches("remove") {
            Self::parse_matches_publishers_remove(m)
        } else if let Some(m) = matches.subcommand_matches("show") {
            Self::parse_matches_publishers_show(m)
        } else if let Some(m) = matches.subcommand_matches("response") {
            Self::parse_matches_publishers_repo_response(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches_pubserver(matches: &ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("publishers") {
            Self::parse_matches_publishers(m)
        } else if let Some(m) = matches.subcommand_matches("server") {
            Self::parse_matches_publication_server(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    fn parse_matches(matches: ArgMatches) -> Result<Options, Error> {
        if let Some(m) = matches.subcommand_matches("config") {
            Self::parse_matches_config(m)
        } else if let Some(m) = matches.subcommand_matches("list") {
            Self::parse_matches_cas_list(m)
        } else if let Some(m) = matches.subcommand_matches("add") {
            Self::parse_matches_cas_add(m)
        } else if let Some(m) = matches.subcommand_matches("delete") {
            Self::parse_matches_cas_delete(m)
        } else if let Some(m) = matches.subcommand_matches("show") {
            Self::parse_matches_cas_show(m)
        } else if let Some(m) = matches.subcommand_matches("history") {
            Self::parse_matches_cas_history(m)
        } else if let Some(m) = matches.subcommand_matches("children") {
            Self::parse_matches_cas_children(m)
        } else if let Some(m) = matches.subcommand_matches("parents") {
            Self::parse_matches_cas_parents(m)
        } else if let Some(m) = matches.subcommand_matches("keyroll") {
            Self::parse_matches_cas_keyroll(m)
        } else if let Some(m) = matches.subcommand_matches("roas") {
            Self::parse_matches_cas_routes(m)
        } else if let Some(m) = matches.subcommand_matches("repo") {
            Self::parse_matches_cas_repo(m)
        } else if let Some(m) = matches.subcommand_matches("issues") {
            Self::parse_matches_cas_issues(m)
        } else if let Some(m) = matches.subcommand_matches("rta") {
            Self::parse_matches_cas_rta(m)
        } else if let Some(m) = matches.subcommand_matches("bulk") {
            Self::parse_matches_bulk(m)
        } else if let Some(m) = matches.subcommand_matches("health") {
            Self::parse_matches_health(m)
        } else if let Some(m) = matches.subcommand_matches("info") {
            Self::parse_matches_info(m)
        } else if let Some(m) = matches.subcommand_matches("pubserver") {
            Self::parse_matches_pubserver(m)
        } else {
            Err(Error::UnrecognizedSubCommand)
        }
    }

    pub fn from_args() -> Result<Options, Error> {
        let matches = Self::make_matches();
        Self::parse_matches(matches)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum Command {
    NotSet,
    Health,
    Info,
    Bulk(BulkCaCommand),
    CertAuth(CaCommand),
    PubServer(PubServerCommand),
    Init(KrillInitDetails),
    #[cfg(feature = "multi-user")]
    User(KrillUserDetails),
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum CaCommand {
    Init(CertAuthInit), // Initialize a CA
    UpdateId(Handle),   // Update CA id
    Delete(Handle),     // Delete the CA -> let it withdraw and request revocation as well

    // Publishing
    RepoPublisherRequest(Handle), // Get the RFC8183 publisher request
    RepoDetails(Handle),
    RepoUpdate(Handle, RepositoryContact),
    RepoStatus(Handle),

    // Parents (to this CA)
    ChildRequest(Handle), // Get the RFC8183 child request
    AddParent(Handle, ParentCaReq),
    MyParentCaContact(Handle, ParentHandle),
    ParentStatuses(Handle),
    RemoveParent(Handle, ParentHandle),

    // Children
    ParentResponse(Handle, ChildHandle), // Get an RFC8183 parent response for a child
    ChildInfo(Handle, ChildHandle),
    ChildAdd(Handle, AddChildRequest),
    ChildUpdate(Handle, ChildHandle, UpdateChildRequest),
    ChildDelete(Handle, ChildHandle),

    // Key Management
    KeyRollInit(Handle),
    KeyRollActivate(Handle),

    // Authorizations
    RouteAuthorizationsList(Handle),
    RouteAuthorizationsUpdate(Handle, RoaDefinitionUpdates),
    RouteAuthorizationsTryUpdate(Handle, RoaDefinitionUpdates),
    RouteAuthorizationsDryRunUpdate(Handle, RoaDefinitionUpdates),
    BgpAnalysisFull(Handle),
    BgpAnalysisSuggest(Handle, Option<ResourceSet>),

    // Show details for this CA
    Show(Handle),
    ShowHistoryCommands(Handle, HistoryOptions),
    ShowHistoryDetails(Handle, String),
    Issues(Option<Handle>),

    // RTA
    RtaList(Handle),
    RtaShow(Handle, RtaName, Option<PathBuf>),
    RtaSign(Handle, RtaName, RtaContentRequest),
    RtaMultiPrep(Handle, RtaName, RtaPrepareRequest),
    RtaMultiCoSign(Handle, RtaName, ResourceTaggedAttestation),

    // List all CAs
    List,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HistoryOptions {
    pub offset: u64,
    pub rows: u64,
    pub after: Option<Time>,
    pub before: Option<Time>,
}

impl Default for HistoryOptions {
    fn default() -> Self {
        HistoryOptions {
            offset: 0,
            rows: 100,
            after: None,
            before: None,
        }
    }
}

impl HistoryOptions {
    pub fn url_path_parameters(&self) -> String {
        if let Some(before) = self.before {
            let after = self.after.map(|t| t.timestamp()).unwrap_or_else(|| 0);
            format!("{}/{}/{}/{}", self.rows, self.offset, after, before.timestamp())
        } else if let Some(after) = self.after {
            format!("{}/{}/{}", self.rows, self.offset, after.timestamp())
        } else if self.offset != 0 {
            format!("{}/{}", self.rows, self.offset)
        } else if self.rows != 100 {
            format!("{}", self.rows)
        } else {
            "".to_string()
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BulkCaCommand {
    Refresh,
    Publish,
    Sync,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KrillInitDetails {
    data_dir: Option<String>,
    log_file: Option<String>,
    multi_user: bool,
}

impl KrillInitDetails {
    pub fn multi_user_dflt() -> Self {
        KrillInitDetails {
            data_dir: None,
            log_file: None,
            multi_user: true,
        }
    }

    pub fn with_data_dir(&mut self, data_dir: &str) {
        self.data_dir = Some(data_dir.to_string())
    }

    pub fn with_log_file(&mut self, log_file: &str) {
        self.log_file = Some(log_file.to_string())
    }

    pub fn data_dir(&self) -> Option<&String> {
        self.data_dir.as_ref()
    }

    pub fn log_file(&self) -> Option<&String> {
        self.log_file.as_ref()
    }

    pub fn multi_user(&self) -> bool {
        self.multi_user
    }
}

impl Default for KrillInitDetails {
    fn default() -> Self {
        KrillInitDetails {
            data_dir: None,
            log_file: None,
            multi_user: false,
        }
    }
}

#[cfg(feature = "multi-user")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KrillUserDetails {
    id: String,
    attrs: HashMap<String, String>,
}

#[cfg(feature = "multi-user")]
impl KrillUserDetails {
    pub fn with_id(&mut self, id: String) {
        self.id = id;
    }
    pub fn with_attr(&mut self, attr: String, value: String) {
        self.attrs.insert(attr, value);
    }
    pub fn id(&self) -> &String {
        &self.id
    }

    pub fn attrs(&self) -> HashMap<String, String> {
        self.attrs.clone()
    }
}

#[cfg(feature = "multi-user")]
impl Default for KrillUserDetails {
    fn default() -> Self {
        KrillUserDetails {
            id: String::new(),
            attrs: HashMap::new(),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum PubServerCommand {
    AddPublisher(rfc8183::PublisherRequest),
    ShowPublisher(PublisherHandle),
    RemovePublisher(PublisherHandle),
    RepositoryResponse(PublisherHandle),
    StalePublishers(i64),
    PublisherList,
    RepositoryStats,
    RepositoryInit(PublicationServerUris),
    RepositoryClear,
}

//------------ Error ---------------------------------------------------------

#[derive(Debug)]
pub enum Error {
    UriError(uri::Error),
    IoError(KrillIoError),
    ReportError(ReportError),
    Rfc8183(rfc8183::Error),
    ResSetErr(ResourceSetError),
    InvalidRouteDelta(AuthorizationFmtError),
    InvalidHandle,
    InvalidSeconds,
    MissingArgWithEnv(String, String),
    MissingResources,
    InvalidChildIdCert,
    UnrecognizedSubCommand,
    GeneralArgumentError(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::UriError(e) => e.fmt(f),
            Error::IoError(e) => e.fmt(f),
            Error::ReportError(e) => e.fmt(f),
            Error::Rfc8183(e) => write!(f, "Invalid RFC8183 XML: {}", e),
            Error::ResSetErr(e) => write!(f, "Invalid resources requested: {}", e),
            Error::InvalidRouteDelta(e) => e.fmt(f),
            Error::InvalidHandle => write!(
                f,
                "The publisher handle may only contain -_A-Za-z0-9, (\\ /) see issue #83"
            ),
            Error::InvalidSeconds => write!(f, "Use a number of 0 or more seconds"),
            Error::MissingArgWithEnv(arg, var) => write!(
                f,
                "Missing argument: --{}, alternatively you may use env var: {}",
                arg, var
            ),
            Error::MissingResources => write!(f, "You must specify resources when adding a CA (--asn, --ipv4, --ipv6)"),
            Error::InvalidChildIdCert => write!(f, "Invalid ID cert for child"),
            Error::UnrecognizedSubCommand => write!(f, "Unrecognized sub-command. Use 'help'"),
            Error::GeneralArgumentError(s) => s.fmt(f),
        }
    }
}

impl Error {
    fn missing_arg_with_env(arg: &str, env_var: &str) -> Self {
        Error::MissingArgWithEnv(arg.to_string(), env_var.to_string())
    }

    fn general(msg: &str) -> Self {
        Error::GeneralArgumentError(msg.to_string())
    }
}

impl From<rfc8183::Error> for Error {
    fn from(e: rfc8183::Error) -> Self {
        Error::Rfc8183(e)
    }
}

impl From<uri::Error> for Error {
    fn from(e: uri::Error) -> Self {
        Error::UriError(e)
    }
}

impl From<KrillIoError> for Error {
    fn from(e: KrillIoError) -> Self {
        Error::IoError(e)
    }
}

impl From<ReportError> for Error {
    fn from(e: ReportError) -> Self {
        Error::ReportError(e)
    }
}

impl From<ResourceSetError> for Error {
    fn from(e: ResourceSetError) -> Self {
        Error::ResSetErr(e)
    }
}

impl From<AuthorizationFmtError> for Error {
    fn from(e: AuthorizationFmtError) -> Self {
        Error::InvalidRouteDelta(e)
    }
}