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
use clap::{builder::PossibleValue, Args, Subcommand, ValueEnum};
use kanidm_proto::internal::ImageType;
use std::fmt;

#[derive(Debug, Args)]
pub struct Named {
    pub name: String,
    #[clap(flatten)]
    pub copt: CommonOpt,
}

#[derive(Debug, Args)]
pub struct DebugOpt {
    /// Enable debugging of the kanidm tool
    #[clap(short, long, env = "KANIDM_DEBUG")]
    pub debug: bool,
}

#[derive(Debug, Clone, Copy)]
/// The CLI output mode, either text or json, falls back to text if you ask for something other than text/json
pub enum OutputMode {
    Text,
    Json,
}

impl std::str::FromStr for OutputMode {
    type Err = String;
    fn from_str(s: &str) -> Result<OutputMode, std::string::String> {
        match s.to_lowercase().as_str() {
            "text" => Ok(OutputMode::Text),
            "json" => Ok(OutputMode::Json),
            _ => Ok(OutputMode::Text),
        }
    }
}

impl OutputMode {
    pub fn print_message<T>(self, input: T)
    where
        T: serde::Serialize + fmt::Debug + fmt::Display,
    {
        match self {
            OutputMode::Json => {
                println!(
                    "{}",
                    serde_json::to_string(&input).unwrap_or(format!("{:?}", input))
                );
            }
            OutputMode::Text => {
                println!("{}", input);
            }
        }
    }
}

#[derive(Debug, Args, Clone)]
pub struct CommonOpt {
    /// Enable debugging of the kanidm tool
    #[clap(short, long, env = "KANIDM_DEBUG")]
    pub debug: bool,
    /// Select the instance name you wish to connect to
    #[clap(short = 'I', long = "instance", env = "KANIDM_INSTANCE",
    value_parser = clap::builder::NonEmptyStringValueParser::new())]
    pub instance: Option<String>,
    /// The URL of the kanidm instance
    #[clap(short = 'H', long = "url", env = "KANIDM_URL",
    value_parser = clap::builder::NonEmptyStringValueParser::new())]
    pub addr: Option<String>,
    /// User which will initiate requests
    #[clap(
        short = 'D',
        long = "name",
        env = "KANIDM_NAME",
        value_parser = clap::builder::NonEmptyStringValueParser::new()
    )]
    pub username: Option<String>,
    /// Path to a CA certificate file
    #[clap(value_parser, short = 'C', long = "ca", env = "KANIDM_CA_PATH")]
    pub ca_path: Option<PathBuf>,
    /// Log format (still in very early development)
    #[clap(short, long = "output", env = "KANIDM_OUTPUT", default_value = "text")]
    output_mode: OutputMode,
    /// Skip hostname verification
    #[clap(
        long = "skip-hostname-verification",
        env = "KANIDM_SKIP_HOSTNAME_VERIFICATION",
        default_value_t = false
    )]
    skip_hostname_verification: bool,
    /// Path to a file to cache tokens in, defaults to ~/.cache/kanidm_tokens
    #[clap(short, long, env = "KANIDM_TOKEN_CACHE_PATH", hide = true, default_value = None,
    value_parser = clap::builder::NonEmptyStringValueParser::new())]
    token_cache_path: Option<String>,
}

#[derive(Debug, Args)]
pub struct GroupNamedMembers {
    name: String,
    #[clap(required = true, num_args(1..))]
    members: Vec<String>,
    #[clap(flatten)]
    copt: CommonOpt,
}

#[derive(Debug, Args)]
pub struct GroupPosixOpt {
    name: String,
    #[clap(long)]
    gidnumber: Option<u32>,
    #[clap(flatten)]
    copt: CommonOpt,
}

#[derive(Debug, Subcommand)]
pub enum GroupPosix {
    /// Show details of a specific posix group
    #[clap(name = "show")]
    Show(Named),
    /// Setup posix group properties, or alter them
    #[clap(name = "set")]
    Set(GroupPosixOpt),
    /// Reset the gidnumber of this group to the generated default
    #[clap(name = "reset-gidnumber")]
    ResetGidnumber {
        group_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum AccountPolicyCredentialType {
    Any,
    Mfa,
    Passkey,
    AttestedPasskey,
}

impl AccountPolicyCredentialType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Any => "any",
            Self::Mfa => "mfa",
            Self::Passkey => "passkey",
            Self::AttestedPasskey => "attested_passkey",
        }
    }
}

impl ValueEnum for AccountPolicyCredentialType {
    fn value_variants<'a>() -> &'a [Self] {
        &[Self::Any, Self::Mfa, Self::Passkey, Self::AttestedPasskey]
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        Some(match self {
            Self::Any => PossibleValue::new("any"),
            Self::Mfa => PossibleValue::new("mfa"),
            Self::Passkey => PossibleValue::new("passkey"),
            Self::AttestedPasskey => PossibleValue::new("attested_passkey"),
        })
    }
}

