xbp 10.26.3

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
use clap::{Args, Parser, Subcommand, ValueEnum};
use std::path::PathBuf;

#[derive(Parser, Debug)]
#[command(
    name = "xbp",
    version,
    about = "Deploy, operate, and debug services with one CLI.",
    long_about = "XBP is an operations-first CLI for deployments, diagnostics, service orchestration,\nnetwork controls, and runtime observability.",
    disable_help_subcommand = false,
    next_line_help = true,
    help_template = "{before-help}{name} {version}\n{about-with-newline}\
{usage-heading} {usage}\n\n\
{all-args}\
{after-help}",
    after_help = "Quick start:\n  xbp diag\n  xbp services\n  xbp service start <name>\n  xbp api install --port 8080\n\nUse `xbp <command> -h` for command-specific examples."
)]
pub struct Cli {
    #[arg(long, global = true, help = "Enable verbose debugging output")]
    pub debug: bool,
    #[arg(short = 'l', help = "List pm2 processes")]
    pub list: bool,
    #[arg(short = 'p', long = "port", help = "Filter by port number")]
    pub port: Option<u16>,
    #[arg(long, help = "Open logs directory")]
    pub logs: bool,

    #[command(subcommand)]
    pub command: Option<Commands>,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    #[command(about = "Inspect or manage listening ports")]
    Ports(PortsCmd),
    #[command(about = "Analyze the current git worktree and create a conventional commit")]
    Commit(CommitCmd),
    #[command(about = "Initialize an XBP project in the current directory")]
    Init,
    #[command(about = "Install common dependencies for host setup")]
    Setup,
    #[command(about = "Redeploy one service or the entire project")]
    Redeploy {
        #[arg(
            help = "Service name to redeploy (optional, uses legacy redeploy.sh if not provided)"
        )]
        service_name: Option<String>,
    },
    #[command(about = "Run the legacy remote redeploy workflow over SSH")]
    RedeployV2(RedeployV2Cmd),
    #[command(about = "Inspect project/global config and manage provider keys")]
    Config(ConfigCmd),
    #[command(
        about = "Install supported host packages or project tooling",
        after_help = crate::commands::INSTALL_COMMAND_AFTER_HELP
    )]
    Install {
        #[arg(short = 'l', long = "list", help = "List installable targets and exit")]
        list: bool,
        #[arg(help = "Install target (leave empty to show installable options)")]
        package: Option<String>,
    },
    #[command(about = "Tail local or remote logs")]
    Logs(LogsCmd),
    #[command(about = "Open an interactive remote shell over SSH", visible_alias = "shell")]
    Ssh(SshCmd),
    #[command(about = "Open or manage cloudflared TCP forwarders")]
    Cloudflared(CloudflaredCmd),
    #[command(about = "List PM2 processes")]
    List,
    #[command(about = "Fetch an HTTP endpoint with sane defaults")]
    Curl(CurlCmd),
    #[command(about = "List configured services from project config")]
    Services,
    #[command(about = "Run service-level commands (build/install/start/dev)")]
    Service {
        #[arg(help = "Command to run: build, install, start, dev, or --help")]
        command: Option<String>,
        #[arg(help = "Service name")]
        service_name: Option<String>,
    },
    #[command(about = "Manage NGINX site configs and upstream mappings")]
    Nginx(NginxCmd),
    #[command(about = "Manage host network configuration and floating IPs")]
    Network(NetworkCmd),
    #[command(about = "Run full system diagnostics and readiness checks")]
    Diag(DiagCmd),
    #[command(about = "Run health-check monitoring commands")]
    Monitor(MonitorCmd),
    #[command(about = "Capture a PM2 snapshot for later restore")]
    Snapshot,
    #[command(about = "Restore PM2 state from dump or latest snapshot")]
    Resurrect,
    #[command(about = "Stop a PM2 process by name or stop all")]
    Stop {
        #[arg(help = "PM2 process name or 'all' (default: all)")]
        target: Option<String>,
    },
    #[command(about = "Flush PM2 logs globally or for a specific process")]
    Flush {
        #[arg(help = "Optional PM2 process name")]
        target: Option<String>,
    },
    #[command(about = "Run login flow against configured XBP API")]
    Login,
    #[command(about = "Inspect, reconcile, or bump project versions")]
    Version(VersionCmd),
    #[command(about = "Show PM2 environment by name or numeric id")]
    Env {
        #[arg(help = "PM2 process name or id")]
        target: String,
    },
    #[command(about = "Tail app logs or Kafka logs")]
    Tail(TailCmd),
    #[command(about = "Start a binary/process under PM2")]
    Start {
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    #[command(about = "Generate helper artifacts such as systemd units")]
    Generate(GenerateCmd),
    #[cfg(feature = "secrets")]
    #[command(about = "Manage env vars and GitHub Actions environment variables (feature-gated)")]
    Secrets(SecretsCmd),
    #[command(
        about = "Generate 'what did I get done' Markdown report from git commits across repos"
    )]
    Done(DoneCmd),
    #[cfg(feature = "kubernetes")]
    #[command(about = "Experimental Kubernetes cluster manager (feature-gated)")]
    Kubernetes(KubernetesCmd),
    #[cfg(feature = "nordvpn")]
    #[command(about = "NordVPN meshnet setup and passthrough (feature-gated)")]
    Nordvpn(NordvpnCmd),
    #[cfg(feature = "monitoring")]
    Monitoring(MonitoringCmd),
    #[command(about = "Manage the XBP API server")]
    Api(ApiCmd),
    #[cfg(feature = "docker")]
    #[command(about = "Pass-through wrapper around the Docker CLI")]
    Docker(DockerCmd),
}

