voli 0.4.0

A fast, no-admin package manager for Windows
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
//! voli CLI (spec §9). Phase 1 step 1: every v1 subcommand exists as a stub that
//! prints "not implemented yet" and exits with code 2.

mod cmd_index;
mod cmd_install;

use std::io::Read;
use std::path::{Path, PathBuf};

use clap::{Parser, Subcommand};
use voli_core::{
    Action, Paths, State, Step, UpgradeOutcome, config, env, self_install, uninstall, upgrade,
};

/// Exit code for a runtime error (bad args, install failure, …).
const EXIT_ERROR: i32 = 1;

#[derive(Parser)]
#[command(
    name = "voli",
    version,
    about = "A fast, no-admin package manager for Windows",
    arg_required_else_help = true
)]
struct Cli {
    /// Assume "yes" to prompts; never wait for interactive input.
    #[arg(long, global = true)]
    yes: bool,

    /// Emit machine-readable JSON where supported.
    #[arg(long, global = true)]
    json: bool,

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

#[derive(Subcommand)]
enum Command {
    /// Install one or more packages (pkg[@version] …).
    ///
    /// In this build only local installs are wired: pass a path to a
    /// `<name>.toml` manifest together with `--archive <path>`.
    Install {
        #[arg(required = true)]
        packages: Vec<String>,
        /// Local archive to install from (required for a local `.toml` manifest).
        #[arg(long)]
        archive: Option<PathBuf>,
        /// Do not apply any `[env]` environment variables (spec §8).
        #[arg(long)]
        no_env: bool,
    },
    /// Uninstall one or more packages.
    Uninstall {
        #[arg(required = true)]
        packages: Vec<String>,
        /// Also remove persist dirs (user data). Off by default.
        #[arg(long)]
        purge: bool,
    },
    /// Refresh the local package index.
    Update,
    /// Upgrade installed packages.
    Upgrade {
        packages: Vec<String>,
        /// Upgrade everything (except pinned packages).
        #[arg(long)]
        all: bool,
    },
    /// List installed packages with versions.
    List,
    /// Search the local index.
    Search {
        #[arg(required = true)]
        query: String,
    },
    /// Show details for a package.
    Info {
        #[arg(required = true)]
        package: String,
    },
    /// Pin a package (exclude from `upgrade --all`).
    Pin {
        #[arg(required = true)]
        package: String,
    },
    /// Unpin a package.
    Unpin {
        #[arg(required = true)]
        package: String,
    },
    /// Show the environment variables a package set (from the ledger).
    Env {
        #[arg(required = true)]
        package: String,
    },
    /// Remove non-current version dirs and stale cache.
    Cleanup {
        /// Delete cache entries older than N days (0 = all). Default 30.
        #[arg(long, default_value_t = 30)]
        cache_days: u64,
        /// Print what would be removed without deleting anything.
        #[arg(long)]
        dry_run: bool,
    },
    /// Install voli itself: copy binaries to bin\ and add shims\ to PATH.
    Setup,
    /// Get or set configuration values.
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Diagnose PATH, env drift, broken shims, and root-folder warnings.
    Doctor,
    /// Resolve a shim to its real target.
    Which {
        #[arg(required = true)]
        bin: String,
    },
    /// Update voli itself.
    SelfUpdate,
    /// Remove voli and all installed packages completely (zero trace).
    SelfUninstall,
}

#[derive(Subcommand)]
enum ConfigAction {
    /// Print a config value.
    Get {
        #[arg(required = true)]
        key: String,
    },
    /// Set a config value.
    Set {
        #[arg(required = true)]
        key: String,
        #[arg(required = true)]
        value: String,
    },
}

fn main() {
    let cli = Cli::parse();

    // Nudge (message only, no action) when running from outside <root>\bin.
    if !matches!(cli.command, Command::Setup) {
        maybe_offer_setup();
    }

    let code = match &cli.command {
        Command::Install {
            packages,
            archive,
            no_env,
        } => cmd_install::run(
            packages,
            archive.as_deref(),
            &root(),
            cli.json,
            cli.yes,
            *no_env,
        ),
        Command::Uninstall { packages, purge } => cmd_uninstall(packages, *purge),
        Command::List => cmd_list(cli.json),
        Command::Upgrade { packages, all } => cmd_upgrade(packages, *all, cli.json),
        Command::Pin { package } => cmd_pin(package, true),
        Command::Unpin { package } => cmd_pin(package, false),
        Command::Env { package } => cmd_env(package, cli.json),
        Command::Cleanup {
            cache_days,
            dry_run,
        } => cmd_cleanup(*cache_days, *dry_run, cli.json),
        Command::Setup => cmd_setup(),
        Command::Config { action } => cmd_config(action, cli.json),
        Command::Doctor => cmd_doctor(cli.json),
        Command::Which { bin } => cmd_which(bin),
        Command::Update => cmd_index::run_update(&root(), cli.json),
        Command::Search { query } => cmd_index::run_search(&root(), query, cli.json),
        Command::Info { package } => cmd_index::run_info(&root(), package, cli.json),
        Command::SelfUpdate => cmd_self_update(),
        Command::SelfUninstall => cmd_self_uninstall(cli.yes),
    };
    std::process::exit(code);
}

/// If voli is not running from `<root>\bin`, print a one-line hint to run
/// `voli setup`. Message only — never takes action (spec §11 step 5).
fn maybe_offer_setup() {
    let Ok(root) = config::resolve_root() else {
        return;
    };
    let bin = root.join("bin");
    let running_in_bin = std::env::current_exe()
        .ok()
        .and_then(|e| e.parent().map(Path::to_path_buf))
        .zip(std::fs::canonicalize(&bin).ok())
        .map(|(dir, canon_bin)| std::fs::canonicalize(&dir).ok() == Some(canon_bin))
        .unwrap_or(false);
    if !running_in_bin {
        eprintln!("note: voli is not installed under {}", bin.display());
        eprintln!("      run `voli setup` to install it and add shims to your PATH.");
    }
}

fn root() -> PathBuf {
    match config::resolve_root() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("error: cannot resolve voli root: {e}");
            std::process::exit(EXIT_ERROR);
        }
    }
}