#[derive(Debug, Subcommand)]
pub enum GroupAccountPolicyOpt {
    /// Enable account policy for this group
    #[clap(name = "enable")]
    Enable {
        name: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Set the maximum time for session expiry in seconds.
    #[clap(name = "auth-expiry")]
    AuthSessionExpiry {
        name: String,
        expiry: u32,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Set the minimum credential class that members may authenticate with. Valid values
    /// in order of weakest to strongest are: "any" "mfa" "passkey" "attested_passkey".
    #[clap(name = "credential-type-minimum")]
    CredentialTypeMinimum {
        name: String,
        #[clap(value_enum)]
        value: AccountPolicyCredentialType,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Set the minimum character length of passwords for accounts.
    #[clap(name = "password-minimum-length")]
    PasswordMinimumLength {
        name: String,
        length: u32,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Set the maximum time for privilege session expiry in seconds.
    #[clap(name = "privilege-expiry")]
    PrivilegedSessionExpiry {
        name: String,
        expiry: u32,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// The WebAuthn attestation CA list that should be enforced
    /// on members of this group. Prevents use of passkeys that are
    /// not in this list. To create this list, use `fido-mds-tool`
    /// from <https://crates.io/crates/fido-mds-tool>
    #[clap(name = "webauthn-attestation-ca-list")]
    WebauthnAttestationCaList {
        name: String,
        attestation_ca_list_json: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Sets the maximum number of entries that may be returned in a
    /// search operation.
    #[clap(name = "limit-search-max-results")]
    LimitSearchMaxResults {
        name: String,
        maximum: u32,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Sets the maximum number of entries that are examined during
    /// a partially indexed search. This does not affect fully
    /// indexed searches. If in doubt, set this to 1.5x limit-search-max-results
    #[clap(name = "limit-search-max-filter-test")]
    LimitSearchMaxFilterTest {
        name: String,
        maximum: u32,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Sets whether during login the primary password can be used
    /// as a fallback if no posix password has been defined
    #[clap(name = "allow-primary-cred-fallback")]
    AllowPrimaryCredFallback {
        name: String,
        #[clap(name = "allow", action = clap::ArgAction::Set)]
        allow: bool,
        #[clap(flatten)]
        copt: CommonOpt,
    },
}

#[derive(Debug, Subcommand)]
pub enum GroupOpt {
    /// List all groups
    #[clap(name = "list")]
    List(CommonOpt),
    /// View a specific group
    #[clap(name = "get")]
    Get(Named),
    /// Search a group by name
    #[clap(name = "search")]
    Search {
        /// The name of the group
        name: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Create a new group
    #[clap(name = "create")]
    Create {
        /// The name of the group
        name: String,
        /// Optional name/spn of a group that have entry manager rights over this group.
        #[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
        entry_managed_by: Option<String>,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Delete a group
    #[clap(name = "delete")]
    Delete(Named),
    /// List the members of a group
    #[clap(name = "list-members")]
    ListMembers(Named),
    /// Set the exact list of members that this group should contain, removing any not listed in the
    /// set operation.
    #[clap(name = "set-members")]
    SetMembers(GroupNamedMembers),
    /// Set the exact list of mail addresses that this group is associated with. The first
    /// mail address in the list is the `primary` and the remainder are aliases. Setting
    /// an empty list will clear the mail attribute.
    #[clap(name = "set-mail")]
    SetMail {
        #[clap(flatten)]
        copt: CommonOpt,
        name: String,
        mail: Vec<String>,
    },
    /// Set a new entry-managed-by for this group.
    #[clap(name = "set-entry-manager")]
    SetEntryManagedBy {
        /// The name of the group
        name: String,
        /// Optional name/spn of a group that have entry manager rights over this group.
        entry_managed_by: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Rename an existing group
    #[clap(name = "rename")]
    Rename {
        /// The name of the group
        name: String,
        /// The new name of the group
        new_name: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Delete all members of a group.
    #[clap(name = "purge-members")]
    PurgeMembers(Named),
    /// Add new members to a group
    #[clap(name = "add-members")]
    AddMembers(GroupNamedMembers),
    /// Remove the named members from this group
    #[clap(name = "remove-members")]
    RemoveMembers(GroupNamedMembers),
    /// Manage posix extensions for this group allowing groups to be used on unix/linux systems
    #[clap(name = "posix")]
    Posix {
        #[clap(subcommand)]
        commands: GroupPosix,
    },
    /// Manage the policies that apply to members of this group.
    #[clap(name = "account-policy")]
    AccountPolicy {
        #[clap(subcommand)]
        commands: GroupAccountPolicyOpt,
    },
}

#[derive(Clone, Debug, ValueEnum)]
pub enum GraphType {
    Graphviz,
    Mermaid,
    MermaidElk,
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, ValueEnum)]
pub enum ObjectType {
    Group,
    BuiltinGroup,
    ServiceAccount,
    Person,
}

#[derive(Debug, Args)]
pub struct GraphCommonOpt {
    #[arg(value_enum)]
    pub graph_type: GraphType,
    #[clap()]
    pub filter: Vec<ObjectType>,
    #[clap(flatten)]
    pub copt: CommonOpt,
}

#[derive(Debug, Args)]
pub struct AccountCommonOpt {
    #[clap()]
    account_id: String,
}

#[derive(Debug, Args)]
pub struct AccountNamedOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(flatten)]
    copt: CommonOpt,
}

#[derive(Debug, Args)]
pub struct AccountNamedExpireDateTimeOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(flatten)]
    copt: CommonOpt,
    #[clap(name = "datetime", verbatim_doc_comment)]
    /// This accepts multiple options:
    /// - An RFC3339 time of the format "YYYY-MM-DDTHH:MM:SS+TZ", "2020-09-25T11:22:02+10:00"
    /// - One of "any", "clear" or "never" to remove account expiry.
    /// - "epoch" to set the expiry to the UNIX epoch
    /// - "now" to expire immediately (this will affect authentication with Kanidm, but external systems may not be aware of the change until next time it's validated, typically ~15 minutes)
    datetime: String,
}

#[derive(Debug, Args)]
pub struct AccountNamedValidDateTimeOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(flatten)]
    copt: CommonOpt,
    #[clap(name = "datetime")]
    /// An rfc3339 time of the format "YYYY-MM-DDTHH:MM:SS+TZ", "2020-09-25T11:22:02+10:00"
    /// or the word "any", "clear" to remove valid from enforcement.
    datetime: String,
}

#[derive(Debug, Args)]
pub struct AccountNamedTagOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(flatten)]
    copt: CommonOpt,
    #[clap(name = "tag")]
    tag: String,
}

#[derive(Debug, Args)]
pub struct AccountNamedTagPkOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(flatten)]
    copt: CommonOpt,
    #[clap(name = "tag")]
    tag: String,
    #[clap(name = "pubkey")]
    pubkey: String,
}

#[derive(Debug, Args)]
/// Command-line options for account credential use-reset-token
pub struct UseResetTokenOpt {
    #[clap(flatten)]
    copt: CommonOpt,
    #[clap(name = "token")]
    token: String,
}

#[derive(Debug, Args)]
pub struct AccountCreateOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(name = "display-name")]
    display_name: String,
    #[clap(flatten)]
    copt: CommonOpt,
}