pub fn command_label(command: &Commands) -> &'static str {
    match command {
        Commands::Ports(_) => "ports",
        Commands::Commit(_) => "commit",
        Commands::Init => "init",
        Commands::Setup => "setup",
        Commands::Redeploy { .. } => "redeploy",
        Commands::RedeployV2(_) => "redeploy-v2",
        Commands::Config(_) => "config",
        Commands::Install { .. } => "install",
        Commands::Logs(_) => "logs",
        Commands::Ssh(_) => "ssh",
        Commands::Cloudflared(_) => "cloudflared",
        Commands::List => "list",
        Commands::Curl(_) => "curl",
        Commands::Services => "services",
        Commands::Service { .. } => "service",
        Commands::Nginx(_) => "nginx",
        Commands::Network(_) => "network",
        Commands::Diag(_) => "diag",
        Commands::Monitor(_) => "monitor",
        Commands::Snapshot => "snapshot",
        Commands::Resurrect => "resurrect",
        Commands::Stop { .. } => "stop",
        Commands::Flush { .. } => "flush",
        Commands::Login => "login",
        Commands::Version(_) => "version",
        Commands::Env { .. } => "env",
        Commands::Tail(_) => "tail",
        Commands::Start { .. } => "start",
        Commands::Generate(_) => "generate",
        #[cfg(feature = "secrets")]
        Commands::Secrets(_) => "secrets",
        Commands::Done(_) => "done",
        #[cfg(feature = "kubernetes")]
        Commands::Kubernetes(_) => "kubernetes",
        #[cfg(feature = "nordvpn")]
        Commands::Nordvpn(_) => "nordvpn",
        #[cfg(feature = "monitoring")]
        Commands::Monitoring(_) => "monitoring",
        Commands::Api(_) => "api",
        #[cfg(feature = "docker")]
        Commands::Docker(_) => "docker",
    }
}

#[derive(Args, Debug)]
pub struct CommitCmd {
    #[arg(
        long,
        help = "Generate and print the conventional commit message without creating a git commit"
    )]
    pub dry_run: bool,
    #[arg(long, help = "Skip OpenRouter and use local heuristics only")]
    pub no_ai: bool,
    #[arg(
        long,
        default_value = "openai/gpt-4o-mini",
        help = "OpenRouter model override used for commit generation"
    )]
    pub model: String,
    #[arg(
        long,
        help = "Force the conventional commit scope (for example: cli, api, docs)"
    )]
    pub scope: Option<String>,
}

#[derive(Args, Debug)]
pub struct PortsCmd {
    #[arg(short = 'p', long = "port")]
    pub port: Option<u16>,
    #[arg(long = "kill")]
    pub kill: bool,
    #[arg(short = 'n', long = "nginx")]
    pub nginx: bool,
    #[arg(
        long = "full",
        help = "Show one unified ports view (reconciled listeners + exposure + security flags)"
    )]
    pub full: bool,
    #[arg(
        long = "no-local",
        help = "Exclude connections where LocalAddr equals RemoteAddr"
    )]
    pub no_local: bool,
    #[arg(
        long = "exposure",
        help = "Diagnose external exposure per port (binding + firewall layer)"
    )]
    pub exposure: bool,
}

#[derive(Args, Debug)]
pub struct ConfigCmd {
    #[arg(
        long,
        help = "Show the current project config instead of opening global XBP paths"
    )]
    pub project: bool,
    #[arg(long, help = "Print global XBP paths without opening them")]
    pub no_open: bool,
    #[command(subcommand)]
    pub provider: Option<ConfigProviderCmd>,
}

#[derive(Subcommand, Debug)]
pub enum ConfigProviderCmd {
    #[command(about = "Manage the OpenRouter API key used by AI-enabled commands")]
    Openrouter(ConfigSecretCmd),
    #[command(about = "Manage the GitHub OAuth2 token used for release automation")]
    Github(ConfigSecretCmd),
    #[command(
        about = "Manage the Linear API key used for release-note issue linking and initiative publishing"
    )]
    Linear(LinearConfigCmd),
}

#[derive(Args, Debug)]
pub struct ConfigSecretCmd {
    #[command(subcommand)]
    pub action: ConfigSecretAction,
}

#[derive(Subcommand, Debug)]
pub enum ConfigSecretAction {
    #[command(about = "Set provider key (omit value to enter it securely)")]
    SetKey {
        #[arg(help = "Provider key/token value")]
        key: Option<String>,
    },
    #[command(about = "Delete the stored provider key")]
    DeleteKey,
    #[command(about = "Show whether a key is configured (masked by default)")]
    Show {
        #[arg(long, help = "Print full key/token value (not masked)")]
        raw: bool,
    },
}

#[derive(Args, Debug)]
pub struct LinearConfigCmd {
    #[command(subcommand)]
    pub action: LinearConfigAction,
}

#[derive(Subcommand, Debug)]
pub enum LinearConfigAction {
    #[command(about = "Set Linear API key (omit value to enter it securely)")]
    SetKey {
        #[arg(help = "Linear API key/token value")]
        key: Option<String>,
    },
    #[command(about = "Delete the stored Linear API key")]
    DeleteKey,
    #[command(about = "Show whether a Linear API key is configured (masked by default)")]
    Show {
        #[arg(long, help = "Print full key/token value (not masked)")]
        raw: bool,
    },
    #[command(
        name = "select-initiative",
        about = "Pick a Linear initiative for the current repo and save it to .xbp/xbp.yaml"
    )]
    SelectInitiative,
}