fn cmd_uninstall(packages: &[String], purge: bool) -> i32 {
    let root = root();
    let mut code = 0;
    for name in packages {
        match uninstall(name, &root, purge) {
            Ok(r) => {
                println!("uninstalled {} {}", r.name, r.version);
                if r.kept_persist {
                    println!("  kept persist data (use --purge to remove it)");
                }
            }
            Err(e) => {
                eprintln!("error: uninstall '{name}' failed: {e}");
                code = EXIT_ERROR;
            }
        }
    }
    code
}

fn cmd_list(json: bool) -> i32 {
    let state = match State::open(&Paths::at(root()).state_db()) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: cannot open state db: {e}");
            return EXIT_ERROR;
        }
    };
    let pkgs = match state.list() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("error: cannot read state db: {e}");
            return EXIT_ERROR;
        }
    };

    if json {
        let arr: Vec<_> = pkgs
            .iter()
            .map(|p| {
                serde_json::json!({
                    "name": p.name,
                    "version": p.version,
                    "installed_at": p.installed_at,
                })
            })
            .collect();
        println!("{}", serde_json::to_string_pretty(&arr).unwrap());
    } else if pkgs.is_empty() {
        println!("no packages installed");
    } else {
        for p in &pkgs {
            println!("{}  {}", p.name, p.version);
        }
    }
    0
}

fn cmd_upgrade(packages: &[String], all: bool, json: bool) -> i32 {
    let root = root();

    // Determine the target set: explicit names, or every non-pinned package.
    let targets: Vec<(String, bool)> = if all {
        let state = match State::open(&Paths::at(&root).state_db()) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("error: cannot open state db: {e}");
                return EXIT_ERROR;
            }
        };
        match state.list() {
            Ok(pkgs) => pkgs
                .into_iter()
                .filter(|p| p.name != "@voli")
                .map(|p| (p.name, p.pinned))
                .collect(),
            Err(e) => {
                eprintln!("error: cannot list installed packages: {e}");
                return EXIT_ERROR;
            }
        }
    } else if packages.is_empty() {
        eprintln!("error: specify a package to upgrade, or use --all");
        return EXIT_ERROR;
    } else {
        // Explicit upgrade proceeds even if pinned (spec §9), with a note.
        packages.iter().map(|n| (n.clone(), false)).collect()
    };

    let mut code = 0;
    let mut results = Vec::new();
    for (name, pinned_under_all) in &targets {
        if all && *pinned_under_all {
            if !json {
                println!("{name}: pinned — skipped");
            }
            results.push(serde_json::json!({ "name": name, "status": "pinned" }));
            continue;
        }
        // Explicit upgrade of a pinned package proceeds, with a note.
        if !all {
            let pinned = State::open(&Paths::at(&root).state_db())
                .ok()
                .and_then(|s| s.is_pinned(name).ok())
                .unwrap_or(false);
            if pinned && !json {
                println!("note: {name} is pinned; upgrading anyway (explicit request)");
            }
        }

        match upgrade(name, &root, &mut |s| upgrade_step(json, s)) {
            Ok(UpgradeOutcome::UpToDate { version }) => {
                if !json {
                    println!("{name} is up to date ({version})");
                }
                results.push(
                    serde_json::json!({ "name": name, "status": "up_to_date", "version": version }),
                );
            }
            Ok(UpgradeOutcome::Upgraded(r)) => {
                if !json {
                    println!("upgraded {} {} -> {}", r.name, r.from_version, r.to_version);
                }
                results.push(serde_json::json!({
                    "name": r.name,
                    "status": "upgraded",
                    "from": r.from_version,
                    "to": r.to_version,
                }));
            }
            Err(e) => {
                if !json {
                    eprintln!("error: upgrade '{name}' failed: {e}");
                }
                results.push(serde_json::json!({ "name": name, "status": "error", "message": e.to_string() }));
                code = EXIT_ERROR;
            }
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "ok": code == 0,
                "results": results,
            }))
            .unwrap()
        );
    }
    code
}