#[derive(Debug, Subcommand)]
pub enum AccountCredential {
    /// Show the status of this accounts credentials.
    #[clap(name = "status")]
    Status(AccountNamedOpt),
    /// Interactively update/change the credentials for an account
    #[clap(name = "update")]
    Update(AccountNamedOpt),
    /// Using a reset token, interactively reset credentials for a user
    #[clap(name = "use-reset-token")]
    UseResetToken(UseResetTokenOpt),
    /// Create a reset token that can be given to another person so they can
    /// recover or reset their account credentials.
    #[clap(name = "create-reset-token")]
    CreateResetToken {
        #[clap(flatten)]
        aopts: AccountCommonOpt,
        #[clap(flatten)]
        copt: CommonOpt,
        /// Optionally set how many seconds the reset token should be valid for.
        /// Default: 3600 seconds
        ttl: Option<u32>,
    },
}

/// RADIUS secret management
#[derive(Debug, Subcommand)]
pub enum AccountRadius {
    /// Show the RADIUS secret for a user.
    #[clap(name = "show-secret")]
    Show(AccountNamedOpt),
    /// Generate a randomized RADIUS secret for a user.
    #[clap(name = "generate-secret")]
    Generate(AccountNamedOpt),
    #[clap(name = "delete-secret")]
    /// Remove the configured RADIUS secret for the user.
    DeleteSecret(AccountNamedOpt),
}

#[derive(Debug, Args)]
pub struct AccountPosixOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(long)]
    gidnumber: Option<u32>,
    #[clap(long, value_parser = clap::builder::NonEmptyStringValueParser::new())]
    /// Set the user's login shell
    shell: Option<String>,
    #[clap(flatten)]
    copt: CommonOpt,
}

#[derive(Debug, Subcommand)]
pub enum PersonPosix {
    #[clap(name = "show")]
    Show(AccountNamedOpt),
    #[clap(name = "set")]
    Set(AccountPosixOpt),
    #[clap(name = "set-password")]
    SetPassword(AccountNamedOpt),
    /// Reset the gidnumber of this person to the generated default
    #[clap(name = "reset-gidnumber")]
    ResetGidnumber {
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
}

#[derive(Debug, Subcommand)]
pub enum ServiceAccountPosix {
    #[clap(name = "show")]
    Show(AccountNamedOpt),
    #[clap(name = "set")]
    Set(AccountPosixOpt),
    /// Reset the gidnumber of this service account to the generated default
    #[clap(name = "reset-gidnumber")]
    ResetGidnumber {
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
}

#[derive(Debug, Args)]
pub struct PersonUpdateOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(long, short, help = "Set the legal name for the person.",
    value_parser = clap::builder::NonEmptyStringValueParser::new())]
    legalname: Option<String>,
    #[clap(long, short, help = "Set the account name for the person.",
    value_parser = clap::builder::NonEmptyStringValueParser::new())]
    newname: Option<String>,
    #[clap(long, short = 'i', help = "Set the display name for the person.",
    value_parser = clap::builder::NonEmptyStringValueParser::new())]
    displayname: Option<String>,
    #[clap(
        long,
        short,
        help = "Set the mail address, can be set multiple times for multiple addresses. The first listed mail address is the 'primary'"
    )]
    mail: Option<Vec<String>>,
    #[clap(flatten)]
    copt: CommonOpt,
}

#[derive(Debug, Subcommand)]
pub enum AccountSsh {
    #[clap(name = "list-publickeys")]
    List(AccountNamedOpt),
    #[clap(name = "add-publickey")]
    Add(AccountNamedTagPkOpt),
    #[clap(name = "delete-publickey")]
    Delete(AccountNamedTagOpt),
}

#[derive(Debug, Subcommand)]
pub enum AccountValidity {
    /// Show an accounts validity window
    #[clap(name = "show")]
    Show(AccountNamedOpt),
    /// Set an accounts expiry time
    #[clap(name = "expire-at")]
    ExpireAt(AccountNamedExpireDateTimeOpt),
    /// Set an account valid from time
    #[clap(name = "begin-from")]
    BeginFrom(AccountNamedValidDateTimeOpt),
}