#[derive(Args, Debug)]
pub struct CurlCmd {
    #[arg(help = "URL or domain to fetch, e.g. example.com or https://example.com/api")]
    pub url: Option<String>,
    #[arg(long, help = "Disable the default 15 second timeout")]
    pub no_timeout: bool,
}

#[derive(Args, Debug)]
#[command(subcommand_precedence_over_arg = true)]
pub struct VersionCmd {
    #[arg(
        help = "Show versions, bump with major/minor/patch, or set an explicit version like 1.2.3"
    )]
    pub target: Option<String>,
    #[arg(long, help = "Show normalized git tags from `git tag --list`")]
    pub git: bool,
    #[command(subcommand)]
    pub command: Option<VersionSubCommand>,
}

#[derive(Subcommand, Debug)]
pub enum VersionSubCommand {
    #[command(about = "Create and push a git tag for this version, then create a GitHub release")]
    Release(VersionReleaseCmd),
}

#[derive(Args, Debug)]
pub struct VersionReleaseCmd {
    #[arg(
        long,
        help = "Release this version instead of auto-detecting from tracked files"
    )]
    pub version: Option<String>,
    #[arg(
        long,
        help = "Allow releasing with uncommitted changes in the working tree"
    )]
    pub allow_dirty: bool,
    #[arg(long, help = "Release title (defaults to <version> - <repo>)")]
    pub title: Option<String>,
    #[arg(long, help = "Release notes body (Markdown)")]
    pub notes: Option<String>,
    #[arg(long, help = "Read release notes body from a file")]
    pub notes_file: Option<PathBuf>,
    #[arg(long, help = "Create as draft release")]
    pub draft: bool,
    #[arg(long, help = "Mark release as pre-release")]
    pub prerelease: bool,
    #[arg(
        long,
        value_enum,
        default_value_t = VersionReleaseLatest::Legacy,
        help = "Control GitHub latest flag: true, false, or legacy"
    )]
    pub make_latest: VersionReleaseLatest,
}

#[derive(Copy, Clone, Debug, ValueEnum)]
pub enum VersionReleaseLatest {
    True,
    False,
    Legacy,
}

#[derive(Args, Debug)]
pub struct RedeployV2Cmd {
    #[arg(short = 'p', long = "password")]
    pub password: Option<String>,
    #[arg(short = 'u', long = "username")]
    pub username: Option<String>,
    #[arg(short = 'h', long = "host")]
    pub host: Option<String>,
    #[arg(short = 'd', long = "project-dir")]
    pub project_dir: Option<String>,
}

#[derive(Args, Debug)]
pub struct LogsCmd {
    #[arg()]
    pub project: Option<String>,
    #[arg(long = "ssh-host", help = "SSH host to stream logs from")]
    pub ssh_host: Option<String>,
    #[arg(long = "ssh-username", help = "SSH username for remote host")]
    pub ssh_username: Option<String>,
    #[arg(long = "ssh-password", help = "SSH password for remote host")]
    pub ssh_password: Option<String>,
}

#[derive(Args, Debug)]
pub struct SshCmd {
    #[arg(long = "host", alias = "ssh-host", help = "SSH host or IP address")]
    pub ssh_host: Option<String>,
    #[arg(
        long = "port",
        default_value_t = 22,
        help = "SSH port for direct connections"
    )]
    pub ssh_port: u16,
    #[arg(
        long = "username",
        alias = "ssh-username",
        help = "SSH username for the remote host"
    )]
    pub ssh_username: Option<String>,
    #[arg(
        long = "password",
        alias = "ssh-password",
        help = "SSH password (omit to use stored config or a secure prompt)"
    )]
    pub ssh_password: Option<String>,
    #[arg(long, help = "Path to a private key file to use instead of password auth")]
    pub private_key: Option<PathBuf>,
    #[arg(long, help = "Passphrase for --private-key when required")]
    pub private_key_passphrase: Option<String>,
    #[arg(
        long,
        help = "Run this remote command in a PTY instead of opening the default login shell"
    )]
    pub command: Option<String>,
    #[arg(
        long,
        help = "TERM value sent to the server (default: TERM env var or xterm-256color)"
    )]
    pub term: Option<String>,
    #[arg(long, help = "Disable SSH host key verification")]
    pub no_host_key_check: bool,
    #[arg(
        long,
        help = "Pin the SSH host key as a base64 blob when using tunnels or first-connect flows"
    )]
    pub host_key: Option<String>,
    #[arg(long, help = "Path to a known_hosts file used for SSH host verification")]
    pub known_hosts_file: Option<PathBuf>,
    #[arg(
        long,
        help = "Cloudflare Access hostname used to open a local cloudflared TCP forwarder"
    )]
    pub cloudflared_hostname: Option<String>,
    #[arg(long, help = "Override the cloudflared binary path")]
    pub cloudflared_binary: Option<PathBuf>,
    #[arg(
        long,
        help = "Optional destination host:port passed to cloudflared access tcp"
    )]
    pub cloudflared_destination: Option<String>,
}

#[derive(Args, Debug)]
pub struct CloudflaredCmd {
    #[command(subcommand)]
    pub command: CloudflaredSubCommand,
}

#[derive(Subcommand, Debug)]
pub enum CloudflaredSubCommand {
    #[command(about = "Start a local cloudflared Access TCP forwarder")]
    Tcp(CloudflaredTcpCmd),
}