/// One-line download note for an upgrade (human mode only). ponytail: upgrade
/// prints a note rather than a live bar — the rich progress bar already exists
/// for install and download is cache-aware/fast.
fn upgrade_step(json: bool, step: Step) {
    if json {
        return;
    }
    if let Step::Downloading { name, version } = step {
        println!("downloading {name} {version}...");
    }
}

fn cmd_pin(package: &str, pin: bool) -> i32 {
    let mut state = match State::open(&Paths::at(root()).state_db()) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: cannot open state db: {e}");
            return EXIT_ERROR;
        }
    };
    match state.set_pinned(package, pin) {
        Ok(true) => {
            println!("{} {package}", if pin { "pinned" } else { "unpinned" });
            0
        }
        Ok(false) => {
            eprintln!("error: '{package}' is not installed");
            EXIT_ERROR
        }
        Err(e) => {
            eprintln!("error: cannot update pin: {e}");
            EXIT_ERROR
        }
    }
}

/// `voli env <pkg>`: show the env vars a package set, from its ledger (spec §8).
fn cmd_env(package: &str, json: bool) -> i32 {
    let root = root();
    let state = match State::open(&Paths::at(&root).state_db()) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: cannot open state db: {e}");
            return EXIT_ERROR;
        }
    };
    if !state.is_installed(package).unwrap_or(false) {
        eprintln!("error: '{package}' is not installed");
        return EXIT_ERROR;
    }
    let actions = match state.actions_for(package) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("error: cannot read ledger: {e}");
            return EXIT_ERROR;
        }
    };
    let subkey = env_subkey();

    let mut entries = Vec::new();
    for a in &actions {
        match a {
            Action::EnvSet { key, value, .. } => {
                let current = env::get(&subkey, key).ok().flatten();
                entries.push((key.clone(), value.clone(), current));
            }
            Action::PathAdded { segment } => {
                let present = env::get(&subkey, "Path")
                    .ok()
                    .flatten()
                    .map(|p| env::path_has_segment(&p, segment))
                    .unwrap_or(false);
                entries.push((
                    "PATH".to_string(),
                    segment.clone(),
                    present.then(|| segment.clone()),
                ));
            }
            _ => {}
        }
    }

    if json {
        let arr: Vec<_> = entries
            .iter()
            .map(|(k, v, cur)| serde_json::json!({ "key": k, "value": v, "current": cur }))
            .collect();
        println!("{}", serde_json::to_string_pretty(&arr).unwrap());
        return 0;
    }
    if entries.is_empty() {
        println!("{package} set no environment variables");
        return 0;
    }
    println!("{package} set:");
    for (k, v, _cur) in &entries {
        println!("  {k} = {v}");
    }
    0
}

/// `voli cleanup`: remove non-current version dirs, `bin\*.old` self-update
/// leftovers, and cache entries older than `cache_days` (0 = all). Reports bytes
/// freed. `--dry-run` prints without deleting. Never touches persist (spec §11).
fn cmd_cleanup(cache_days: u64, dry_run: bool, json: bool) -> i32 {
    use voli_core::cleanup_versions;

    let root = root();
    let paths = Paths::at(&root);
    let state = match State::open(&paths.state_db()) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: cannot open state db: {e}");
            return EXIT_ERROR;
        }
    };
    let pkgs = match state.list() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("error: cannot list installed packages: {e}");
            return EXIT_ERROR;
        }
    };

    let mut removed_dirs: Vec<String> = Vec::new();
    let mut freed: u64 = 0;

    // 1. Non-current version dirs, per package.
    for p in &pkgs {
        if p.name == "@voli" {
            continue;
        }
        match cleanup_versions(&root, &p.name, &p.version, dry_run) {
            Ok((dirs, bytes)) => {
                freed += bytes;
                removed_dirs.extend(dirs.iter().map(|d| d.display().to_string()));
            }
            Err(e) => eprintln!("warning: cleanup of {} failed: {e}", p.name),
        }
    }

    // 2. bin\*.old self-update leftovers.
    let bin = root.join("bin");
    if let Ok(entries) = std::fs::read_dir(&bin) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("old") {
                freed += entry.metadata().map(|m| m.len()).unwrap_or(0);
                removed_dirs.push(path.display().to_string());
                if !dry_run {
                    let _ = std::fs::remove_file(&path);
                }
            }
        }
    }

    // 3. Stale cache entries (mtime older than cache_days; 0 = all).
    let cache = paths.cache();
    let now = std::time::SystemTime::now();
    let max_age = std::time::Duration::from_secs(cache_days * 24 * 60 * 60);
    if let Ok(entries) = std::fs::read_dir(&cache) {
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_file() {
                continue;
            }
            let stale = cache_days == 0
                || entry
                    .metadata()
                    .and_then(|m| m.modified())
                    .ok()
                    .and_then(|mt| now.duration_since(mt).ok())
                    .map(|age| age >= max_age)
                    .unwrap_or(false);
            if stale {
                freed += entry.metadata().map(|m| m.len()).unwrap_or(0);
                removed_dirs.push(path.display().to_string());
                if !dry_run {
                    let _ = std::fs::remove_file(&path);
                }
            }
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "dry_run": dry_run,
                "freed_bytes": freed,
                "removed": removed_dirs,
            }))
            .unwrap()
        );
    } else {
        let verb = if dry_run { "would remove" } else { "removed" };
        if removed_dirs.is_empty() {
            println!("cleanup: nothing to remove");
        } else {
            for d in &removed_dirs {
                println!("  {verb}: {d}");
            }
            println!(
                "cleanup: {verb} {} item(s), {} freed",
                removed_dirs.len(),
                human_bytes(freed)
            );
        }
    }
    0
}

