reeve-cli 1.1.2

Localhost web dev stack manager: web servers, per-vhost PHP versions, SSL, and DNS — RunCloud, scaled down.
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
mod backends;
mod brew;
mod cli;
mod config;
mod daemon;
mod dns;
mod doctor;
mod logs;
mod ops;
mod park;
mod paths;
mod php;
mod preset;
mod probe;
mod project;
mod services;
mod ssl;
mod state;
mod traffic;
mod tui;
mod update;
mod vhost;

use anyhow::{Context, Result};
use backends::apache_modules::Origin;
use backends::{backend_for, server_service_id};
use clap::Parser;
use cli::{
    Cli, Commands, DnsCommands, ModCommands, ParkCommands, PhpCommands, ServerCommands,
    ServiceCommands, SslCommands, VhostCommands,
};
use config::{load_config, save_config, Config};
use state::{load_state, save_state, Backend, Server, Vhost};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "warn".into()),
        )
        .with_writer(std::io::stderr)
        .init();

    let cli = Cli::parse();

    match cli.command {
        None => tui::run(false).await,
        Some(Commands::Traffic) => tui::run(true).await,
        Some(Commands::Init) => cmd_init(),
        Some(Commands::Php(c)) => cmd_php(c),
        Some(Commands::Server(c)) => cmd_server(c),
        Some(Commands::Vhost(c)) => cmd_vhost(c),
        Some(Commands::Service(c)) => cmd_service(c),
        Some(Commands::Park(c)) => cmd_park(c),
        Some(Commands::Xdebug {
            action,
            target,
            all,
        }) => cmd_xdebug(action, target, all),
        Some(Commands::Apply) => cmd_apply(),
        Some(Commands::Validate) => cmd_validate(),
        Some(Commands::Ssl(c)) => cmd_ssl(c),
        Some(Commands::Dns(c)) => cmd_dns(c),
        Some(Commands::Logs {
            target,
            lines,
            follow,
        }) => cmd_logs(target, lines, follow),
        Some(Commands::Doctor) => cmd_doctor(),
        Some(Commands::Update { check }) => update::run(check),
        Some(Commands::TuiSnapshot {
            width,
            height,
            modal,
        }) => {
            print!("{}", tui::snapshot(width, height, &modal)?);
            Ok(())
        }
    }
}

fn cmd_dns(c: DnsCommands) -> Result<()> {
    let brew = brew::Brew::detect()?;
    let cfg = load_config().unwrap_or_default();
    let tlds = cfg.local_tlds;
    match c {
        DnsCommands::Setup => {
            let ok = dns::setup(&brew, &tlds)?;
            let list = tlds
                .iter()
                .map(|t| format!("*.{t}"))
                .collect::<Vec<_>>()
                .join(", ");
            println!(
                "✓ dnsmasq resolving {list} → 127.0.0.1 [{}]",
                daemon::status(dns::service_id()).as_str()
            );
            if ok {
                println!("✓ system resolver configured — {list} resolve system-wide");
            } else {
                println!("⚠ system resolver not fully configured");
            }
            Ok(())
        }
        DnsCommands::Status => {
            println!(
                "dnsmasq service : {}",
                daemon::status(dns::service_id()).as_str()
            );
            for tld in &tlds {
                println!(
                    "{} : {}",
                    dns::resolver_location(tld),
                    if dns::resolver_ready(tld) {
                        "present"
                    } else {
                        "missing"
                    }
                );
            }
            Ok(())
        }
    }
}

fn cmd_logs(target: Option<String>, lines: usize, follow: bool) -> Result<()> {
    let state = load_state().unwrap_or_default();
    let Some(target) = target else {
        println!("Available logs:");
        for t in logs::targets(&state)? {
            let where_ = if t.path.exists() {
                t.path.display().to_string()
            } else {
                "(no log yet)".to_string()
            };
            println!("  {:<16} {}", t.label, where_);
        }
        println!("\nView one with `reeve logs <target> [-n N] [--follow]`.");
        return Ok(());
    };
    let path = logs::resolve(&state, &target)?;
    if follow {
        logs::follow(&path, lines)
    } else {
        logs::tail(&path, lines)
    }
}

fn cmd_doctor() -> Result<()> {
    let brew = brew::Brew::detect().ok();
    let cfg = load_config().unwrap_or_default();
    let state = load_state().unwrap_or_default();
    let checks = doctor::run(brew.as_ref(), &cfg, &state);
    for c in &checks {
        println!("{} {:<14} {}", c.health.symbol(), c.name, c.detail);
    }
    let (mut warn, mut fail) = (0, 0);
    for c in &checks {
        match c.health {
            doctor::Health::Warn => warn += 1,
            doctor::Health::Fail => fail += 1,
            doctor::Health::Ok => {}
        }
    }
    println!();
    if fail > 0 {
        anyhow::bail!("{fail} check(s) failed, {warn} warning(s)");
    }
    if warn > 0 {
        println!("All critical checks passed ({warn} warning(s)).");
    } else {
        println!("All checks passed.");
    }
    Ok(())
}