#[derive(Args, Debug)]
pub struct CloudflaredTcpCmd {
    #[arg(long, help = "Protected Cloudflare Access hostname")]
    pub hostname: String,
    #[arg(
        long,
        help = "Local listener address for the forwarder (default: auto-allocate 127.0.0.1:<port>)"
    )]
    pub listener: Option<String>,
    #[arg(long, help = "Optional destination host:port passed to cloudflared access tcp")]
    pub destination: Option<String>,
    #[arg(long, help = "Override the cloudflared binary path")]
    pub binary: Option<PathBuf>,
}

#[derive(Args, Debug)]
pub struct NginxCmd {
    #[command(subcommand)]
    pub command: NginxSubCommand,
}

#[derive(Args, Debug)]
pub struct NetworkCmd {
    #[command(subcommand)]
    pub command: NetworkSubCommand,
}

#[derive(Subcommand, Debug)]
pub enum NetworkSubCommand {
    #[command(about = "Manage persistent floating IP configuration")]
    FloatingIp(NetworkFloatingIpCmd),
    #[command(about = "Inspect discovered network configuration sources")]
    Config(NetworkConfigCmd),
    #[command(about = "Manage Hetzner-specific Linux network configuration")]
    Hetzner(NetworkHetznerCmd),
}

#[derive(Args, Debug)]
pub struct NetworkFloatingIpCmd {
    #[command(subcommand)]
    pub command: NetworkFloatingIpSubCommand,
}

#[derive(Subcommand, Debug)]
pub enum NetworkFloatingIpSubCommand {
    #[command(about = "Add a persistent floating IP entry to detected network backend")]
    Add {
        #[arg(long, help = "Floating IP address (IPv4 or IPv6)")]
        ip: String,
        #[arg(long, help = "CIDR suffix (defaults: IPv4=32, IPv6=64)")]
        cidr: Option<u8>,
        #[arg(long, help = "Network interface override (auto-detected when omitted)")]
        interface: Option<String>,
        #[arg(long, help = "Optional label for backend metadata/file naming")]
        label: Option<String>,
        #[arg(long, help = "Apply network changes after writing config")]
        apply: bool,
        #[arg(long, help = "Preview computed changes without writing files")]
        dry_run: bool,
    },
    #[command(about = "List floating IPs from runtime and persisted network config")]
    List {
        #[arg(long, help = "Emit JSON output")]
        json: bool,
    },
}

#[derive(Args, Debug)]
pub struct NetworkConfigCmd {
    #[command(subcommand)]
    pub command: NetworkConfigSubCommand,
}

#[derive(Subcommand, Debug)]
pub enum NetworkConfigSubCommand {
    #[command(about = "List detected backend and configuration source files")]
    List {
        #[arg(long, help = "Emit JSON output")]
        json: bool,
    },
}

#[derive(Args, Debug)]
pub struct NetworkHetznerCmd {
    #[command(subcommand)]
    pub command: NetworkHetznerSubCommand,
}

#[derive(Subcommand, Debug)]
pub enum NetworkHetznerSubCommand {
    #[command(about = "Configure a Hetzner vSwitch VLAN interface persistently")]
    Vswitch(NetworkHetznerVswitchCmd),
}

#[derive(Args, Debug)]
pub struct NetworkHetznerVswitchCmd {
    #[command(subcommand)]
    pub command: NetworkHetznerVswitchSubCommand,
}

#[derive(Subcommand, Debug)]
pub enum NetworkHetznerVswitchSubCommand {
    #[command(about = "Write persistent Linux config for a Hetzner vSwitch VLAN interface")]
    Setup {
        #[arg(long, help = "Private IPv4 address to assign on the vSwitch VLAN interface")]
        ip: String,
        #[arg(long, default_value_t = 24, help = "CIDR prefix for --ip (default: 24)")]
        cidr: u8,
        #[arg(long, help = "Physical parent interface (auto-detected when omitted)")]
        interface: Option<String>,
        #[arg(long, help = "Hetzner vSwitch VLAN ID")]
        vlan_id: u16,
        #[arg(long, default_value_t = 1400, help = "Interface MTU (default: 1400)")]
        mtu: u16,
        #[arg(
            long,
            default_value = "10.0.3.1",
            help = "Gateway for the routed Hetzner cloud network"
        )]
        gateway: String,
        #[arg(
            long,
            default_value = "10.0.0.0/16",
            help = "Destination CIDR routed through the Hetzner vSwitch gateway"
        )]
        route_cidr: String,
        #[arg(long, help = "Apply or activate the new config immediately")]
        apply: bool,
        #[arg(long, help = "Preview file changes without writing them")]
        dry_run: bool,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum NginxDnsMode {
    Manual,
    Plugin,
}