#[derive(Debug, Subcommand)]
pub enum AccountCertificate {
    #[clap(name = "status")]
    Status {
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    #[clap(name = "create")]
    Create {
        account_id: String,
        certificate_path: PathBuf,
        #[clap(flatten)]
        copt: CommonOpt,
    },
}

#[derive(Debug, Subcommand)]
pub enum AccountUserAuthToken {
    /// Show the status of logged in sessions associated to this account.
    #[clap(name = "status")]
    Status(AccountNamedOpt),
    /// Destroy / revoke a session for this account. Access to the
    /// session (user auth token) is NOT required, only the uuid of the session.
    #[clap(name = "destroy")]
    Destroy {
        #[clap(flatten)]
        aopts: AccountCommonOpt,
        #[clap(flatten)]
        copt: CommonOpt,
        /// The UUID of the token to destroy.
        #[clap(name = "session-id")]
        session_id: Uuid,
    },
}

#[derive(Debug, Subcommand)]
pub enum PersonOpt {
    /// Manage the credentials this person uses for authentication
    #[clap(name = "credential")]
    Credential {
        #[clap(subcommand)]
        commands: AccountCredential,
    },
    /// Manage radius access for this person
    #[clap(name = "radius")]
    Radius {
        #[clap(subcommand)]
        commands: AccountRadius,
    },
    /// Manage posix extensions for this person allowing access to unix/linux systems
    #[clap(name = "posix")]
    Posix {
        #[clap(subcommand)]
        commands: PersonPosix,
    },
    /// Manage sessions (user auth tokens) associated to this person.
    #[clap(name = "session")]
    Session {
        #[clap(subcommand)]
        commands: AccountUserAuthToken,
    },
    /// Manage ssh public key's associated to this person
    #[clap(name = "ssh")]
    Ssh {
        #[clap(subcommand)]
        commands: AccountSsh,
    },
    /// List all persons
    #[clap(name = "list")]
    List(CommonOpt),
    /// View a specific person
    #[clap(name = "get")]
    Get(AccountNamedOpt),
    /// Search persons by name
    #[clap(name = "search")]
    Search {
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Update a specific person's attributes
    #[clap(name = "update")]
    Update(PersonUpdateOpt),
    /// Create a new person's account
    #[clap(name = "create")]
    Create(AccountCreateOpt),
    /// Delete a person's account
    #[clap(name = "delete")]
    Delete(AccountNamedOpt),
    /// Manage a person's account validity, such as expiry time (account lock/unlock)
    #[clap(name = "validity")]
    Validity {
        #[clap(subcommand)]
        commands: AccountValidity,
    },
    #[clap(name = "certificate", hide = true)]
    Certificate {
        #[clap(subcommand)]
        commands: AccountCertificate,
    },
}

#[derive(Debug, Subcommand)]
pub enum ServiceAccountCredential {
    /// Show the status of this accounts password
    #[clap(name = "status")]
    Status(AccountNamedOpt),
    /// Reset and generate a new service account password. This password can NOT
    /// be used with the LDAP interface.
    #[clap(name = "generate")]
    GeneratePw(AccountNamedOpt),
}

#[derive(Debug, Subcommand)]
pub enum ServiceAccountApiToken {
    /// Show the status of api tokens associated to this service account.
    #[clap(name = "status")]
    Status(AccountNamedOpt),
    /// Generate a new api token for this service account.
    #[clap(name = "generate")]
    Generate {
        #[clap(flatten)]
        aopts: AccountCommonOpt,
        #[clap(flatten)]
        copt: CommonOpt,
        /// A string describing the token. This is not used to identify the token, it is only
        /// for human description of the tokens purpose.
        #[clap(name = "label")]
        label: String,
        #[clap(name = "expiry")]
        /// An optional rfc3339 time of the format "YYYY-MM-DDTHH:MM:SS+TZ", "2020-09-25T11:22:02+10:00".
        /// After this time the api token will no longer be valid.
        #[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
        expiry: Option<String>,
        #[clap(long = "rw")]
        read_write: bool,
    },
    /// Destroy / revoke an api token from this service account. Access to the
    /// token is NOT required, only the tag/uuid of the token.
    #[clap(name = "destroy")]
    Destroy {
        #[clap(flatten)]
        aopts: AccountCommonOpt,
        #[clap(flatten)]
        copt: CommonOpt,
        /// The UUID of the token to destroy.
        #[clap(name = "token-id")]
        token_id: Uuid,
    },
}

#[derive(Debug, Args)]
pub struct ServiceAccountUpdateOpt {
    #[clap(flatten)]
    aopts: AccountCommonOpt,
    #[clap(long, short, help = "Set the account name for the service account.",
    value_parser = clap::builder::NonEmptyStringValueParser::new())]
    newname: Option<String>,
    #[clap(
        long,
        short = 'i',
        help = "Set the display name for the service account.",
        value_parser = clap::builder::NonEmptyStringValueParser::new()
    )]
    displayname: Option<String>,
    #[clap(
        long,
        short = 'e',
        help = "Set the entry manager for the service account.",
        value_parser = clap::builder::NonEmptyStringValueParser::new()
    )]
    entry_managed_by: Option<String>,
    #[clap(
        long,
        short,
        help = "Set the mail address, can be set multiple times for multiple addresses. The first listed mail address is the 'primary'"
    )]
    mail: Option<Vec<String>>,
    #[clap(flatten)]
    copt: CommonOpt,
}