/// Render a byte count as a short human string (KiB/MiB/GiB).
fn human_bytes(n: u64) -> String {
    const UNITS: &[&str] = &["B", "KiB", "MiB", "GiB", "TiB"];
    let mut v = n as f64;
    let mut i = 0;
    while v >= 1024.0 && i < UNITS.len() - 1 {
        v /= 1024.0;
        i += 1;
    }
    if i == 0 {
        format!("{n} B")
    } else {
        format!("{v:.1} {}", UNITS[i])
    }
}

// Test hook shared by setup, doctor, and the env flows: point env mutations /
// checks at a scratch subkey so tests and smoke runs never touch the real user
// Environment. The real logic lives in `voli_core::env` so core flows resolve
// the same subkey (spec §8).
fn env_subkey() -> String {
    env::env_subkey()
}

fn cmd_setup() -> i32 {
    let root = root();
    match self_install(&root, None, &env_subkey()) {
        Ok(r) => {
            println!("voli installed to {}", r.bin_dir.display());
            for f in &r.copied {
                println!("  bin: {f}");
            }
            if r.path_added {
                println!("  added {} to your PATH", r.shims_dir.display());
                println!("  open a new shell for the PATH change to take effect.");
            } else {
                println!("  {} already on PATH", r.shims_dir.display());
            }
            0
        }
        Err(e) => {
            eprintln!("error: setup failed: {e}");
            EXIT_ERROR
        }
    }
}

const GITHUB_RELEASE_API: &str = "https://api.github.com/repos/Topurrra/voli/releases/latest";

fn cmd_self_update() -> i32 {
    use sha2::{Digest, Sha256};

    let current = env!("CARGO_PKG_VERSION");
    println!("voli {current}: checking for updates...");

    // 1. Query GitHub API for the latest release.
    let resp = match ureq::get(GITHUB_RELEASE_API)
        .set("User-Agent", concat!("voli/", env!("CARGO_PKG_VERSION")))
        .call()
    {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: cannot reach GitHub API: {e}");
            return EXIT_ERROR;
        }
    };
    let body_str = match resp.into_string() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: reading API response: {e}");
            return EXIT_ERROR;
        }
    };
    let body: serde_json::Value = match serde_json::from_str(&body_str) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("error: bad API JSON: {e}");
            return EXIT_ERROR;
        }
    };

    let tag = body["tag_name"].as_str().unwrap_or("unknown");
    let latest = tag.trim_start_matches('v');
    if latest == current {
        println!("already up to date ({current})");
        return 0;
    }
    println!("updating {current} -> {latest}");

    // 2. Find the zip asset (stable name uploaded by release.yml).
    let asset_name = "voli-x64.zip";
    let sha_name = format!("{asset_name}.sha256");
    let mut zip_url = None;
    let mut sha_url = None;
    if let Some(assets) = body["assets"].as_array() {
        for a in assets {
            let name = a["name"].as_str().unwrap_or("");
            let url = a["browser_download_url"].as_str().unwrap_or("");
            if name == asset_name {
                zip_url = Some(url.to_string());
            } else if name == sha_name {
                sha_url = Some(url.to_string());
            }
        }
    }
    let Some(zip_url) = zip_url else {
        eprintln!("error: release {tag} has no {asset_name} asset");
        return EXIT_ERROR;
    };

    // 3. Download the zip.
    println!("downloading {zip_url} ...");
    let zip_resp = match ureq::get(&zip_url)
        .set("User-Agent", concat!("voli/", env!("CARGO_PKG_VERSION")))
        .call()
    {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: download failed: {e}");
            return EXIT_ERROR;
        }
    };
    let mut zip_bytes = Vec::new();
    if let Err(e) = zip_resp.into_reader().read_to_end(&mut zip_bytes) {
        eprintln!("error: reading download: {e}");
        return EXIT_ERROR;
    }

    // 4. Verify sha256 if a checksums asset exists.
    if let Some(sha_url) = sha_url {
        if let Ok(sha_resp) = ureq::get(&sha_url)
            .set("User-Agent", concat!("voli/", env!("CARGO_PKG_VERSION")))
            .call()
        {
            let expected = sha_resp.into_string().unwrap_or_default();
            let expected = expected
                .split_whitespace()
                .next()
                .unwrap_or("")
                .to_ascii_lowercase();
            let actual = hex::encode(Sha256::digest(&zip_bytes));
            if actual != expected {
                eprintln!("error: sha256 mismatch: expected {expected}, got {actual}");
                return EXIT_ERROR;
            }
            println!("sha256 verified");
        }
    } else {
        eprintln!("warning: no .sha256 asset found; skipping hash verification");
    }

    // 5. Extract to temp and swap binaries.
    let td = match tempfile::tempdir() {
        Ok(td) => td,
        Err(e) => {
            eprintln!("error: cannot create temp dir: {e}");
            return EXIT_ERROR;
        }
    };
    let zip_path = td.path().join("release.zip");
    if let Err(e) = std::fs::write(&zip_path, &zip_bytes) {
        eprintln!("error: writing temp zip: {e}");
        return EXIT_ERROR;
    }
    let extract_dir = td.path().join("extracted");
    std::fs::create_dir_all(&extract_dir).ok();
    {
        let file = match std::fs::File::open(&zip_path) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("error: opening zip: {e}");
                return EXIT_ERROR;
            }
        };
        let mut archive = match zip::ZipArchive::new(file) {
            Ok(a) => a,
            Err(e) => {
                eprintln!("error: reading zip: {e}");
                return EXIT_ERROR;
            }
        };
        if let Err(e) = archive.extract(&extract_dir) {
            eprintln!("error: extracting zip: {e}");
            return EXIT_ERROR;
        }
    }

    // 6. Replace binaries in bin\ using the .new/.old rename dance.
    let root = root();
    let bin_dir = root.join("bin");
    let mut updated = Vec::new();
    for name in ["voli.exe", "voli-shim.exe", "voli-shim-gui.exe"] {
        let src = extract_dir.join(name);
        if src.is_file() {
            let dst = bin_dir.join(name);
            if let Err(e) = replace_binary(&src, &dst) {
                eprintln!("error: replacing {name}: {e}");
                return EXIT_ERROR;
            }
            updated.push(name.to_string());
        }
    }

    if updated.is_empty() {
        eprintln!("error: no binaries found in the release archive");
        return EXIT_ERROR;
    }
    println!("updated to {latest}: {}", updated.join(", "));
    0
}