#[derive(Subcommand, Debug)]
pub enum NginxSubCommand {
    #[command(
        about = "Provision an HTTPS NGINX reverse proxy with Certbot",
        long_about = "Provision an NGINX reverse proxy, issue or reuse Let's Encrypt certificates,\n\
and write final HTTP->HTTPS redirect + TLS proxy config.\n\
\n\
Wildcard domains (for example *.example.com) require DNS-01 mode.\n\
Use --dns-mode manual for interactive TXT record prompts, or --dns-mode plugin\n\
with --dns-plugin and --dns-creds for non-interactive provider automation."
    )]
    Setup {
        #[arg(short, long, help = "Domain name (supports wildcard: *.example.com)")]
        domain: String,
        #[arg(short, long, help = "Port to proxy to")]
        port: u16,
        #[arg(
            short,
            long,
            help = "Email used for Let's Encrypt account registration"
        )]
        email: String,
        #[arg(
            long,
            value_enum,
            default_value_t = NginxDnsMode::Manual,
            help = "DNS challenge mode for wildcard certificates: manual or plugin"
        )]
        dns_mode: NginxDnsMode,
        #[arg(
            long,
            help = "Certbot DNS plugin name for --dns-mode plugin (for example: cloudflare)"
        )]
        dns_plugin: Option<String>,
        #[arg(
            long,
            help = "Path to DNS plugin credentials file for --dns-mode plugin"
        )]
        dns_creds: Option<PathBuf>,
        #[arg(
            long,
            default_value_t = true,
            action = clap::ArgAction::Set,
            value_parser = clap::builder::BoolishValueParser::new(),
            help = "For wildcard domains, also request the base domain certificate (true|false)"
        )]
        include_base: bool,
    },
    #[command(about = "List discovered NGINX sites with listen/upstream ports")]
    List,
    #[command(about = "Show full NGINX config for one domain or all domains")]
    Show {
        #[arg(help = "Optional domain name to inspect")]
        domain: Option<String>,
    },
    #[command(about = "Open an NGINX site config in your configured editor")]
    Edit {
        #[arg(help = "Domain name to edit")]
        domain: String,
    },
    #[command(about = "Update upstream port for an existing NGINX site")]
    Update {
        #[arg(short, long, help = "Domain name to update")]
        domain: String,
        #[arg(short, long, help = "New port to proxy to")]
        port: u16,
    },
}

#[derive(Args, Debug)]
pub struct DiagCmd {
    #[arg(long, help = "Check Nginx configuration")]
    pub nginx: bool,
    #[arg(long, help = "Check specific ports (comma-separated)")]
    pub ports: Option<String>,
    #[arg(long, help = "Skip internet speed test")]
    pub no_speed_test: bool,
    #[arg(
        long,
        help = "Path to docker compose file to validate (defaults to docker-compose.yml/compose.yml)"
    )]
    pub compose_file: Option<String>,
}

#[derive(Args, Debug)]
pub struct MonitorCmd {
    #[command(subcommand)]
    pub command: Option<MonitorSubCommand>,
}

#[derive(Subcommand, Debug)]
pub enum MonitorSubCommand {
    Check,
    Start,
}

#[cfg(feature = "monitoring")]
#[derive(Args, Debug)]
pub struct MonitoringCmd {
    #[command(subcommand)]
    pub command: MonitoringSubCommand,
}

#[cfg(feature = "monitoring")]
#[derive(Subcommand, Debug)]
pub enum MonitoringSubCommand {
    Serve {
        #[arg(
            short,
            long,
            default_value = "prodzilla.yml",
            help = "Monitoring config file"
        )]
        file: String,
    },
    RunOnce {
        #[arg(
            short,
            long,
            default_value = "prodzilla.yml",
            help = "Monitoring config file"
        )]
        file: String,
        #[arg(long, help = "Run probes only")]
        probes_only: bool,
        #[arg(long, help = "Run stories only")]
        stories_only: bool,
    },
    List {
        #[arg(
            short,
            long,
            default_value = "prodzilla.yml",
            help = "Monitoring config file"
        )]
        file: String,
    },
}

#[derive(Args, Debug)]
#[command(arg_required_else_help = true)]
pub struct ApiCmd {
    #[command(subcommand)]
    pub command: ApiSubCommand,
}

#[cfg(feature = "docker")]
#[derive(Args, Debug)]
pub struct DockerCmd {
    #[arg(
        trailing_var_arg = true,
        allow_hyphen_values = true,
        help = "Arguments to pass directly to the Docker CLI (default: --help)"
    )]
    pub args: Vec<String>,
}

#[derive(Subcommand, Debug)]
pub enum ApiSubCommand {
    Install {
        #[arg(long, default_value_t = 8080, help = "Port to expose the API on")]
        port: u16,
    },
}
#[derive(Args, Debug)]
pub struct TailCmd {
    #[arg(long, help = "Tail Kafka topic instead of log files")]
    pub kafka: bool,
    #[arg(long, help = "Ship logs to Kafka")]
    pub ship: bool,
}

#[derive(Args, Debug)]
pub struct GenerateCmd {
    #[command(subcommand)]
    pub command: GenerateSubCommand,
}

#[derive(Subcommand, Debug)]
pub enum GenerateSubCommand {
    #[command(about = "Generate or update .xbp/xbp.yaml (and convert legacy JSON)")]
    Config(GenerateConfigCmd),
    Systemd(GenerateSystemdCmd),
}

#[derive(Args, Debug)]
pub struct GenerateConfigCmd {
    #[arg(
        long,
        help = "Overwrite .xbp/xbp.yaml if it already exists (default errors when present)"
    )]
    pub force: bool,
    #[arg(
        long,
        help = "Refresh .xbp/xbp.yaml by applying project detection defaults for missing fields"
    )]
    pub update: bool,
    #[arg(
        long,
        help = "Path to a legacy xbp.json file to convert into .xbp/xbp.yaml"
    )]
    pub from_json: Option<PathBuf>,
}

#[cfg(feature = "secrets")]
#[derive(Args, Debug)]
pub struct SecretsCmd {
    #[arg(long, help = "GitHub repository override (owner/repo)")]
    pub repo: Option<String>,
    #[arg(long, help = "GitHub token to use (repo scope for private repos)")]
    pub token: Option<String>,
    #[arg(
        long = "environment",
        alias = "env",
        value_enum,
        default_value_t = SecretsEnvironment::XbpDev,
        help = "GitHub Actions environment to sync (default: xbp-dev)"
    )]
    pub environment: SecretsEnvironment,
    #[command(subcommand)]
    pub command: Option<SecretsSubCommand>,
}