fn cmd_init() -> Result<()> {
    let brew = brew::Brew::detect_or_offer_install()?;
    println!("✓ Homebrew detected at {}", brew.prefix.display());

    paths::ensure_dirs()?;
    println!("✓ Config root: {}", paths::config_dir()?.display());

    // Write config.toml if absent, seeding the detected brew prefix.
    let cfg_path = paths::config_path()?;
    if cfg_path.exists() {
        println!("• config.toml already exists — leaving it untouched");
    } else {
        let cfg = Config {
            brew_prefix: brew.prefix.display().to_string(),
            ..Config::default()
        };
        save_config(&cfg)?;
        println!("✓ Wrote {}", cfg_path.display());
    }

    // Seed an empty state file if absent.
    if !paths::state_path()?.exists() {
        save_state(&state::State::default())?;
        println!("✓ Wrote {}", paths::state_path()?.display());
    }

    // Report any PHP versions already installed via brew so the user can adopt
    // them instead of reinstalling.
    let existing = php::discover(&brew);
    if !existing.is_empty() {
        println!();
        println!("Found existing PHP install(s): {}", existing.join(", "));
        println!("  Adopt one with `reeve php install <version>` (reuses the brew install).");
    }

    // Offer to put the CLI php shim (`reeve php cli`) on PATH now, so the
    // one-time setup is handled up front instead of surfacing later.
    offer_shim_path_setup(&brew)?;

    // Linux one-time host setup: login lingering + privileged-port allowance.
    #[cfg(target_os = "linux")]
    linux_post_init()?;

    println!();
    println!("Next steps:");
    println!("  reeve php install 8.3       # install a PHP version + FPM master");
    println!("  reeve server add caddy      # add a web server");
    println!("  reeve vhost add app.test --root ~/Sites/app --php 8.3 --server caddy");
    Ok(())
}

/// Linux-only host setup run at the end of `init`: enable systemd login
/// lingering (so user units survive logout and start at boot), warn if the user
/// session bus is missing, and offer to allow unprivileged binding to :80/:443.
#[cfg(target_os = "linux")]
fn linux_post_init() -> Result<()> {
    println!();
    if daemon::linger_enabled() {
        println!("✓ systemd login lingering already enabled");
    } else {
        match daemon::enable_linger() {
            Ok(()) => println!(
                "✓ Enabled systemd login lingering — services persist across logout and start at boot"
            ),
            Err(e) => println!("⚠ {e}"),
        }
    }
    if !daemon::user_bus_ok() {
        println!(
            "⚠ `systemctl --user` is not responding — reeve needs a user session bus \
             (unavailable in bare containers)."
        );
    }
    offer_privileged_ports_setup()?;
    Ok(())
}

/// The sysctl drop-in that lets unprivileged processes bind low ports.
#[cfg(target_os = "linux")]
const SYSCTL_FILE: &str = "/etc/sysctl.d/99-reeve.conf";

/// Current `net.ipv4.ip_unprivileged_port_start`; low enough to bind :80?
#[cfg(target_os = "linux")]
fn privileged_ports_allowed() -> bool {
    std::fs::read_to_string("/proc/sys/net/ipv4/ip_unprivileged_port_start")
        .ok()
        .and_then(|s| s.trim().parse::<u16>().ok())
        .map(|start| start <= 80)
        .unwrap_or(false)
}

/// Offer to write the sysctl drop-in so user-level servers can bind :80/:443.
/// One sudo, survives reboots, no per-binary setcap that brew upgrades break.
#[cfg(target_os = "linux")]
fn offer_privileged_ports_setup() -> Result<()> {
    if privileged_ports_allowed() {
        println!("✓ Unprivileged binding to :80/:443 already allowed");
        return Ok(());
    }
    println!();
    println!("Linux blocks non-root processes from binding ports below 1024, but reeve's");
    println!("default servers use :80/:443. Allowing low ports takes one sudo:");
    println!("  {SYSCTL_FILE}: net.ipv4.ip_unprivileged_port_start = 80");
    if !brew::confirm("Write it now (via sudo)?")? {
        println!("• Skipped — configure servers on ports >= 1024, or run later:");
        println!(
            "    echo 'net.ipv4.ip_unprivileged_port_start = 80' | sudo tee {SYSCTL_FILE} && sudo sysctl --system"
        );
        return Ok(());
    }
    let script = format!(
        "printf 'net.ipv4.ip_unprivileged_port_start = 80\\n' > {SYSCTL_FILE} && sysctl --system"
    );
    let status = std::process::Command::new("sudo")
        .arg("bash")
        .arg("-c")
        .arg(&script)
        .status()
        .context("Failed to run sudo for sysctl setup")?;
    if status.success() {
        println!("✓ Wrote {SYSCTL_FILE} — servers can now bind :80/:443");
    } else {
        println!("⚠ sudo did not complete — servers will need ports >= 1024 until this is set");
    }
    Ok(())
}