#[derive(Debug, Subcommand)]
pub enum ServiceAccountOpt {
    /// Manage the generated password of this service account.
    #[clap(name = "credential")]
    Credential {
        #[clap(subcommand)]
        commands: ServiceAccountCredential,
    },
    /// Manage api tokens associated to this service account.
    #[clap(name = "api-token")]
    ApiToken {
        #[clap(subcommand)]
        commands: ServiceAccountApiToken,
    },
    /// Manage posix extensions for this service account allowing access to unix/linux systems
    #[clap(name = "posix")]
    Posix {
        #[clap(subcommand)]
        commands: ServiceAccountPosix,
    },
    /// Manage sessions (user auth tokens) associated to this service account.
    #[clap(name = "session")]
    Session {
        #[clap(subcommand)]
        commands: AccountUserAuthToken,
    },
    /// Manage ssh public key's associated to this person
    #[clap(name = "ssh")]
    Ssh {
        #[clap(subcommand)]
        commands: AccountSsh,
    },
    /// List all service accounts
    #[clap(name = "list")]
    List(CommonOpt),
    /// View a specific service account
    #[clap(name = "get")]
    Get(AccountNamedOpt),
    /// Create a new service account
    #[clap(name = "create")]
    Create {
        #[clap(flatten)]
        aopts: AccountCommonOpt,
        #[clap(name = "display-name")]
        display_name: String,
        #[clap(name = "entry-managed-by")]
        entry_managed_by: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Update a specific service account's attributes
    #[clap(name = "update")]
    Update(ServiceAccountUpdateOpt),
    /// Delete a service account
    #[clap(name = "delete")]
    Delete(AccountNamedOpt),
    /// Manage a service account validity, such as expiry time (account lock/unlock)
    #[clap(name = "validity")]
    Validity {
        #[clap(subcommand)]
        commands: AccountValidity,
    },
    /// (Deprecated - due for removal in v1.1.0-15) - Convert a service account into a person. This is used during the alpha.9
    /// to alpha.10 migration to "fix up" accounts that were not previously marked
    /// as persons.
    #[clap(name = "into-person")]
    IntoPerson(AccountNamedOpt),
}

#[derive(Debug, Subcommand)]
pub enum RecycleOpt {
    #[clap(name = "list")]
    /// List objects that are in the recycle bin
    List(CommonOpt),
    #[clap(name = "get")]
    /// Display an object from the recycle bin
    Get(Named),
    #[clap(name = "revive")]
    /// Revive a recycled object into a live (accessible) state - this is the opposite of "delete"
    Revive(Named),
}

#[derive(Debug, Args)]
pub struct LoginOpt {
    #[clap(flatten)]
    copt: CommonOpt,
    #[clap(short, long, env = "KANIDM_PASSWORD", hide = true,
    value_parser = clap::builder::NonEmptyStringValueParser::new())]
    /// Supply a password to the login option
    password: Option<String>,
}

#[derive(Debug, Args)]
pub struct ReauthOpt {
    #[clap(flatten)]
    copt: CommonOpt,
}

#[derive(Debug, Args)]
pub struct LogoutOpt {
    #[clap(flatten)]
    copt: CommonOpt,
    #[clap(short, long)]
    /// Do not send a logout request to the server - only remove the session token locally.
    local_only: bool,
}

#[derive(Debug, Subcommand)]
pub enum SessionOpt {
    #[clap(name = "list")]
    /// List current active sessions
    List(CommonOpt),
    #[clap(name = "cleanup")]
    /// Remove sessions that have expired or are invalid.
    Cleanup(CommonOpt),
}

#[derive(Debug, Args)]
pub struct FilterOpt {
    #[clap()]
    filter: String,
    #[clap(flatten)]
    commonopts: CommonOpt,
}

#[derive(Debug, Args)]
pub struct CreateOpt {
    #[clap(value_parser)]
    file: PathBuf,
    #[clap(flatten)]
    commonopts: CommonOpt,
}

#[derive(Debug, Args)]
pub struct ModifyOpt {
    #[clap(flatten)]
    commonopts: CommonOpt,
    #[clap()]
    filter: String,
    #[clap(value_parser)]
    file: PathBuf,
}

#[derive(Debug, Subcommand)]
pub enum RawOpt {
    #[clap(name = "search")]
    Search(FilterOpt),
    #[clap(name = "create")]
    Create(CreateOpt),
    #[clap(name = "modify")]
    Modify(ModifyOpt),
    #[clap(name = "delete")]
    Delete(FilterOpt),
}

#[derive(Debug, Subcommand)]
pub enum SelfOpt {
    /// Use the identify user feature
    #[clap(name = "identify-user")]
    IdentifyUser(CommonOpt),
    /// Show the current authenticated user's identity
    Whoami(CommonOpt),
}

#[derive(Debug, Args)]
pub struct Oauth2SetDisplayname {
    #[clap(flatten)]
    nopt: Named,
    #[clap(name = "displayname")]
    displayname: String,
}

#[derive(Debug, Args)]
pub struct Oauth2SetImplicitScopes {
    #[clap(flatten)]
    nopt: Named,
    #[clap(name = "scopes")]
    scopes: Vec<String>,
}

#[derive(Debug, Args)]
pub struct Oauth2CreateScopeMapOpt {
    #[clap(flatten)]
    nopt: Named,
    #[clap(name = "group")]
    group: String,
    #[clap(name = "scopes", required = true)]
    scopes: Vec<String>,
}

#[derive(Debug, Args)]
pub struct Oauth2DeleteScopeMapOpt {
    #[clap(flatten)]
    nopt: Named,
    #[clap(name = "group")]
    group: String,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Oauth2ClaimMapJoin {
    Csv,
    Ssv,
    Array,
}

impl Oauth2ClaimMapJoin {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Csv => "csv",
            Self::Ssv => "ssv",
            Self::Array => "array",
        }
    }
}

impl ValueEnum for Oauth2ClaimMapJoin {
    fn value_variants<'a>() -> &'a [Self] {
        &[Self::Csv, Self::Ssv, Self::Array]
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        Some(match self {
            Self::Csv => PossibleValue::new("csv"),
            Self::Ssv => PossibleValue::new("ssv"),
            Self::Array => PossibleValue::new("array"),
        })
    }
}