#[cfg(feature = "secrets")]
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
pub enum SecretsEnvironment {
    #[value(name = "xbp-dev")]
    XbpDev,
    #[value(name = "xbp-preview")]
    XbpPreview,
    #[value(name = "xbp-prod")]
    XbpProd,
}

#[cfg(feature = "secrets")]
impl SecretsEnvironment {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::XbpDev => "xbp-dev",
            Self::XbpPreview => "xbp-preview",
            Self::XbpProd => "xbp-prod",
        }
    }
}

#[cfg(feature = "secrets")]
#[derive(Subcommand, Debug)]
pub enum SecretsSubCommand {
    /// List local env vars from the preferred env file
    List(ListCmd),
    /// Push local env vars to the secrets provider (GitHub)
    Push(PushCmd),
    /// Pull secrets from the provider into .env.local
    Pull(PullCmd),
    /// Generate .env.default from source code inspection
    GenerateDefault(GenerateDefaultCmd),
    /// Generate .env.example with categories and defaults
    GenerateExample(GenerateExampleCmd),
    /// Compare local env with remote (GitHub) variables
    Diff,
    /// Verify that all required env vars are available locally
    Verify,
    /// Check connectivity, token scope, and repo access for secrets
    #[command(name = "diag", alias = "doctor")]
    Diag,
    /// Show secrets command usage
    #[command(name = "usage")]
    Usage,
}

#[cfg(feature = "secrets")]
#[derive(Args, Debug)]
pub struct ListCmd {
    #[arg(long, help = "Env file to list (.env.local, .env, .env.default)")]
    pub file: Option<String>,
    #[arg(long, help = "Output format: plain (default) or json")]
    pub format: Option<String>,
}

#[cfg(feature = "secrets")]
#[derive(Args, Debug)]
pub struct PushCmd {
    #[arg(long, help = "Path to env file (default: .env.local/.env)")]
    pub file: Option<String>,
    #[arg(
        long,
        help = "Force overwrite existing GitHub Actions environment variables"
    )]
    pub force: bool,
    #[arg(long, help = "Show what would be pushed without making changes")]
    pub dry_run: bool,
}

#[cfg(feature = "secrets")]
#[derive(Args, Debug)]
pub struct PullCmd {
    #[arg(long, help = "Output file path (default: .env.local)")]
    pub output: Option<String>,
}

#[cfg(feature = "secrets")]
#[derive(Args, Debug)]
pub struct GenerateDefaultCmd {
    #[arg(long, help = "Output file path (default: .env.default)")]
    pub output: Option<String>,
}

#[cfg(feature = "secrets")]
#[derive(Args, Debug)]
pub struct GenerateExampleCmd {
    #[arg(long, help = "Output file path (default: .env.example)")]
    pub output: Option<String>,
    #[arg(long, help = "Remove keys from .env.local not in .env.example")]
    pub clean: bool,
    #[arg(long, help = "Only include vars matching prefix (repeatable)")]
    pub include_prefix: Vec<String>,
    #[arg(long, help = "Exclude vars matching prefix (repeatable)")]
    pub exclude_prefix: Vec<String>,
}

#[derive(Args, Debug)]
pub struct GenerateSystemdCmd {
    #[arg(
        long,
        default_value = "/etc/systemd/system",
        help = "Directory where the systemd units are written"
    )]
    pub output_dir: PathBuf,
    #[arg(long, help = "Only generate the unit for this service name")]
    pub service: Option<String>,
    #[arg(
        long,
        default_value_t = true,
        help = "Also generate the xbp-api systemd unit alongside project/services"
    )]
    pub api: bool,
}

#[derive(Args, Debug)]
pub struct DoneCmd {
    #[arg(long, help = "Root directory under which to discover git repos")]
    pub root: Option<std::path::PathBuf>,
    #[arg(
        long,
        default_value = "24 hours ago",
        help = "Git --since value (e.g. '7 days ago')"
    )]
    pub since: String,
    #[arg(short, long, help = "Output Markdown file path")]
    pub output: Option<std::path::PathBuf>,
    #[arg(long, help = "Skip AI summarization (OpenRouter)")]
    pub no_ai: bool,
    #[arg(short, long, help = "Discover repos recursively")]
    pub recursive: bool,
    #[arg(long, help = "Exclude repo by name (repeatable)")]
    pub exclude: Vec<String>,
}

#[cfg(feature = "nordvpn")]
#[derive(Args, Debug)]
pub struct NordvpnCmd {
    #[arg(
        trailing_var_arg = true,
        allow_hyphen_values = true,
        help = "Subcommand or args to pass to nordvpn (e.g. setup, meshnet peer list)"
    )]
    pub args: Vec<String>,
}

#[cfg(feature = "kubernetes")]
#[derive(Args, Debug)]
pub struct KubernetesCmd {
    #[command(subcommand)]
    pub command: KubernetesSubCommand,
}

#[cfg(feature = "kubernetes")]
#[derive(Args, Debug)]
pub struct KubernetesAddonCmd {
    #[command(subcommand)]
    pub command: KubernetesAddonSubCommand,
}

#[cfg(feature = "kubernetes")]
#[derive(Subcommand, Debug)]
pub enum KubernetesAddonSubCommand {
    /// Show complete addon status (enabled/disabled) from `microk8s status`
    List,
    /// Enable a MicroK8s addon
    Enable {
        #[arg(help = "Addon name (e.g. cert-manager, ingress, dashboard)")]
        name: String,
    },
    /// Disable a MicroK8s addon
    Disable {
        #[arg(help = "Addon name (e.g. cert-manager, ingress, dashboard)")]
        name: String,
    },
}