fn cmd_php(c: PhpCommands) -> Result<()> {
    match c {
        PhpCommands::Install { version } => {
            // Ensure brew exists (offer install) before the shared path runs.
            brew::Brew::detect_or_offer_install()?;
            ops::install_php(&version)?;
            println!(
                "✓ PHP {version} ready — FPM master '{}' is {}",
                daemon::label(&php::service_id(&version)),
                daemon::status(&php::service_id(&version)).as_str()
            );
            Ok(())
        }
        PhpCommands::Pin { version } => {
            brew::Brew::detect_or_offer_install()?;
            match ops::pin_php(&version)? {
                php::Healed::Pinned => {
                    println!("✓ PHP {version} pinned to {}", php::formula(&version))
                }
                php::Healed::Adopted { actual } => {
                    println!(
                        "✓ PHP {version} adopted from Homebrew's unversioned `php` keg ({actual})"
                    );
                    println!(
                        "  No php@{version} formula exists while {version} is the current series. \
                         reeve re-checks the keg on every start and will flag it the moment \
                         Homebrew moves on."
                    );
                }
            }
            println!(
                "  FPM master '{}' is {}",
                daemon::label(&php::service_id(&version)),
                daemon::status(&php::service_id(&version)).as_str()
            );
            Ok(())
        }
        PhpCommands::List => {
            let mut state = load_state()?;
            state.sort_php();
            if state.php_versions.is_empty() {
                println!("No PHP versions installed. Run `reeve php install <version>`.");
            } else {
                let cfg = load_config().ok();
                let default = cfg.and_then(|c| c.default_php);
                let brew = brew::Brew::detect().ok();
                println!("{:<8} {:<9} {:<8} SOCKET", "VERSION", "FPM", "DEFAULT");
                for p in &state.php_versions {
                    // "no keg" beats a bare "error": the master isn't crashed,
                    // Homebrew's series bump took the keg out from under it.
                    let no_keg = brew
                        .as_ref()
                        .map(|b| php::keg(b, &p.version) == php::Keg::Missing)
                        .unwrap_or(false);
                    let status = if no_keg {
                        "no keg".to_string()
                    } else {
                        daemon::status(&php::service_id(&p.version))
                            .as_str()
                            .to_string()
                    };
                    let is_default = default.as_deref() == Some(p.version.as_str());
                    println!(
                        "{:<8} {:<9} {:<8} {}",
                        p.version,
                        status,
                        if is_default { "*" } else { "" },
                        p.fpm_socket
                    );
                }
            }
            Ok(())
        }
        PhpCommands::Use { version } => {
            let restarted = ops::set_default_php(&version)?;
            println!("✓ Default PHP set to {version}");
            if !restarted.is_empty() {
                println!(
                    "  restarted {} to pick it up: {}",
                    if restarted.len() == 1 {
                        "server"
                    } else {
                        "servers"
                    },
                    restarted.join(", ")
                );
            }
            Ok(())
        }
        PhpCommands::Restart { version } => {
            if load_state()?.get_php(&version).is_none() {
                anyhow::bail!("PHP {version} is not managed. See `reeve php list`.");
            }
            ops::restart_fpm(&version)?;
            println!("✓ PHP {version}: FPM master restarted");
            Ok(())
        }
        PhpCommands::Cli { version } => cmd_php_cli(version),
        PhpCommands::Ext(ext) => cmd_php_ext(ext),
        PhpCommands::Settings { version } => {
            let state = load_state()?;
            let php = state
                .get_php(&version)
                .ok_or_else(|| anyhow::anyhow!("PHP {version} is not managed"))?;
            println!("PHP {version} settings (★ = overridden):");
            println!("{:<28} {:<12} DEFAULT", "KEY", "VALUE");
            for def in php::php_settings_defs() {
                let val = php.setting(def.key, def.default);
                let overridden = php.settings.contains_key(def.key);
                println!(
                    "{}{:<27} {:<12} {}",
                    if overridden { "★" } else { " " },
                    def.key,
                    val,
                    def.default
                );
            }
            println!("\nXdebug:");
            for def in php::xdebug_settings_defs() {
                let val = php::xdebug_setting(php, def);
                println!(
                    "{}{:<27} {:<12} {}",
                    if val != def.default { "★" } else { " " },
                    def.key,
                    if val.is_empty() { "-" } else { &val },
                    if def.default.is_empty() {
                        "-"
                    } else {
                        def.default
                    }
                );
            }
            Ok(())
        }
        PhpCommands::Set {
            version,
            key,
            value,
        } => {
            ops::set_php_setting(&version, &key, &value)?;
            println!("✓ PHP {version}: {key} = {value} (FPM restarted)");
            Ok(())
        }
        PhpCommands::Xdebug { version, mode } => {
            let target = ops::XdebugTarget {
                via: format!("PHP {version}"),
                version,
            };
            set_xdebug_for(&[target], &mode)
        }
    }
}

/// `reeve xdebug [action] [target] [--all]`.
fn cmd_xdebug(action: Option<String>, target: Option<String>, all: bool) -> Result<()> {
    // A lone version or site (`reeve xdebug grav.test`) reads as a status query.
    let (action, target) = match action {
        Some(a)
            if target.is_none() && !XDEBUG_ACTIONS.contains(&a.to_ascii_lowercase().as_str()) =>
        {
            ("status".to_string(), Some(a))
        }
        a => (
            a.unwrap_or_else(|| "status".into()).to_ascii_lowercase(),
            target,
        ),
    };
    if !XDEBUG_ACTIONS.contains(&action.as_str()) {
        anyhow::bail!(
            "Unknown Xdebug action '{action}'. Use one of: {}.",
            XDEBUG_ACTIONS.join(", ")
        );
    }
    let mut state = load_state()?;
    state.sort_php();
    let targets = if all {
        state
            .php_versions
            .iter()
            .map(|p| ops::XdebugTarget {
                version: p.version.clone(),
                via: format!("PHP {}", p.version),
            })
            .collect()
    } else {
        let cwd = std::env::current_dir()?;
        match ops::resolve_xdebug_target(target.as_deref(), &cwd) {
            Ok(t) => vec![t],
            // A plain status check still lists every version when the current
            // folder is ambiguous; changing anything needs a clear target.
            Err(_) if action == "status" && target.is_none() => Vec::new(),
            Err(e) => return Err(e),
        }
    };
    if action == "status" {
        print_xdebug_status(&state, &targets, all);
        return Ok(());
    }
    set_xdebug_for(&targets, &action)
}

/// Words `reeve xdebug` accepts as its action.
const XDEBUG_ACTIONS: &[&str] = &["status", "on", "off", "toggle", "debug", "profile"];

/// The mode an Xdebug action leaves a version in. `on` keeps an already
/// enabled mode (a running profile stays a profile); `toggle` flips off ↔ on.
fn xdebug_action_mode(action: &str, current: state::XdebugMode) -> Result<state::XdebugMode> {
    use state::XdebugMode::{Debug, Off};
    Ok(match action {
        "on" if !current.is_off() => current,
        "on" => Debug,
        "toggle" if current.is_off() => Debug,
        "toggle" => Off,
        mode => state::XdebugMode::from_str(mode)?,
    })
}