/// Copy `src` over `dst`, coping with a locked running exe (.new/.old dance).
fn replace_binary(src: &Path, dst: &Path) -> std::io::Result<()> {
    let staged = {
        let mut s = dst.as_os_str().to_os_string();
        s.push(".new");
        PathBuf::from(s)
    };
    std::fs::copy(src, &staged)?;
    if dst.exists() {
        if std::fs::rename(&staged, dst).is_ok() {
            return Ok(());
        }
        let old = {
            let mut s = dst.as_os_str().to_os_string();
            s.push(".old");
            PathBuf::from(s)
        };
        let _ = std::fs::remove_file(&old);
        std::fs::rename(dst, &old)?;
        std::fs::rename(&staged, dst)?;
    } else {
        std::fs::rename(&staged, dst)?;
    }
    Ok(())
}

fn cmd_self_uninstall(auto_yes: bool) -> i32 {
    let root = root();
    let paths = Paths::at(&root);

    // Safety rail: refuse if root doesn't look like a voli installation.
    if !root.join("bin").join("voli.exe").exists() || !root.join("db").join("state.sqlite").exists()
    {
        eprintln!(
            "error: {} does not look like a voli root (missing bin\\voli.exe or db\\state.sqlite)",
            root.display()
        );
        eprintln!("refusing to delete a directory that is not a voli installation.");
        return EXIT_ERROR;
    }

    // Gather what will be removed.
    let state = match State::open(&paths.state_db()) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: cannot open state db: {e}");
            return EXIT_ERROR;
        }
    };
    let pkgs: Vec<String> = match state.list() {
        Ok(list) => list
            .iter()
            .filter(|p| p.name != "@voli")
            .map(|p| p.name.clone())
            .collect(),
        Err(e) => {
            eprintln!("error: cannot list packages: {e}");
            return EXIT_ERROR;
        }
    };
    drop(state);

    // Prompt (default NO — the only voli prompt that defaults to no).
    if !auto_yes {
        println!("This will PERMANENTLY remove:");
        println!("  - voli itself (bin, shims, db, cache)");
        if pkgs.is_empty() {
            println!("  - no installed packages");
        } else {
            println!(
                "  - {} installed package(s): {}",
                pkgs.len(),
                pkgs.join(", ")
            );
        }
        println!(
            "  - all persist data, env vars, PATH entries, shortcuts, and Apps & Features keys"
        );
        println!("  - the voli root: {}", root.display());
        println!();
        print!("This cannot be undone. Proceed? [y/N] ");
        use std::io::Write;
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer).ok();
        if !answer.trim().eq_ignore_ascii_case("y") && !answer.trim().eq_ignore_ascii_case("yes") {
            println!("aborted.");
            return 0;
        }
    }

    // 1. Uninstall every package (purge — persist goes too).
    let env_subkey = env_subkey();
    for name in &pkgs {
        match uninstall(name, &root, true) {
            Ok(_) => println!("  uninstalled {name}"),
            Err(e) => eprintln!("  warning: uninstall {name} failed: {e}"),
        }
    }

    // 2. Remove @voli ledger items (PATH entry, self-shim).
    {
        let mut state = match State::open(&paths.state_db()) {
            Ok(s) => s,
            Err(_) => {
                // State db may already be gone; proceed.
                eprintln!("  warning: cannot open state db for @voli cleanup");
                return cleanup_root(&root);
            }
        };
        if let Ok(actions) = state.actions_for("@voli") {
            for a in actions.iter().rev() {
                match a {
                    Action::PathAdded { segment } => {
                        let _ = env::remove_from_path(&env_subkey, segment);
                    }
                    Action::ShimWritten { shim, exe } => {
                        let _ = std::fs::remove_file(shim);
                        let _ = std::fs::remove_file(exe);
                    }
                    _ => {}
                }
            }
        }
        let _ = state.remove_package("@voli");
        env::broadcast_change();
    }

    // 3. Delete everything under root except bin\voli.exe (which is running).
    cleanup_root(&root)
}