#[derive(Debug, Subcommand)]
pub enum Oauth2Opt {
    #[clap(name = "list")]
    /// List all configured oauth2 clients
    List(CommonOpt),
    #[clap(name = "get")]
    /// Display a selected oauth2 client
    Get(Named),
    // #[clap(name = "set")]
    // /// Set options for a selected oauth2 client
    // Set(),
    #[clap(name = "create")]
    /// Create a new oauth2 confidential client that is protected by basic auth.
    CreateBasic {
        #[clap(name = "name")]
        name: String,
        #[clap(name = "displayname")]
        displayname: String,
        #[clap(name = "origin")]
        origin: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    #[clap(name = "create-public")]
    /// Create a new OAuth2 public client that requires PKCE. You should prefer
    /// using confidential client types if possible over public ones.
    ///
    /// Public clients have many limitations and can not access all API's of OAuth2. For
    /// example rfc7662 token introspection requires client authentication.
    CreatePublic {
        #[clap(name = "name")]
        name: String,
        #[clap(name = "displayname")]
        displayname: String,
        #[clap(name = "origin")]
        origin: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    #[clap(name = "update-scope-map", visible_aliases=&["create-scope-map"])]
    /// Update or add a new mapping from a group to scopes that it provides to members
    UpdateScopeMap(Oauth2CreateScopeMapOpt),
    #[clap(name = "delete-scope-map")]
    /// Remove a mapping from groups to scopes
    DeleteScopeMap(Oauth2DeleteScopeMapOpt),

    #[clap(name = "update-sup-scope-map", visible_aliases=&["create-sup-scope-map"])]
    /// Update or add a new mapping from a group to scopes that it provides to members
    UpdateSupScopeMap(Oauth2CreateScopeMapOpt),
    #[clap(name = "delete-sup-scope-map")]
    /// Remove a mapping from groups to scopes
    DeleteSupScopeMap(Oauth2DeleteScopeMapOpt),

    #[clap(name = "update-claim-map", visible_aliases=&["create-claim-map"])]
    /// Update or add a new mapping from a group to custom claims that it provides to members
    UpdateClaimMap {
        #[clap(flatten)]
        copt: CommonOpt,
        name: String,
        claim_name: String,
        group: String,
        values: Vec<String>,
    },
    #[clap(name = "update-claim-map-join")]
    UpdateClaimMapJoin {
        #[clap(flatten)]
        copt: CommonOpt,
        name: String,
        claim_name: String,
        /// The join strategy. Valid values are csv (comma separated value), ssv (space
        /// separated value) and array.
        join: Oauth2ClaimMapJoin,
    },
    #[clap(name = "delete-claim-map")]
    /// Remove a mapping from groups to a custom claim
    DeleteClaimMap {
        #[clap(flatten)]
        copt: CommonOpt,
        name: String,
        claim_name: String,
        group: String,
    },

    #[clap(name = "reset-secrets")]
    /// Reset the secrets associated to this client
    ResetSecrets(Named),
    #[clap(name = "show-basic-secret")]
    /// Show the associated basic secret for this client
    ShowBasicSecret(Named),
    #[clap(name = "delete")]
    /// Delete a oauth2 client
    Delete(Named),
    /// Set a new displayname for a client
    #[clap(name = "set-displayname")]
    SetDisplayname(Oauth2SetDisplayname),
    /// Set a new name for this client. You may need to update
    /// your integrated applications after this so that they continue to
    /// function correctly.
    #[clap(name = "set-name")]
    SetName {
        #[clap(flatten)]
        nopt: Named,
        #[clap(name = "newname")]
        name: String,
    },

    /// The landing URL is the default origin of the OAuth2 client. Additionally, this landing
    /// URL is the target when Kanidm redirects the user from the apps listing page.
    #[clap(name = "set-landing-url")]
    SetLandingUrl {
        #[clap(flatten)]
        nopt: Named,
        #[clap(name = "landing-url")]
        url: Url,
    },
    /// The image presented on the Kanidm Apps Listing page for an OAuth2 resource server.
    #[clap(name = "set-image")]
    SetImage {
        #[clap(flatten)]
        nopt: Named,
        #[clap(name = "file-path")]
        /// A local file path to an image to use as the icon for this OAuth2 client.
        path: PathBuf,
        #[clap(name = "image-type")]
        /// The type of image being uploaded.
        image_type: Option<ImageType>,
    },
    /// Removes the custom image previously set.
    #[clap(name = "remove-image")]
    RemoveImage(Named),

    /// Add a supplemental URL as a redirection target. For example a phone app
    /// may use a redirect URL such as `app://my-cool-app` to trigger a native
    /// redirection event out of a browser.
    #[clap(name = "add-redirect-url")]
    AddOrigin {
        name: String,
        #[clap(name = "url")]
        origin: Url,
        #[clap(flatten)]
        copt: CommonOpt,
    },

    /// Remove a supplemental redirect URL from the OAuth2 client configuration.
    #[clap(name = "remove-redirect-url")]
    RemoveOrigin {
        name: String,
        #[clap(name = "url")]
        origin: Url,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    #[clap(name = "enable-pkce")]
    /// Enable PKCE on this oauth2 client. This defaults to being enabled.
    EnablePkce(Named),
    /// Disable PKCE on this oauth2 client to work around insecure clients that
    /// may not support it. You should request the client to enable PKCE!
    #[clap(name = "warning-insecure-client-disable-pkce")]
    DisablePkce(Named),
    #[clap(name = "warning-enable-legacy-crypto")]
    /// Enable legacy signing crypto on this oauth2 client. This defaults to being disabled.
    /// You only need to enable this for openid clients that do not support modern cryptographic
    /// operations.
    EnableLegacyCrypto(Named),
    /// Disable legacy signing crypto on this oauth2 client. This is the default.
    #[clap(name = "disable-legacy-crypto")]
    DisableLegacyCrypto(Named),
    /// Enable strict validation of redirect URLs. Previously redirect URLs only
    /// validated the origin of the URL matched. When enabled, redirect URLs must
    /// match exactly.
    #[clap(name = "enable-strict-redirect-url")]
    EnableStrictRedirectUri {
        name: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    #[clap(name = "disable-strict-redirect-url")]
    DisableStrictRedirectUri {
        name: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    #[clap(name = "enable-localhost-redirects")]
    /// Allow public clients to redirect to localhost.
    EnablePublicLocalhost {
        #[clap(flatten)]
        copt: CommonOpt,
        name: String,
    },
    /// Disable public clients redirecting to localhost.
    #[clap(name = "disable-localhost-redirects")]
    DisablePublicLocalhost {
        #[clap(flatten)]
        copt: CommonOpt,
        name: String,
    },
    /// Use the 'name' attribute instead of 'spn' for the preferred_username
    #[clap(name = "prefer-short-username")]
    PreferShortUsername(Named),
    /// Use the 'spn' attribute instead of 'name' for the preferred_username
    #[clap(name = "prefer-spn-username")]
    PreferSPNUsername(Named),
    #[cfg(feature = "dev-oauth2-device-flow")]
    /// Enable OAuth2 Device Flow authentication
    DeviceFlowEnable(Named),
    #[cfg(feature = "dev-oauth2-device-flow")]
    /// Disable OAuth2 Device Flow authentication
    DeviceFlowDisable(Named),
}

#[derive(Args, Debug)]
pub struct OptSetDomainDisplayName {
    #[clap(flatten)]
    copt: CommonOpt,
    #[clap(name = "new-display-name")]
    new_display_name: String,
}

#[derive(Debug, Subcommand)]
pub enum PwBadlistOpt {
    #[clap[name = "show"]]
    /// Show information about this system's password badlist
    Show(CommonOpt),
    #[clap[name = "upload"]]
    /// Upload an extra badlist, appending to the currently configured one.
    /// This badlist will be preprocessed to remove items that are already
    /// caught by "zxcvbn" at the configured level.
    Upload {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(value_parser, required = true, num_args(1..))]
        paths: Vec<PathBuf>,
        /// Perform a dry run and display the list that would have been uploaded instead.
        #[clap(short = 'n', long)]
        dryrun: bool,
    },
    #[clap[name = "remove", hide = true]]
    /// Remove the content of these lists if present in the configured
    /// badlist.
    Remove {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(value_parser, required = true, num_args(1..))]
        paths: Vec<PathBuf>,
    },
}

#[derive(Debug, Subcommand)]
pub enum DeniedNamesOpt {
    #[clap[name = "show"]]
    /// Show information about this system's denied name list
    Show {
        #[clap(flatten)]
        copt: CommonOpt,
    },
    #[clap[name = "append"]]
    Append {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(value_parser, required = true, num_args(1..))]
        names: Vec<String>,
    },
    #[clap[name = "remove"]]
    /// Remove a name from the denied name list.
    Remove {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(value_parser, required = true, num_args(1..))]
        names: Vec<String>,
    },
}

#[derive(Debug, Subcommand)]
pub enum DomainOpt {
    #[clap[name = "set-display-name"]]
    /// Set the domain display name
    SetDisplayName(OptSetDomainDisplayName),
    #[clap[name = "set-ldap-basedn"]]
    /// Change the basedn of this server. Takes effect after a server restart.
    /// Examples are `o=organisation` or `dc=domain,dc=name`. Must be a valid ldap
    /// dn containing only alphanumerics, and dn components must be org (o), domain (dc) or
    /// orgunit (ou).
    SetLdapBasedn {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(name = "new-basedn")]
        new_basedn: String,
    },
    /// Enable or disable unix passwords being used to bind via LDAP. Unless you have a specific
    /// requirement for this, you should disable this.
    SetLdapAllowUnixPasswordBind {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(name = "allow", action = clap::ArgAction::Set)]
        enable: bool,
    },
    #[clap(name = "show")]
    /// Show information about this system's domain
    Show(CommonOpt),
    #[clap(name = "revoke-key")]
    /// Revoke a key by its key id. This will cause all user sessions to be
    /// invalidated (logged out).
    RevokeKey {
        #[clap(flatten)]
        copt: CommonOpt,
        key_id: String,
    },
    /// The image presented as the instance logo
    #[clap(name = "set-image")]
    SetImage {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(name = "file-path")]
        path: PathBuf,
        #[clap(name = "image-type")]
        image_type: Option<ImageType>,
    },
    /// The remove the current instance logo, reverting to the default.
    #[clap(name = "remove-image")]
    RemoveImage {
        #[clap(flatten)]
        copt: CommonOpt,
    },
}