/// Apply an Xdebug action to each target version, reporting what changed.
fn set_xdebug_for(targets: &[ops::XdebugTarget], action: &str) -> Result<()> {
    let action = action.to_ascii_lowercase();
    let state = load_state()?;
    // `--all toggle` flips the set as a whole: any version on turns them all off.
    let any_on = targets
        .iter()
        .filter_map(|t| state.get_php(&t.version))
        .any(|p| !p.xdebug.is_off());
    let mut debug_on = false;
    let mut enabled = false;
    for t in targets {
        let current = state
            .get_php(&t.version)
            .map(|p| p.xdebug)
            .ok_or_else(|| anyhow::anyhow!("PHP {} is not managed", t.version))?;
        let next = if action == "toggle" && targets.len() > 1 {
            if any_on {
                state::XdebugMode::Off
            } else {
                state::XdebugMode::Debug
            }
        } else {
            xdebug_action_mode(&action, current)?
        };
        let label = if t.via == format!("PHP {}", t.version) {
            t.via.clone()
        } else {
            format!("PHP {} ({})", t.version, t.via)
        };
        if next == current {
            println!("• {label}: Xdebug already {}", next.as_str());
        } else {
            if !next.is_off() {
                brew::Brew::detect_or_offer_install()?;
            }
            ops::set_xdebug(&t.version, next)?;
            println!("✓ {label}: Xdebug {} (FPM restarted)", next.as_str());
            enabled |= !next.is_off();
        }
        debug_on |= next == state::XdebugMode::Debug;
    }
    if debug_on {
        println!(
            "  Sessions start on demand: use an IDE debug run configuration, a browser\n  \
             extension, or add ?XDEBUG_SESSION=1 to the URL."
        );
    }
    // Xdebug is per FPM master, so enabling it for one site enables it for
    // every site on that version — worth saying when it isn't obvious.
    if let ([t], true) = (targets, enabled) {
        let sharing = ops::sites_on_php(&state, &t.version);
        if sharing > 1 {
            println!("  Applies to all {sharing} sites on PHP {}.", t.version);
        }
    }
    Ok(())
}

/// Print every version's Xdebug state, marking the one(s) a command targeted.
fn print_xdebug_status(state: &state::State, targets: &[ops::XdebugTarget], all: bool) {
    if state.php_versions.is_empty() {
        println!("No PHP versions installed. Run `reeve php install <version>`.");
        return;
    }
    println!(
        "  {:<8} {:<8} {:<8} {:<22} {:<10} OUTPUT",
        "VERSION", "MODE", "START", "CLIENT", "IDEKEY"
    );
    for p in &state.php_versions {
        let get = |key: &str| {
            php::xdebug_settings_defs()
                .iter()
                .find(|d| d.key == key)
                .map(|d| php::xdebug_setting(p, d))
                .unwrap_or_default()
        };
        let mut start = get("xdebug.start_with_request");
        if start == php::XDEBUG_START_AUTO {
            start = p.xdebug.start_with_request().to_string();
        }
        let idekey = get("xdebug.idekey");
        let target = targets.iter().find(|t| t.version == p.version);
        println!(
            "{} {:<8} {:<8} {:<8} {:<22} {:<10} {}{}",
            if target.is_some() && !all { "›" } else { " " },
            p.version,
            p.xdebug.as_str(),
            if p.xdebug.is_off() { "-" } else { &start },
            format!("{}:{}", get("xdebug.client_host"), p.xdebug_port),
            if idekey.is_empty() { "-" } else { &idekey },
            get("xdebug.output_dir"),
            match target {
                Some(t) if !all && t.via != format!("PHP {}", t.version) =>
                    format!("   ← {}", t.via),
                _ => String::new(),
            }
        );
    }
    println!(
        "\nToggle with `reeve xdebug on|off [version|site]`; set options with\n\
         `reeve php set <version> xdebug.<option> <value>` (see `reeve php settings`)."
    );
}

fn cmd_php_cli(version: Option<String>) -> Result<()> {
    let brew = brew::Brew::detect()?;
    match version {
        Some(version) => {
            php::set_cli_php(&brew, &version)?;
            println!("✓ CLI php → {version}");
            // The switch only takes effect once the shim wins on PATH — offer to
            // wire that up rather than just printing the line to add.
            offer_shim_path_setup(&brew)?;
            Ok(())
        }
        None => {
            match php::current_cli_php() {
                Some(v) => println!("CLI php: {v}"),
                None => {
                    println!("CLI php: not set — run `reeve php cli <version>` to point the shim.")
                }
            }
            offer_shim_path_setup(&brew)?;
            Ok(())
        }
    }
}

/// When the `~/.reeve/bin` shim isn't effective on PATH, offer to add it to the
/// user's shell profile (interactively), or print the line when we can't edit
/// automatically. No-op when the shim already wins on PATH.
fn offer_shim_path_setup(brew: &brew::Brew) -> Result<()> {
    if php::shim_on_path(brew) {
        return Ok(());
    }
    let shim = paths::shim_dir()?;
    let export = format!("export PATH=\"{}:$PATH\"", shim.display());
    let home = dirs::home_dir().context("Could not determine home directory")?;
    let shell = std::env::var("SHELL").unwrap_or_default();

    // fish uses different PATH syntax — guide rather than auto-edit it.
    if shell.contains("fish") {
        println!(
            "\n⚠ {} isn't on your PATH yet. Add it (fish):\n      fish_add_path {}",
            shim.display(),
            shim.display()
        );
        return Ok(());
    }

    // macOS defaults to zsh; bash login shells read ~/.bash_profile.
    let profile = if shell.contains("bash") {
        home.join(".bash_profile")
    } else {
        home.join(".zshrc")
    };

    // Already written but not active in this shell → just needs a reload.
    if std::fs::read_to_string(&profile)
        .map(|c| c.contains(".reeve/bin"))
        .unwrap_or(false)
    {
        println!(
            "\n• {} already adds the shim to PATH — open a new terminal (or `exec $SHELL`) to pick it up.",
            profile.display()
        );
        return Ok(());
    }

    println!(
        "\n⚠ {} isn't ahead of Homebrew on your PATH, so `reeve php cli` won't take effect yet.",
        shim.display()
    );
    if brew::confirm(&format!("Add it to {}?", profile.display()))? {
        use std::io::Write;
        let block = format!("\n# reeve: CLI php shim (reeve php cli <ver>)\n{export}\n");
        let mut f = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&profile)
            .with_context(|| format!("Failed to open {}", profile.display()))?;
        f.write_all(block.as_bytes())
            .with_context(|| format!("Failed to write {}", profile.display()))?;
        println!(
            "✓ Added to {} — open a new terminal (or `exec $SHELL`) to use it.",
            profile.display()
        );
    } else {
        println!("  Add this line to your shell profile yourself:\n      {export}");
    }
    Ok(())
}