/// Remove the entire voli root, deterministically, while we are still running.
///
/// Windows will not DELETE a running exe, but it will happily MOVE one — so we
/// move our own binary out to %TEMP% first, at which point nothing in the root
/// is locked and a plain remove_dir_all wipes it synchronously (no detached
/// helper races, works even under process-tree-killing Job Objects). The moved
/// exe in %TEMP% gets a best-effort background delete; if that dies, a single
/// orphan file in the temp dir is the worst case and the OS cleans temp anyway.
fn cleanup_root(root: &Path) -> i32 {
    // 3a. Move the running exe out of the tree.
    let parked = std::env::temp_dir().join(format!("voli-selfdelete-{}.exe", std::process::id()));
    if let Ok(me) = std::env::current_exe() {
        let _ = std::fs::remove_file(&parked);
        if std::fs::rename(&me, &parked).is_err() {
            // Cross-volume temp (rename can't move a running exe between
            // volumes) — park it inside root's parent instead.
            let fallback = root.with_extension("voli-selfdelete.exe");
            if std::fs::rename(&me, &fallback).is_ok() {
                let _ = std::fs::remove_dir_all(root);
                schedule_temp_delete(&fallback);
                println!();
                println!("voli removed itself. The bear waves goodbye. \u{1F43B}");
                return 0;
            }
            // Can't move at all — extremely unusual; leave bin\voli.exe and
            // tell the user rather than pretending.
            let _ = std::fs::remove_dir_all(root.join("apps"));
            let _ = std::fs::remove_dir_all(root.join("shims"));
            let _ = std::fs::remove_dir_all(root.join("db"));
            let _ = std::fs::remove_dir_all(root.join("cache"));
            let _ = std::fs::remove_file(root.join("config.toml"));
            eprintln!(
                "warning: could not relocate the running voli.exe; delete {} manually.",
                root.display()
            );
            return 0;
        }
    }

    // 3b. Nothing in root is locked now — synchronous, verifiable removal.
    if let Err(e) = std::fs::remove_dir_all(root) {
        eprintln!("warning: could not fully remove {}: {e}", root.display());
    }

    // 3c. Best-effort background delete of the parked exe after we exit.
    schedule_temp_delete(&parked);

    println!();
    println!("voli removed itself. The bear waves goodbye. \u{1F43B}");
    0
}

/// Best-effort detached delete of the parked (still-running) exe copy.
/// Breakaway first so tree-killing Job Objects don't reap the helper; if even
/// that dies, one orphan file in %TEMP% is the accepted worst case.
fn schedule_temp_delete(parked: &Path) {
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        const DETACHED_PROCESS: u32 = 0x0000_0008;
        const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
        let target = parked.to_string_lossy().replace('/', "\\");
        let cmd = format!(
            "for /l %n in (1,1,15) do (del /f /q \"{target}\" 2>nul & \
             if not exist \"{target}\" exit 0 & ping -n 2 127.0.0.1 >nul)"
        );
        let spawn = |flags: u32| {
            std::process::Command::new("cmd")
                .args(["/c", &cmd])
                .creation_flags(flags)
                .spawn()
        };
        if spawn(CREATE_NO_WINDOW | DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB).is_err() {
            let _ = spawn(CREATE_NO_WINDOW | DETACHED_PROCESS);
        }
    }
    #[cfg(not(windows))]
    {
        let _ = std::fs::remove_file(parked);
    }
}

fn cmd_config(action: &ConfigAction, json: bool) -> i32 {
    match action {
        ConfigAction::Get { key } => cmd_config_get(key, json),
        ConfigAction::Set { key, value } => cmd_config_set(key, value),
    }
}