#[derive(Debug, Subcommand)]
pub enum SynchOpt {
    #[clap(name = "list")]
    /// List all configured IDM sync accounts
    List(CommonOpt),
    #[clap(name = "get")]
    /// Display a selected IDM sync account
    Get(Named),
    #[clap(name = "set-credential-portal")]
    /// Set the url to the external credential portal. This will be displayed to synced users
    /// so that they can be redirected to update their credentials on this portal.
    SetCredentialPortal {
        #[clap()]
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(name = "url")]
        url: Option<Url>,
    },
    /// Create a new IDM sync account
    #[clap(name = "create")]
    Create {
        #[clap()]
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(name = "description",
        value_parser = clap::builder::NonEmptyStringValueParser::new())]
        description: Option<String>,
    },
    /// Generate a bearer token for an IDM sync account
    #[clap(name = "generate-token")]
    GenerateToken {
        #[clap()]
        account_id: String,
        #[clap()]
        label: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Destroy (revoke) the bearer token for an IDM sync account
    #[clap(name = "destroy-token")]
    DestroyToken {
        #[clap()]
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Set the list of attributes that have their authority yielded from the sync account
    /// and are allowed to be modified by kanidm and users. Any attributes not listed in
    /// in this command will have their authority returned to the sync account.
    #[clap(name = "set-yield-attributes")]
    SetYieldAttributes {
        #[clap()]
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(name = "attributes")]
        attrs: Vec<String>,
    },
    /// Reset the sync cookie of this connector, so that on the next operation of the sync tool
    /// a full refresh of the provider is requested. Kanidm attributes that have been granted
    /// authority will *not* be lost or deleted.
    #[clap(name = "force-refresh")]
    ForceRefresh {
        #[clap()]
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Finalise and remove this sync account. This will transfer all synchronised entries into
    /// the authority of Kanidm. This signals the end of a migration from an external IDM into
    /// Kanidm. ⚠️  This action can NOT be undone. Once complete, it is most likely
    /// that attempting to recreate a sync account from the same IDM will fail due to conflicting
    /// entries that Kanidm now owns.
    #[clap(name = "finalise")]
    Finalise {
        #[clap()]
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
    /// Terminate and remove this sync account. This will DELETE all entries that were imported
    /// from the external IDM source. ⚠️  This action can NOT be undone, and will require you to
    /// recreate the sync account if you
    /// wish to re-import data. Recreating the sync account may fail until the recycle bin and
    /// and tombstones are purged.
    #[clap(name = "terminate")]
    Terminate {
        #[clap()]
        account_id: String,
        #[clap(flatten)]
        copt: CommonOpt,
    },
}

#[derive(Debug, Subcommand)]
pub enum AuthSessionExpiryOpt {
    #[clap[name = "get"]]
    /// Show information about this system auth session expiry
    Get(CommonOpt),
    #[clap[name = "set"]]
    /// Sets the system auth session expiry in seconds
    Set {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(name = "expiry")]
        expiry: u32,
    },
}

#[derive(Debug, Subcommand)]
pub enum PrivilegedSessionExpiryOpt {
    #[clap[name = "get"]]
    /// Show information about this system privileged session expiry
    Get(CommonOpt),
    #[clap[name = "set"]]
    /// Sets the system auth privilege session expiry in seconds
    Set {
        #[clap(flatten)]
        copt: CommonOpt,
        #[clap(name = "expiry")]
        expiry: u32,
    },
}

#[derive(Args, Debug)]
pub struct ApiSchemaDownloadOpt {
    #[clap(flatten)]
    copt: CommonOpt,
    /// Where to put the file, defaults to ./kanidm-openapi.json
    #[clap(name = "filename", env, default_value = "./kanidm-openapi.json")]
    filename: PathBuf,
    /// Force overwriting the file if it exists
    #[clap(short, long, env)]
    force: bool,
}

#[derive(Debug, Subcommand)]
pub enum ApiOpt {
    /// Download the OpenAPI schema file
    #[clap(name = "download-schema")]
    DownloadSchema(ApiSchemaDownloadOpt),
}

#[derive(Debug, Subcommand)]
pub enum SystemOpt {
    #[clap(name = "pw-badlist")]
    /// Configure and manage the password badlist entry
    PwBadlist {
        #[clap(subcommand)]
        commands: PwBadlistOpt,
    },
    #[clap(name = "denied-names")]
    /// Configure and manage denied names
    DeniedNames {
        #[clap(subcommand)]
        commands: DeniedNamesOpt,
    },
    #[clap(name = "oauth2")]
    /// Configure and display oauth2/oidc client configuration
    Oauth2 {
        #[clap(subcommand)]
        commands: Oauth2Opt,
    },
    #[clap(name = "domain")]
    /// Configure and display domain configuration
    Domain {
        #[clap(subcommand)]
        commands: DomainOpt,
    },
    #[clap(name = "sync")]
    /// Configure synchronisation from an external IDM system
    Synch {
        #[clap(subcommand)]
        commands: SynchOpt,
    },
    #[clap(name = "api")]
    /// API related things
    Api {
        #[clap(subcommand)]
        commands: ApiOpt,
    },
}

#[derive(Debug, Subcommand)]
#[clap(about = "Kanidm Client Utility")]
pub enum KanidmClientOpt {
    /// Login to an account to use with future cli operations
    Login(LoginOpt),
    /// Reauthenticate to access privileged functions of this account for a short period.
    Reauth(ReauthOpt),
    /// Logout of an active cli session
    Logout(LogoutOpt),
    /// Manage active cli sessions
    Session {
        #[clap(subcommand)]
        commands: SessionOpt,
    },
    #[clap(name = "self")]
    /// Actions for the current authenticated account
    CSelf {
        #[clap(subcommand)]
        commands: SelfOpt,
    },
    /// Actions to manage and view person (user) accounts
    Person {
        #[clap(subcommand)]
        commands: PersonOpt,
    },
    /// Actions to manage groups
    Group {
        #[clap(subcommand)]
        commands: GroupOpt,
    },
    /// Actions to manage and view service accounts
    #[clap(name = "service-account")]
    ServiceAccount {
        #[clap(subcommand)]
        commands: ServiceAccountOpt,
    },
    /// Prints graphviz dot file of all groups
    #[clap(name = "graph")]
    Graph(GraphCommonOpt),
    /// System configuration operations
    System {
        #[clap(subcommand)]
        commands: SystemOpt,
    },
    #[clap(name = "recycle-bin")]
    /// Recycle Bin operations
    Recycle {
        #[clap(subcommand)]
        commands: RecycleOpt,
    },
    /// Unsafe - low level, raw database queries and operations.
    #[clap(hide = true)]
    Raw {
        #[clap(subcommand)]
        commands: RawOpt,
    },
    /// Print the program version and exit
    Version {},
}

#[derive(Debug, clap::Parser)]
#[clap(about = "Kanidm Client Utility")]
pub struct KanidmClientParser {
    #[clap(subcommand)]
    pub commands: KanidmClientOpt,
}