fn cmd_php_ext(ext: cli::ExtCommands) -> Result<()> {
    use cli::ExtCommands;
    let brew = brew::Brew::detect()?;
    match ext {
        ExtCommands::List { version } => {
            let mods = php::extensions::list(&brew, &version)?;
            println!("PHP {version} — {} loaded extensions:", mods.len());
            for chunk in mods.chunks(4) {
                println!("  {}", chunk.join("  "));
            }
            Ok(())
        }
        ExtCommands::Add { version, name } => {
            if php::extensions::list(&brew, &version)?
                .iter()
                .any(|m| m.eq_ignore_ascii_case(&name))
            {
                println!("• {name} is already loaded in PHP {version}");
                return Ok(());
            }
            php::extensions::add(&brew, &version, &name)?;
            ops::restart_fpm(&version)?;
            let loaded = php::extensions::list(&brew, &version)?
                .iter()
                .any(|m| m.eq_ignore_ascii_case(&name));
            if loaded {
                println!("✓ {name} installed and loaded in PHP {version} (FPM restarted)");
            } else {
                println!(
                    "⚠ {name} built but not showing in `php -m`. It may need an ini entry; \
                     check `reeve php ext list {version}`."
                );
            }
            Ok(())
        }
        ExtCommands::Remove { version, name } => {
            php::extensions::remove(&brew, &version, &name)?;
            ops::restart_fpm(&version)?;
            println!("✓ {name} removed from PHP {version} (FPM restarted)");
            Ok(())
        }
    }
}

fn cmd_server(c: ServerCommands) -> Result<()> {
    match c {
        ServerCommands::Add {
            backend,
            name,
            http,
            https,
            default_site,
            root,
            preset,
        } => {
            let backend = Backend::from_str(&backend)?;
            let default_preset = state::Framework::from_str(&preset)?;
            let name = name.unwrap_or_else(|| backend.to_string());
            let mut state = load_state()?;
            state.add_server(Server {
                name: name.clone(),
                backend,
                http_port: http,
                https_port: https,
                enabled: false,
                default_site,
                default_preset,
                default_root: root
                    .filter(|r| !r.trim().is_empty())
                    .map(|r| expand_tilde(r.trim())),
                settings: Default::default(),
                modules: Vec::new(),
            })?;
            save_state(&state)?;
            // Install the backend's brew formula now (visible), rather than
            // letting the first `apply`/`start` stall silently on it.
            let brew = brew::Brew::detect_or_offer_install()?;
            backend_for(backend).ensure_installed(&brew)?;
            println!("✓ Added {backend} server '{name}' (http:{http} https:{https})");
            println!("  Run `reeve apply` to render and start it.");
            Ok(())
        }
        ServerCommands::List => {
            let state = load_state()?;
            if state.servers.is_empty() {
                println!("No servers. Run `reeve server add <backend>`.");
            } else {
                println!(
                    "{:<14} {:<8} {:<7} {:<7} STATUS",
                    "NAME", "BACKEND", "HTTP", "HTTPS"
                );
                for s in &state.servers {
                    println!(
                        "{:<14} {:<8} {:<7} {:<7} {}",
                        s.name,
                        s.backend,
                        s.http_port,
                        s.https_port,
                        ops::serve_state(s).label()
                    );
                }
            }
            Ok(())
        }
        ServerCommands::Remove { name } => {
            let mut state = load_state()?;
            let before = state.servers.len();
            state.servers.retain(|s| s.name != name);
            if state.servers.len() == before {
                anyhow::bail!("Server '{name}' not found");
            }
            state.vhosts.retain(|v| v.server != name);
            save_state(&state)?;
            println!("✓ Removed server '{name}' (and its vhosts)");
            Ok(())
        }
        ServerCommands::Start { name } => {
            let out = ops::start_server(&name)?;
            if let Some(note) = &out.handoff {
                println!("  ↪ {note}");
            }
            println!("✓ Started '{name}' — {}", out.status.as_str());
            Ok(())
        }
        ServerCommands::Stop { name } => {
            ops::stop_server(&name)?;
            println!("✓ Stopped '{name}'");
            Ok(())
        }
        ServerCommands::Restart { name } => {
            let status = ops::restart_server(&name)?;
            println!("✓ Restarted '{name}' — {}", status.as_str());
            Ok(())
        }
        ServerCommands::Mod(c) => cmd_server_mod(c),
    }
}

/// Report what a module change did, shared by `mod add` and `mod remove`.
fn report_module_change(name: &str, change: &ops::ModuleChange) {
    for m in &change.added {
        println!("  + {m}");
    }
    for m in &change.removed {
        println!("  - {m}");
    }
    if change.restarted {
        println!("  Restarted '{name}' — live now.");
    } else {
        // The conf is already rendered and `httpd -t`-clean at this point;
        // the only thing left is a server that isn't currently serving.
        println!("  Config written and validated. Start '{name}' to load them.");
    }
}