/// Path of the config file that owns `key`: `root` lives in the bootstrap
/// config, everything else in `<root>\config.toml`.
fn config_file_for(key: &str) -> Option<PathBuf> {
    if key == "root" {
        config::bootstrap_config_path()
    } else {
        Some(root().join("config.toml"))
    }
}

fn cmd_config_get(key: &str, json: bool) -> i32 {
    if key != "root" && key != "index_url" {
        eprintln!("error: unknown config key '{key}' (known: root, index_url)");
        return EXIT_ERROR;
    }
    let Some(path) = config_file_for(key) else {
        eprintln!("error: cannot locate config file for '{key}'");
        return EXIT_ERROR;
    };
    let value = config::Config::load(&path).get(key);
    if json {
        println!("{}", serde_json::json!({ "key": key, "value": value }));
    } else {
        match value {
            Some(v) => println!("{v}"),
            None => println!("(unset)"),
        }
    }
    0
}

fn cmd_config_set(key: &str, value: &str) -> i32 {
    if key != "root" && key != "index_url" {
        eprintln!("error: unknown config key '{key}' (known: root, index_url)");
        return EXIT_ERROR;
    }
    if key == "root"
        && let Some(provider) = config::synced_provider(Path::new(value))
    {
        eprintln!(
            "warning: '{value}' looks like a {provider} sync folder; running exes from \
             synced folders is unreliable (spec §3). Prefer a local disk path."
        );
    }
    let Some(path) = config_file_for(key) else {
        eprintln!("error: cannot locate config file for '{key}'");
        return EXIT_ERROR;
    };
    match config::set_raw(&path, key, value) {
        Ok(()) => {
            println!("set {key} = {value}");
            if key == "root" {
                println!(
                    "  (takes effect on next run; bootstrap: {})",
                    path.display()
                );
            }
            0
        }
        Err(e) => {
            eprintln!("error: could not write {}: {e}", path.display());
            EXIT_ERROR
        }
    }
}

#[derive(Clone, Copy, PartialEq)]
enum Status {
    Pass,
    Warn,
    Fail,
}

impl Status {
    fn label(self) -> &'static str {
        match self {
            Status::Pass => "PASS",
            Status::Warn => "WARN",
            Status::Fail => "FAIL",
        }
    }
}

struct Check {
    status: Status,
    name: String,
    detail: String,
}

fn cmd_doctor(json: bool) -> i32 {
    let root = root();
    let paths = Paths::at(&root);
    let env_subkey = env_subkey();

    let mut checks: Vec<Check> = Vec::new();
    let mut add = |status, name: &str, detail: String| {
        checks.push(Check {
            status,
            name: name.to_string(),
            detail,
        })
    };

    // 1. shims dir on user PATH?
    let shims = paths.shims();
    let shims_str = shims.to_string_lossy().into_owned();
    match env::get(&env_subkey, "Path") {
        Ok(path) => {
            let present = path
                .as_deref()
                .map(|p| env::path_has_segment(p, &shims_str))
                .unwrap_or(false);
            if present {
                add(Status::Pass, "shims on PATH", shims_str.clone());
            } else {
                add(
                    Status::Fail,
                    "shims on PATH",
                    format!("{shims_str} is not on your user PATH (run `voli setup`)"),
                );
            }
        }
        Err(e) => add(
            Status::Fail,
            "shims on PATH",
            format!("cannot read PATH: {e}"),
        ),
    }

    // 2. bin dir + binaries present?
    let bin = root.join("bin");
    let missing: Vec<&str> = ["voli.exe", "voli-shim.exe", "voli-shim-gui.exe"]
        .into_iter()
        .filter(|b| !bin.join(b).is_file())
        .collect();
    if !bin.is_dir() {
        add(
            Status::Fail,
            "bin dir",
            format!("{} does not exist (run `voli setup`)", bin.display()),
        );
    } else if missing.is_empty() {
        add(Status::Pass, "bin binaries", bin.display().to_string());
    } else {
        add(
            Status::Fail,
            "bin binaries",
            format!("missing in {}: {}", bin.display(), missing.join(", ")),
        );
    }

    // 3. root on a synced folder?
    match config::synced_provider(&root) {
        Some(provider) => add(
            Status::Warn,
            "root location",
            format!("{} looks like a {provider} sync folder", root.display()),
        ),
        None => add(Status::Pass, "root location", root.display().to_string()),
    }

    // 4. state db openable?
    let state = match State::open(&paths.state_db()) {
        Ok(s) => {
            add(
                Status::Pass,
                "state db",
                paths.state_db().display().to_string(),
            );
            Some(s)
        }
        Err(e) => {
            add(Status::Fail, "state db", format!("cannot open: {e}"));
            None
        }
    };

    // 5 + 6. per-package shims, shim targets, and current junctions.
    if let Some(state) = &state {
        match state.list() {
            Ok(pkgs) => {
                for p in &pkgs {
                    if p.name == "@voli" {
                        continue; // synthetic self entry has no shims/junction
                    }
                    check_package(&paths, state, p, &env_subkey, &mut add);
                }
            }
            Err(e) => add(
                Status::Fail,
                "installed packages",
                format!("cannot list: {e}"),
            ),
        }
    }

    // 7. Orphaned Apps & Features keys (key exists but package not in state db).
    {
        let base = voli_core::uninstall_reg::uninstall_base();
        match voli_core::uninstall_reg::list_voli_keys(&base) {
            Ok(keys) => {
                let installed: std::collections::HashSet<String> = state
                    .as_ref()
                    .and_then(|s| s.list().ok())
                    .map(|pkgs| pkgs.into_iter().map(|p| p.name).collect())
                    .unwrap_or_default();
                let orphans: Vec<&String> =
                    keys.iter().filter(|k| !installed.contains(*k)).collect();
                if orphans.is_empty() {
                    add(Status::Pass, "uninstall keys", "no orphans".to_string());
                } else {
                    let names: Vec<&str> = orphans.iter().map(|s| s.as_str()).collect();
                    add(
                        Status::Warn,
                        "uninstall keys",
                        format!("orphaned: {}", names.join(", ")),
                    );
                }
            }
            Err(_) => {
                // Cannot read the key — not fatal.
            }
        }
    }

    let failed = checks.iter().any(|c| c.status == Status::Fail);

    if json {
        let arr: Vec<_> = checks
            .iter()
            .map(|c| {
                serde_json::json!({
                    "status": c.status.label(),
                    "check": c.name,
                    "detail": c.detail,
                })
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "ok": !failed,
                "checks": arr,
            }))
            .unwrap()
        );
    } else {
        for c in &checks {
            println!("[{}] {}{}", c.status.label(), c.name, c.detail);
        }
        println!();
        println!("{}", if failed { "doctor: FAIL" } else { "doctor: OK" });
    }

    if failed { EXIT_ERROR } else { 0 }
}