#[cfg(feature = "kubernetes")]
#[derive(Subcommand, Debug)]
pub enum KubernetesSubCommand {
    /// Validate kubectl, current context, and node readiness
    Check {
        #[arg(long, help = "Kubeconfig context to target")]
        context: Option<String>,
        #[arg(
            long,
            default_value = "default",
            help = "Namespace to probe for workload readiness"
        )]
        namespace: String,
        #[arg(long, help = "Skip live cluster calls (tooling check only)")]
        offline: bool,
    },
    /// Generate Deployment/Service/NetworkPolicy YAML
    Generate {
        #[arg(long, help = "Logical app name (used for resource names)")]
        name: String,
        #[arg(long, help = "Container image reference")]
        image: String,
        #[arg(long, default_value_t = 80, help = "Container port for the service")]
        port: u16,
        #[arg(long, default_value_t = 1, help = "Replica count")]
        replicas: u16,
        #[arg(
            long,
            default_value = "default",
            help = "Namespace for generated resources"
        )]
        namespace: String,
        #[arg(
            long,
            default_value = "k8s/xbp-manifest.yaml",
            help = "Path to write the manifest bundle"
        )]
        output: String,
        #[arg(long, help = "Optional ingress host (creates Ingress when set)")]
        host: Option<String>,
    },
    /// Apply a manifest bundle with kubectl apply -f
    Apply {
        #[arg(long, help = "Path to manifest file")]
        file: String,
        #[arg(long, help = "Override kube context")]
        context: Option<String>,
        #[arg(long, help = "Override namespace")]
        namespace: Option<String>,
        #[arg(long, help = "Use --dry-run=server")]
        dry_run: bool,
    },
    /// Summarize deployments/services/pods in a namespace
    Status {
        #[arg(long, default_value = "default", help = "Namespace to summarize")]
        namespace: String,
        #[arg(long, help = "Override kube context")]
        context: Option<String>,
    },
    /// Manage MicroK8s addons (list, enable, disable)
    Addons(KubernetesAddonCmd),
    /// Extract Kubernetes Dashboard login token from secret describe output
    DashboardToken {
        #[arg(
            long,
            default_value = "kube-system",
            help = "Namespace containing the dashboard token secret"
        )]
        namespace: String,
        #[arg(
            long,
            default_value = "microk8s-dashboard-token",
            help = "Secret name containing the dashboard login token"
        )]
        secret: String,
        #[arg(long, help = "Override kube context")]
        context: Option<String>,
    },
    /// Print decoded Grafana admin credentials from observability secret
    ObservabilityCreds {
        #[arg(
            long,
            default_value = "observability",
            help = "Namespace containing Grafana secret"
        )]
        namespace: String,
        #[arg(
            long,
            default_value = "kube-prom-stack-grafana",
            help = "Grafana secret name"
        )]
        secret: String,
        #[arg(long, help = "Override kube context")]
        context: Option<String>,
    },
    /// Create or update a cert-manager Issuer for Let's Encrypt
    Issuer {
        #[arg(
            long,
            help = "Email used for Let's Encrypt account registration (required)"
        )]
        email: String,
        #[arg(long, default_value = "letsencrypt", help = "Issuer resource name")]
        name: String,
        #[arg(
            long,
            default_value = "default",
            help = "Namespace for the Issuer resource"
        )]
        namespace: String,
        #[arg(
            long,
            default_value = "https://acme-v02.api.letsencrypt.org/directory",
            help = "ACME server URL (production by default)"
        )]
        server: String,
        #[arg(
            long,
            default_value = "letsencrypt-account-key",
            help = "Secret used to store the ACME account private key"
        )]
        private_key_secret: String,
        #[arg(
            long,
            default_value = "nginx",
            help = "Ingress class name used for HTTP01 solving"
        )]
        ingress_class_name: String,
        #[arg(long, help = "Override kube context")]
        context: Option<String>,
        #[arg(long, help = "Use --dry-run=server")]
        dry_run: bool,
    },
}

#[cfg(test)]
mod tests {
    use super::{
        Cli, CloudflaredSubCommand, Commands, GenerateSubCommand, LinearConfigAction,
        NetworkFloatingIpSubCommand, NetworkHetznerSubCommand, NetworkHetznerVswitchSubCommand,
        NetworkSubCommand, SshCmd,
    };
    #[cfg(feature = "secrets")]
    use super::{SecretsEnvironment, SecretsSubCommand};
    use clap::Parser;
    use std::path::PathBuf;

    #[test]
    fn parses_network_floating_ip_add() {
        let cli = Cli::parse_from([
            "xbp",
            "network",
            "floating-ip",
            "add",
            "--ip",
            "1.2.3.4",
            "--apply",
        ]);

        match cli.command {
            Some(Commands::Network(network)) => match network.command {
                NetworkSubCommand::FloatingIp(fip) => match fip.command {
                    NetworkFloatingIpSubCommand::Add { ip, apply, .. } => {
                        assert_eq!(ip, "1.2.3.4");
                        assert!(apply);
                    }
                    _ => panic!("expected add subcommand"),
                },
                _ => panic!("expected floating-ip subcommand"),
            },
            _ => panic!("expected network command"),
        }
    }

    #[test]
    fn parses_generate_config_update() {
        let cli = Cli::parse_from(["xbp", "generate", "config", "--update"]);

        match cli.command {
            Some(Commands::Generate(generate_cmd)) => match generate_cmd.command {
                GenerateSubCommand::Config(config_cmd) => assert!(config_cmd.update),
                _ => panic!("expected generate config command"),
            },
            _ => panic!("expected generate command"),
        }
    }