fn cmd_server_mod(c: ModCommands) -> Result<()> {
    match c {
        ModCommands::List { name, all } => {
            let server = ops::require_server(&name)?;
            if server.backend != Backend::Apache {
                anyhow::bail!(
                    "'{name}' is a {} server — module management is Apache-only.",
                    server.backend
                );
            }
            let brew = brew::Brew::detect_or_offer_install()?;
            let catalog = backends::apache_modules::catalog(&brew, &server)?;
            let shown: Vec<_> = catalog
                .iter()
                .filter(|m| all || m.enabled || m.implied || m.origin != Origin::Optional)
                .collect();
            println!("{:<30} {:<9} SOURCE", "MODULE", "LOADED");
            for m in &shown {
                let loaded = match (m.origin, m.enabled, m.implied) {
                    (Origin::Base, _, _) | (Origin::Ssl, _, _) => "yes",
                    (_, true, _) => "yes",
                    (_, _, true) => "yes",
                    _ => "no",
                };
                let source = match (m.origin, m.enabled, m.implied) {
                    (Origin::Base, _, _) => "base (always on)".to_string(),
                    (Origin::Ssl, _, _) => "ssl (auto when HTTPS)".to_string(),
                    (_, true, _) => "enabled".to_string(),
                    (_, _, true) => "required by another module".to_string(),
                    _ => "available".to_string(),
                };
                println!("{:<30} {loaded:<9} {source}", m.name);
            }
            if !all {
                let total = catalog.len();
                println!(
                    "\n{} of {total} modules shown — `reeve server mod list {name} --all` for the rest.",
                    shown.len()
                );
            }
            Ok(())
        }
        ModCommands::Add { name, module } => {
            let change = ops::add_apache_module(&name, &module)?;
            println!("✓ Enabled modules on '{name}':");
            report_module_change(&name, &change);
            Ok(())
        }
        ModCommands::Remove { name, module } => {
            let change = ops::remove_apache_module(&name, &module)?;
            println!("✓ Disabled modules on '{name}':");
            report_module_change(&name, &change);
            Ok(())
        }
    }
}

fn cmd_vhost(c: VhostCommands) -> Result<()> {
    match c {
        VhostCommands::Add {
            server_name,
            root,
            php,
            server,
            ssl,
            preset,
            proxy,
        } => {
            let preset = state::Framework::from_str(&preset)?;
            let mut state = load_state()?;
            state.add_vhost(Vhost {
                server_name: server_name.clone(),
                server,
                docroot: root,
                php_version: php,
                ssl,
                preset,
                proxy_target: proxy,
            })?;
            save_state(&state)?;
            println!("✓ Added vhost '{server_name}'");
            println!("  Run `reeve apply` to render and reload.");
            Ok(())
        }
        VhostCommands::List => {
            let state = load_state()?;
            if state.vhosts.is_empty() {
                println!("No vhosts. Run `reeve vhost add <host> ...`.");
            } else {
                println!(
                    "{:<22} {:<12} {:<6} {:<5} {:<9} TARGET",
                    "HOST", "SERVER", "PHP", "SSL", "PRESET"
                );
                for v in &state.vhosts {
                    let target = v.proxy_target.clone().unwrap_or_else(|| v.docroot.clone());
                    println!(
                        "{:<22} {:<12} {:<6} {:<5} {:<9} {}",
                        v.server_name, v.server, v.php_version, v.ssl, v.preset, target
                    );
                }
            }
            Ok(())
        }
        VhostCommands::Show { server_name } => {
            let state = load_state()?;
            // Declared vhosts win over parked ones, and `effective_vhosts_for`
            // already applies that; search every server so the host is found
            // whichever one serves it.
            let found = state
                .servers
                .iter()
                .flat_map(|s| park::effective_vhosts_for(&state, &s.name))
                .find(|v| v.server_name == server_name);
            let Some(v) = found else {
                anyhow::bail!(
                    "Host '{server_name}' isn't served by any server \
                     (no vhost declared, no parked folder matching it)"
                );
            };
            let declared = state.vhosts.iter().any(|d| d.server_name == server_name);
            println!("{}", v.server_name);
            println!(
                "  server      {} ({})",
                v.server,
                if declared {
                    "declared vhost"
                } else {
                    "parked folder"
                }
            );
            if let Some(target) = &v.proxy_target {
                println!("  proxy       {target}");
                return Ok(());
            }
            let site = project::resolve(&v)?;
            println!("  php         {}", v.php_version);
            println!("  ssl         {}", v.ssl);
            println!("  project     {}", v.docroot);
            println!("  docroot     {}", site.docroot);
            println!("  preset      {}", site.preset);
            match project::source(&v) {
                Some(path) => println!("  {:<11} {path}", project::FILE_NAME),
                None => println!(
                    "  {:<11} none — expected at {}",
                    project::FILE_NAME,
                    std::path::Path::new(&v.docroot)
                        .join(project::FILE_NAME)
                        .display()
                ),
            }
            if site.env.is_empty() {
                println!("  env         none");
            } else {
                // Names only: these are commonly secrets, and the file is right
                // there for anyone who wants the values.
                println!(
                    "  env         {}",
                    site.env.keys().cloned().collect::<Vec<_>>().join(", ")
                );
            }
            if let Some(w) = project::misplacement_warning(&v) {
                println!("⚠ {w}");
            }
            Ok(())
        }
        VhostCommands::Remove { server_name } => {
            let mut state = load_state()?;
            let before = state.vhosts.len();
            state.vhosts.retain(|v| v.server_name != server_name);
            if state.vhosts.len() == before {
                anyhow::bail!("Vhost '{server_name}' not found");
            }
            save_state(&state)?;
            println!("✓ Removed vhost '{server_name}'");
            Ok(())
        }
    }
}