/// Check one installed package's shims (present + target exists) and its
/// `current` junction (resolves).
fn check_package(
    paths: &Paths,
    state: &State,
    pkg: &voli_core::InstalledPkg,
    env_subkey: &str,
    add: &mut impl FnMut(Status, &str, String),
) {
    use voli_core::Action;

    // current junction must resolve to a real directory.
    let current = paths.current(&pkg.name);
    if current.exists() {
        add(
            Status::Pass,
            "junction",
            format!("{} -> ok", current.display()),
        );
    } else {
        add(
            Status::Fail,
            "junction",
            format!("{} is broken or missing", current.display()),
        );
    }

    let actions = match state.actions_for(&pkg.name) {
        Ok(a) => a,
        Err(e) => {
            add(
                Status::Fail,
                "shims",
                format!("{}: cannot read ledger: {e}", pkg.name),
            );
            return;
        }
    };
    for a in &actions {
        if let Action::ShimWritten { shim, exe } = a {
            if !exe.is_file() {
                add(
                    Status::Fail,
                    "shim",
                    format!("{} missing shim exe {}", pkg.name, exe.display()),
                );
                continue;
            }
            // The .shim file's first line is the real target path.
            let target_ok = std::fs::read_to_string(shim)
                .ok()
                .and_then(|b| b.lines().next().map(|l| l.trim().to_string()))
                .map(|t| Path::new(&t).exists())
                .unwrap_or(false);
            if target_ok {
                add(
                    Status::Pass,
                    "shim",
                    format!("{}: {}", pkg.name, shim.display()),
                );
            } else {
                add(
                    Status::Fail,
                    "shim",
                    format!("{}: target of {} does not exist", pkg.name, shim.display()),
                );
            }
        }
    }

    // Env drift (spec §8): if the live registry value differs from what we set,
    // WARN — never auto-fix (the user may have edited it deliberately).
    for a in &actions {
        if let Action::EnvSet { key, value, .. } = a {
            let current = env::get(env_subkey, key).ok().flatten();
            match current.as_deref() {
                Some(cur) if cur == value => add(
                    Status::Pass,
                    "env",
                    format!("{}: {key} = {value}", pkg.name),
                ),
                Some(cur) => add(
                    Status::Warn,
                    "env drift",
                    format!("{}: {key} is now '{cur}' (voli set '{value}')", pkg.name),
                ),
                None => add(
                    Status::Warn,
                    "env drift",
                    format!("{}: {key} was removed (voli set '{value}')", pkg.name),
                ),
            }
        }
    }
}

fn cmd_which(bin: &str) -> i32 {
    let base = bin.strip_suffix(".exe").unwrap_or(bin);
    let shim = Paths::at(root()).shims().join(format!("{base}.shim"));
    match std::fs::read_to_string(&shim) {
        Ok(body) => {
            // Line 1 of a .shim is the target path (spec §6).
            match body.lines().next() {
                Some(target) if !target.trim().is_empty() => {
                    println!("{}", target.trim());
                    0
                }
                _ => {
                    eprintln!("error: shim {} is empty or malformed", shim.display());
                    EXIT_ERROR
                }
            }
        }
        Err(_) => {
            eprintln!("error: no shim for '{bin}' (looked for {})", shim.display());
            EXIT_ERROR
        }
    }
}