    #[test]
    fn parses_commit_command_with_dry_run() {
        let cli = Cli::parse_from(["xbp", "commit", "--dry-run", "--scope", "cli"]);

        match cli.command {
            Some(Commands::Commit(commit_cmd)) => {
                assert!(commit_cmd.dry_run);
                assert_eq!(commit_cmd.scope.as_deref(), Some("cli"));
                assert_eq!(commit_cmd.model, "openai/gpt-4o-mini");
            }
            _ => panic!("expected commit command"),
        }
    }

    #[test]
    fn parses_linear_select_initiative_config_command() {
        let cli = Cli::parse_from(["xbp", "config", "linear", "select-initiative"]);

        match cli.command {
            Some(Commands::Config(config_cmd)) => match config_cmd.provider {
                Some(super::ConfigProviderCmd::Linear(linear_cmd)) => {
                    assert!(matches!(
                        linear_cmd.action,
                        LinearConfigAction::SelectInitiative
                    ));
                }
                _ => panic!("expected linear config provider"),
            },
            _ => panic!("expected config command"),
        }
    }

    #[test]
    fn parses_ssh_command_with_cloudflared_and_key_auth() {
        let cli = Cli::parse_from([
            "xbp",
            "ssh",
            "--host",
            "ssh.internal",
            "--username",
            "deploy",
            "--private-key",
            "C:/Users/floris/.ssh/id_ed25519",
            "--cloudflared-hostname",
            "bastion.example.com",
            "--command",
            "htop",
        ]);

        let Some(Commands::Ssh(SshCmd {
            ssh_host,
            ssh_username,
            private_key,
            cloudflared_hostname,
            command,
            ..
        })) = cli.command
        else {
            panic!("expected shell command");
        };

        assert_eq!(ssh_host.as_deref(), Some("ssh.internal"));
        assert_eq!(ssh_username.as_deref(), Some("deploy"));
        assert_eq!(private_key, Some(PathBuf::from("C:/Users/floris/.ssh/id_ed25519")));
        assert_eq!(cloudflared_hostname.as_deref(), Some("bastion.example.com"));
        assert_eq!(command.as_deref(), Some("htop"));
    }

    #[test]
    fn parses_cloudflared_tcp_command() {
        let cli = Cli::parse_from([
            "xbp",
            "cloudflared",
            "tcp",
            "--hostname",
            "bastion.example.com",
            "--listener",
            "127.0.0.1:2222",
        ]);

        let Some(Commands::Cloudflared(cloudflared_cmd)) = cli.command else {
            panic!("expected cloudflared command");
        };

        match cloudflared_cmd.command {
            CloudflaredSubCommand::Tcp(tcp_cmd) => {
                assert_eq!(tcp_cmd.hostname, "bastion.example.com");
                assert_eq!(tcp_cmd.listener.as_deref(), Some("127.0.0.1:2222"));
            }
        }
    }

    #[test]
    fn parses_shell_alias_as_ssh_command() {
        let cli = Cli::parse_from(["xbp", "shell", "--host", "ssh.internal"]);

        let Some(Commands::Ssh(ssh_cmd)) = cli.command else {
            panic!("expected ssh command through shell alias");
        };

        assert_eq!(ssh_cmd.ssh_host.as_deref(), Some("ssh.internal"));
    }

    #[test]
    fn parses_hetzner_vswitch_setup_command() {
        let cli = Cli::parse_from([
            "xbp",
            "network",
            "hetzner",
            "vswitch",
            "setup",
            "--ip",
            "10.0.3.2",
            "--vlan-id",
            "4000",
            "--interface",
            "enp0s31f6",
            "--apply",
        ]);

        let Some(Commands::Network(network_cmd)) = cli.command else {
            panic!("expected network command");
        };

        match network_cmd.command {
            NetworkSubCommand::Hetzner(hetzner_cmd) => match hetzner_cmd.command {
                NetworkHetznerSubCommand::Vswitch(vswitch_cmd) => match vswitch_cmd.command {
                    NetworkHetznerVswitchSubCommand::Setup {
                        ip,
                        cidr,
                        interface,
                        vlan_id,
                        apply,
                        ..
                    } => {
                        assert_eq!(ip, "10.0.3.2");
                        assert_eq!(cidr, 24);
                        assert_eq!(interface.as_deref(), Some("enp0s31f6"));
                        assert_eq!(vlan_id, 4000);
                        assert!(apply);
                    }
                },
            },
            _ => panic!("expected hetzner subcommand"),
        }
    }

    #[cfg(feature = "secrets")]
    #[test]
    fn parses_secrets_diag_command() {
        let cli = Cli::parse_from(["xbp", "secrets", "diag"]);

        match cli.command {
            Some(Commands::Secrets(secrets_cmd)) => {
                assert!(matches!(secrets_cmd.command, Some(SecretsSubCommand::Diag)));
                assert!(matches!(
                    secrets_cmd.environment,
                    SecretsEnvironment::XbpDev
                ));
            }
            _ => panic!("expected secrets command"),
        }
    }

    #[cfg(feature = "secrets")]
    #[test]
    fn parses_secrets_environment_override() {
        let cli = Cli::parse_from(["xbp", "secrets", "--environment", "xbp-prod", "push"]);

        match cli.command {
            Some(Commands::Secrets(secrets_cmd)) => {
                assert!(matches!(
                    secrets_cmd.environment,
                    SecretsEnvironment::XbpProd
                ));
                assert!(matches!(
                    secrets_cmd.command,
                    Some(SecretsSubCommand::Push(_))
                ));
            }
            _ => panic!("expected secrets command"),
        }
    }
}