fn cmd_service(c: ServiceCommands) -> Result<()> {
    use state::ServiceKind;
    match c {
        ServiceCommands::Add { kind } => {
            let kind = ServiceKind::from_str(&kind)?;
            ops::add_service(kind)?;
            println!("✓ Added service '{kind}' — `reeve service start {kind}` to run it.");
            Ok(())
        }
        ServiceCommands::Start { kind } => {
            brew::Brew::detect_or_offer_install()?;
            let kind = ServiceKind::from_str(&kind)?;
            let out = ops::start_service(kind)?;
            if let Some(note) = &out.handoff {
                println!("  ↪ {note}");
            }
            let summary = load_state()?
                .get_service(kind)
                .map(services::ports_summary)
                .unwrap_or_default();
            println!("✓ Started '{kind}' on {summary} — {}", out.status.as_str());
            Ok(())
        }
        ServiceCommands::Stop { kind } => {
            let kind = ServiceKind::from_str(&kind)?;
            ops::stop_service(kind)?;
            println!("✓ Stopped '{kind}'");
            Ok(())
        }
        ServiceCommands::Restart { kind } => {
            let kind = ServiceKind::from_str(&kind)?;
            let status = ops::restart_service(kind)?;
            println!("✓ Restarted '{kind}' — {}", status.as_str());
            Ok(())
        }
        ServiceCommands::Remove { kind } => {
            let kind = ServiceKind::from_str(&kind)?;
            ops::remove_service(kind)?;
            println!("✓ Removed service '{kind}'");
            Ok(())
        }
        ServiceCommands::List => {
            let state = load_state()?;
            if state.services.is_empty() {
                println!(
                    "No services. Add one with `reeve service add <mysql|mariadb|postgres|redis|memcached|mailpit>`."
                );
                return Ok(());
            }
            println!("{:<12} {:<12} {:<9} STATUS", "SERVICE", "PORTS", "ENABLED");
            for s in &state.services {
                let status = daemon::status(&services::service_id(s.kind));
                println!(
                    "{:<12} {:<12} {:<9} {}",
                    s.kind,
                    services::ports_display(s),
                    if s.enabled { "yes" } else { "no" },
                    status.as_str()
                );
            }
            Ok(())
        }
        ServiceCommands::Ports { kind } => {
            let kind = ServiceKind::from_str(&kind)?;
            let state = load_state()?;
            let inst = state
                .get_service(kind)
                .cloned()
                .unwrap_or_else(|| state::ManagedServiceInstance::new(kind));
            println!("{:<8} {:<8} DESCRIPTION", "KEY", "PORT");
            for d in services::port_defs(kind) {
                println!(
                    "{:<8} {:<8} {} — {} (default {})",
                    d.key,
                    inst.port(d.key, d.default),
                    d.label,
                    d.help,
                    d.default
                );
            }
            println!("\nChange one with `reeve service set {kind} <key> <port>`.");
            Ok(())
        }
        ServiceCommands::Set { kind, key, port } => {
            let kind = ServiceKind::from_str(&kind)?;
            let (inst, outcome) = ops::set_service_port(kind, &key, port)?;
            let note = match outcome {
                ops::PortChange::Restarted => "restarted",
                ops::PortChange::OnNextStart => "takes effect on next start",
                ops::PortChange::Unchanged => "unchanged",
            };
            println!(
                "✓ {kind} now on {} ({note})",
                services::ports_summary(&inst),
            );
            Ok(())
        }
    }
}

fn cmd_park(c: ParkCommands) -> Result<()> {
    match c {
        ParkCommands::Add {
            dir,
            server,
            php,
            tld,
            ssl,
        } => {
            let cfg = load_config()?;
            let root = expand_tilde(&dir);
            let tld = tld.unwrap_or_else(|| cfg.local_tlds[0].clone());
            let n = ops::add_park(&root, &server, &php, &tld, ssl)?;
            println!("✓ Parked {root} → *.{tld} ({n} site(s) found)");
            // Apply straight away. A park isn't one site you might still be
            // setting up (as `vhost add` often is) — it changes how a whole
            // directory of existing sites is served, and re-parking is how you
            // change their PHP version or server. Leaving that to a separate
            // step means `park list` reports the new settings while the sites
            // are still served with the old ones.
            cmd_apply()
        }
        ParkCommands::Remove { dir } => {
            let root = expand_tilde(&dir);
            ops::remove_park(&root)?;
            println!("✓ Unparked {root}");
            // Apply so its sites stop being served now, not later.
            cmd_apply()
        }
        ParkCommands::List => {
            let state = load_state()?;
            if state.parks.is_empty() {
                println!("No parked directories. Park one with `reeve park add <dir> --server <s> --php <v>`.");
                return Ok(());
            }
            for p in &state.parks {
                let sites = park::expand(p);
                println!(
                    "{}  → *.{}  ({}, PHP {}, {})",
                    p.root,
                    p.tld,
                    p.server,
                    p.php_version,
                    if p.ssl { "https" } else { "http" }
                );
                for v in sites {
                    println!("    {}  {}", v.server_name, v.docroot);
                }
            }
            Ok(())
        }
    }
}

/// Expand a leading `~` to the user's home directory.
fn expand_tilde(path: &str) -> String {
    state::expand_tilde(path)
}

fn cmd_apply() -> Result<()> {
    let brew = brew::Brew::detect()?;
    let cfg = load_config()?;
    let state = load_state()?;
    if state.servers.is_empty() {
        println!("Nothing to apply — no servers defined.");
        return Ok(());
    }
    // One server failing (a config that won't validate, a restart launchd
    // refuses) is reported and the rest carry on — otherwise every server and
    // PHP master after it in the list is silently left unreconciled.
    let mut failed: Vec<&str> = Vec::new();
    for server in &state.servers {
        let backend = backend_for(server.backend);
        let vhosts_owned = park::effective_vhosts_for(&state, &server.name);
        let vhosts: Vec<&Vhost> = vhosts_owned.iter().collect();
        let applied = (|| -> Result<()> {
            backend.ensure_installed(&brew)?;
            ops::ensure_vhost_certs(&vhosts, &brew)?;
            // The default site's HTTPS catch-all needs a `localhost` cert.
            if server.default_site && !ssl::exists(backends::DEFAULT_SITE_HOST) {
                ssl::mint(&brew, backends::DEFAULT_SITE_HOST)?;
            }
            backend.render(server, &vhosts, &state, &cfg, &brew)?;
            backend.validate(server, &brew)?;
            if server.enabled {
                let spec = backend.service_spec(server, &brew)?;
                daemon::install(&spec)?;
                daemon::restart(&server_service_id(server))?;
            }
            Ok(())
        })();
        if let Err(e) = applied {
            failed.push(&server.name);
            let now = daemon::status(&server_service_id(server)).as_str();
            println!(
                "✗ {} ({}) not applied — {e:#}\n  ↪ it is {now}; `reeve server start {}` once the cause is fixed",
                server.name, server.backend, server.name
            );
            continue;
        }
        // A `.reeve.toml` in the served docroot (or in a parked directory) is
        // never read, and the site keeps working without it — so say so here
        // rather than let the env silently go missing.
        for v in &vhosts {
            if let Some(w) = project::misplacement_warning(v) {
                println!("⚠ {w}");
            }
        }
        let status = if server.enabled {
            daemon::status(&server_service_id(server)).as_str()
        } else {
            "stopped"
        };
        // Rendering a config for a server that isn't running looks like success
        // but serves nothing — every site on it refuses the connection. Say so,
        // with the command that fixes it, rather than a bare tick.
        let running = status == "running";
        println!(
            "{} {} ({}) — {} vhost(s) [{}]",
            if running || vhosts.is_empty() {
                "✓"
            } else {
                "⚠"
            },
            server.name,
            server.backend,
            vhosts.len(),
            status
        );
        if !running && !vhosts.is_empty() {
            println!(
                "  ↪ config written, but nothing is serving it — `reeve server start {}`",
                server.name
            );
        }
    }
    for park in &state.parks {
        if let Some(w) = project::park_root_warning(&park.root) {
            println!("⚠ {w}");
        }
    }
    // Reconcile every PHP-FPM master too: rewrite its plist (so settings like
    // the launchd QoS apply to all versions, not just whichever was last
    // touched) and restart it.
    for php in &state.php_versions {
        // Report and carry on rather than `?`: a single version whose keg
        // Homebrew moved must not stop the other versions, servers and vhosts
        // from being applied.
        match php::ensure_fpm_running(&brew, php) {
            Ok(()) => println!("✓ php {} FPM master reconciled", php.version),
            Err(e) => println!("✗ php {} not reconciled — {e}", php.version),
        }
    }
    if !failed.is_empty() {
        anyhow::bail!("not applied: {}", failed.join(", "));
    }
    Ok(())
}

fn cmd_validate() -> Result<()> {
    let brew = brew::Brew::detect()?;
    let state = load_state()?;
    if state.servers.is_empty() {
        println!("No servers to validate.");
        return Ok(());
    }
    let mut all_ok = true;
    for server in &state.servers {
        let backend = backend_for(server.backend);
        match backend.validate(server, &brew) {
            Ok(()) => println!("✓ {} ({}) config valid", server.name, server.backend),
            Err(e) => {
                all_ok = false;
                println!("✗ {} ({}): {e}", server.name, server.backend);
            }
        }
    }
    if !all_ok {
        anyhow::bail!("one or more server configs are invalid");
    }
    Ok(())
}

fn cmd_ssl(c: SslCommands) -> Result<()> {
    let brew = brew::Brew::detect()?;
    match c {
        SslCommands::Mint { server_name } => {
            ssl::mint(&brew, &server_name)?;
            let (cert, _) = ssl::cert_paths(&server_name)?;
            println!("✓ Minted certificate for {server_name}");
            println!("  {}", cert.display());
            if !trust_store_ready(&brew) {
                println!("  Run `reeve ssl trust` once so browsers trust it.");
            }
            Ok(())
        }
        SslCommands::Trust => {
            if ssl::ensure_ca(&brew)? {
                println!(
                    "✓ mkcert local CA installed into the trust store — local HTTPS is now trusted"
                );
                // Browsers read the store once at launch, so a running one keeps
                // showing "Not secure" until it is fully quit — closing the last
                // window often isn't enough.
                println!("  ↪ fully quit and reopen your browser for it to take effect");
            } else {
                println!("✓ mkcert local CA was already trusted — local HTTPS works");
            }
            Ok(())
        }
        SslCommands::Untrust => {
            ssl::uninstall_ca(&brew)?;
            println!("✓ mkcert local CA removed from the trust store (CA files kept on disk)");
            Ok(())
        }
        SslCommands::Status => {
            let root = ssl::caroot(&brew)?;
            let generated = ssl::ca_cert(&brew).map(|p| p.exists()).unwrap_or(false);
            let trusted = ssl::is_trusted(&brew);
            println!("CA root:   {}", root.display());
            println!("Generated: {}", if generated { "yes" } else { "no" });
            println!(
                "Trusted:   {}",
                if trusted {
                    "yes — browsers/curl trust local certs"
                } else {
                    "no — run `reeve ssl trust`"
                }
            );
            Ok(())
        }
        SslCommands::Ca => {
            println!("{}", ssl::ca_cert(&brew)?.display());
            Ok(())
        }
    }
}

/// Best-effort check that the mkcert CA root exists (i.e. has been generated).
fn trust_store_ready(brew: &brew::Brew) -> bool {
    ssl::ca_cert(brew).map(|p| p.exists()).unwrap_or(false)
}