nd300 3.7.0

Cross-platform network diagnostic tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
use crate::config::{Config, OutputFormat};
use crate::render::color;
use std::path::{Path, PathBuf};

use super::{fail_icon, is_interactive, prompt_yes_no, success_icon};

/// Binaries that are part of this package (installed together by cargo-dist).
/// This is the deletion allowlist: `migrate-cleanup` (src/actions/migrate.rs) only
/// ever deletes files whose stem is in this list, so it can never touch
/// `cargo.exe`, `rustup.exe`, or any other binary that shares a directory.
pub(crate) const OUR_BINARIES: &[&str] = &["nd300", "speedqx"];

/// Tracks what we cleaned up for reporting.
pub(crate) struct CleanupReport {
    /// True only when the binary is actually gone now (Unix `remove_file`, or a
    /// non-running sibling delete). On Windows the *running* exe can't be deleted
    /// in place, so this stays false even on a successful uninstall — see
    /// `binary_removal_scheduled`.
    pub(crate) binary_removed: bool,
    /// Windows-only: the running exe couldn't be removed now, but a background
    /// trusted PowerShell retry helper was successfully spawned to delete it
    /// once this process exits. Kept distinct from `binary_removed` so the
    /// updater's shadow-cleanup guard can tell "already gone" from "scheduled
    /// for removal on exit" and not be silently defeated by an optimistic
    /// "removed".
    pub(crate) binary_removal_scheduled: bool,
    /// Unix symlink invocation: only the link was removed; the underlying
    /// package-manager/Cargo/archive target remains installed.
    pub(crate) target_retained: bool,
    /// True when a present allowlisted sibling was removed synchronously.
    pub(crate) sibling_removed: bool,
    /// Windows-only: at least one present allowlisted sibling was locked, but a
    /// trusted delayed-delete helper was started for it successfully.
    pub(crate) sibling_removal_scheduled: bool,
    /// At least one present allowlisted sibling could neither be removed now
    /// nor scheduled for trusted delayed deletion. This is kept internal so the
    /// public JSON schema remains stable while pair cleanup is classified
    /// honestly.
    pub(crate) sibling_removal_failed: bool,
    pub(crate) receipt_removed: bool,
    pub(crate) path_cleaned: bool,
    pub(crate) notes: Vec<String>,
}

pub async fn run(config: &Config) -> i32 {
    let exe_path = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            if config.format == OutputFormat::Json {
                let output = serde_json::json!({
                    "action": "uninstall",
                    "success": false,
                    "message": format!("Could not determine binary location: {}", e),
                });
                println!(
                    "{}",
                    serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_string())
                );
            } else {
                println!(
                    "  {} {}",
                    color::red(fail_icon(config), config),
                    color::red(
                        &format!("Could not determine binary location: {}", e),
                        config
                    ),
                );
            }
            return 2;
        }
    };

    // Resolve symlinks to get the real path
    let real_path = match exe_path.canonicalize() {
        Ok(p) => p,
        Err(_) => exe_path.clone(),
    };

    if config.format == OutputFormat::Json {
        return run_json(&real_path, config).await;
    }

    println!();
    #[cfg(unix)]
    print_unix_uninstall_preview(&real_path, config);
    #[cfg(windows)]
    match super::update::registered_install_owner(&real_path) {
        Some(owner) => println!(
            "  This will start the registered {} uninstaller for: {}",
            owner.origin.json_id(),
            color::cyan(&owner.install_location.display().to_string(), config),
        ),
        None => println!(
            "  This will remove nd300 and speedqx from: {}",
            color::cyan(
                &real_path
                    .parent()
                    .unwrap_or(&real_path)
                    .display()
                    .to_string(),
                config
            ),
        ),
    }

    // Show what we'll clean up
    let receipt_dir = get_receipt_dir();
    #[cfg(unix)]
    let show_receipt = unix_uninstall_cleans_receipt();
    #[cfg(windows)]
    let show_receipt = true;
    if let Some(ref dir) = receipt_dir {
        if show_receipt && dir.exists() {
            println!(
                "  Config/receipt directory:    {}",
                color::cyan(&dir.display().to_string(), config),
            );
        }
    }

    #[cfg(windows)]
    {
        let bin_dir = real_path.parent().map(|p| p.to_path_buf());
        if let Some(ref dir) = bin_dir {
            if is_sole_package_in_dir(dir) {
                println!(
                    "  PATH entry to clean:        {}",
                    color::cyan(&dir.display().to_string(), config),
                );
            }
        }
    }

    println!();

    if is_interactive(config) {
        #[cfg(unix)]
        let prompt = "  Proceed with this origin-aware uninstall? (y/N): ";
        #[cfg(windows)]
        let prompt = "  Are you sure you want to uninstall nd300 and speedqx? (y/N): ";
        if !prompt_yes_no(prompt) {
            println!("  Uninstall cancelled.");
            return 0;
        }
        println!();
    }

    let report = execute_uninstall(&real_path).await;

    // Print results
    if report.target_retained {
        print_ok(
            "Invocation symlink removed; target installation retained",
            config,
        );
    } else if report.binary_removed {
        print_ok("nd300 binary removed", config);
    } else if report.binary_removal_scheduled {
        // Windows: the running exe is deleted by the spawned helper once we exit.
        print_ok(
            "nd300 binary scheduled for removal (completes when this process exits)",
            config,
        );
    } else {
        print_fail("Failed to remove nd300 binary", config);
    }

    if report.sibling_removed {
        print_ok("speedqx binary removed", config);
    } else if report.sibling_removal_scheduled {
        print_ok(
            "speedqx binary scheduled for removal (completes after its process exits)",
            config,
        );
    } else if report.sibling_removal_failed {
        print_fail("Failed to remove speedqx binary", config);
    }

    if report.receipt_removed {
        print_ok("Install receipt cleaned up", config);
    }

    if report.path_cleaned {
        print_ok("PATH entry removed", config);
    }

    for note in &report.notes {
        println!("  {}", color::dim(note, config));
    }

    println!();
    if report.target_retained {
        println!(
            "  {} {}",
            color::green(success_icon(config), config),
            color::green(
                "Invocation symlink removed; ND300 remains installed",
                config
            ),
        );
        0
    } else if !report.sibling_removal_failed
        && (report.binary_removed || report.binary_removal_scheduled)
    {
        println!(
            "  {} {}",
            color::green(success_icon(config), config),
            color::green("nd300 and speedqx have been uninstalled", config),
        );
        0
    } else {
        println!(
            "  {} {}",
            color::red(fail_icon(config), config),
            color::red("Uninstall incomplete — could not remove binary", config),
        );
        2
    }
}

#[cfg(unix)]
fn unix_uninstall_cleans_receipt() -> bool {
    use super::unix_install::UnixOriginKind;
    let Ok(user) = crate::platform::invoking_user::InvokingUser::detect() else {
        return false;
    };
    super::unix_install::detect_origin(&user)
        .ok()
        .is_some_and(|origin| {
            matches!(
                origin.kind,
                UnixOriginKind::Cargo | UnixOriginKind::ManagedArchive | UnixOriginKind::MacPackage
            ) && (origin.kind == UnixOriginKind::MacPackage
                || super::unix_install::cargo_dist_receipt_valid(&user))
        })
}

#[cfg(unix)]
fn print_unix_uninstall_preview(real_path: &Path, config: &Config) {
    use super::unix_install::UnixOriginKind;

    let origin = crate::platform::invoking_user::InvokingUser::detect()
        .ok()
        .and_then(|user| super::unix_install::detect_origin(&user).ok());
    match origin {
        Some(origin) if origin.kind == UnixOriginKind::Symlink => {
            let link = origin.invocation_symlink.as_deref().unwrap_or(real_path);
            println!(
                "  This will remove only the invocation symlink: {}",
                color::cyan(&link.display().to_string(), config)
            );
            println!("  The target installation will remain intact.");
        }
        Some(origin) if origin.kind == UnixOriginKind::Cargo => println!(
            "  This will run `cargo uninstall nd300` for: {}",
            color::cyan(&origin.executable.display().to_string(), config)
        ),
        Some(origin) if origin.kind == UnixOriginKind::ManagedArchive => println!(
            "  This will remove the validated ND300 archive install from: {}",
            color::cyan(
                &origin
                    .executable
                    .parent()
                    .unwrap_or(&origin.executable)
                    .display()
                    .to_string(),
                config
            )
        ),
        Some(origin) if origin.kind == UnixOriginKind::MacPackage => println!(
            "  This will request Apple authorization, remove the receipt-owned system pair, and forget com.qubetx.nd300.pkg: {}",
            color::cyan(&origin.executable.display().to_string(), config)
        ),
        Some(origin) => println!(
            "  ND300 will inspect and refuse this {} installation unless its original manager removes it: {}",
            match origin.kind {
                UnixOriginKind::PackageManager => "package-manager-owned",
                UnixOriginKind::LocalBuild => "local-build",
                UnixOriginKind::MacPackage => "Apple-Installer-owned",
                _ => "unknown",
            },
            color::cyan(&origin.executable.display().to_string(), config)
        ),
        None => println!(
            "  ND300 could not validate the install origin and will refuse removal: {}",
            color::cyan(&real_path.display().to_string(), config)
        ),
    }
}

async fn run_json(exe_path: &Path, _config: &Config) -> i32 {
    let report = execute_uninstall(exe_path).await;

    // `binary_removed` stays a literal "is it gone right now?" so existing
    // scripts read the same field; `success` and the exit code also accept a
    // Windows scheduled removal or a Unix symlink-only removal.
    let succeeded = !report.sibling_removal_failed
        && (report.binary_removed || report.binary_removal_scheduled || report.target_retained);
    let output = serde_json::json!({
        "action": "uninstall",
        "success": succeeded,
        "binary_removed": report.binary_removed,
        "binary_removal_scheduled": report.binary_removal_scheduled,
        "sibling_removed": report.sibling_removed,
        "receipt_removed": report.receipt_removed,
        "path_cleaned": report.path_cleaned,
        "notes": report.notes,
        "path": exe_path.display().to_string(),
    });
    println!(
        "{}",
        serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_string())
    );

    if succeeded {
        0
    } else {
        2
    }
}

async fn execute_uninstall(_exe_path: &Path) -> CleanupReport {
    #[cfg(unix)]
    {
        let user = match crate::platform::invoking_user::InvokingUser::detect() {
            Ok(user) => user,
            Err(error) => {
                return CleanupReport {
                    binary_removed: false,
                    binary_removal_scheduled: false,
                    target_retained: false,
                    sibling_removed: false,
                    sibling_removal_scheduled: false,
                    sibling_removal_failed: false,
                    receipt_removed: false,
                    path_cleaned: false,
                    notes: vec![format!("Could not identify invoking user: {error}")],
                };
            }
        };
        super::unix_install::uninstall_detected(&user).await
    }

    #[cfg(windows)]
    {
        if let Some(owner) = super::update::registered_install_owner(_exe_path) {
            uninstall_registered_owner(&owner)
        } else {
            uninstall_path(_exe_path)
        }
    }
}

/// Launch the registry-proven MSI/Inno owner directly, without passing its raw
/// registry command through cmd.exe or PowerShell. The current process returns
/// immediately so the official uninstaller can remove the running executable,
/// its sibling, ARP registration, the correct PATH hive, and InstallSource
/// marker together.
#[cfg(windows)]
fn uninstall_registered_owner(owner: &super::update::RegisteredInstallOwner) -> CleanupReport {
    use super::update::{InstallOrigin, RegisteredUninstall};

    let mut report = empty_cleanup_report();
    let command: Result<(PathBuf, Vec<String>), String> = match &owner.uninstall {
        RegisteredUninstall::Msi { product_code } => system_msiexec_path().map(|program| {
            (
                program,
                vec![
                    "/x".to_string(),
                    product_code.clone(),
                    "/passive".to_string(),
                    "/norestart".to_string(),
                ],
            )
        }),
        RegisteredUninstall::Inno { executable } => Ok((
            executable.clone(),
            vec![
                "/VERYSILENT".to_string(),
                "/SUPPRESSMSGBOXES".to_string(),
                "/NORESTART".to_string(),
                "/SP-".to_string(),
            ],
        )),
    };
    let (program, args) = match command {
        Ok(command) => command,
        Err(error) => {
            report.notes.push(error);
            return report;
        }
    };

    let needs_elevation = matches!(
        owner.origin,
        InstallOrigin::MsiGlobal | InstallOrigin::ExeGlobal
    );
    let launch = if needs_elevation {
        shell_execute_elevated(&program, &args)
    } else {
        spawn_uninstaller(&program, &args)
    };

    match launch {
        Ok(()) => {
            report.binary_removal_scheduled = true;
            report.notes.push(format!(
                "Registered {} uninstaller started; binaries, registration, PATH, and installer marker are removed after this process exits",
                owner.origin.json_id()
            ));
            if let Some(receipt_dir) = get_receipt_dir() {
                if receipt_dir.exists() {
                    match std::fs::remove_dir_all(&receipt_dir) {
                        Ok(()) => report.receipt_removed = true,
                        Err(error) => report.notes.push(format!(
                            "Could not remove receipt dir {}: {}",
                            receipt_dir.display(),
                            error
                        )),
                    }
                }
            }
        }
        Err(error) => report
            .notes
            .push(format!("Could not start registered uninstaller: {error}")),
    }
    report
}

/// Resolve a trusted Windows system executable from the kernel-provided system
/// directory instead of PATH or the current working directory.
#[cfg(windows)]
pub(crate) fn system_executable_path(relative_path: &Path) -> Result<PathBuf, String> {
    use std::os::windows::ffi::OsStringExt;
    use winapi::um::sysinfoapi::GetSystemDirectoryW;

    // System directories are bounded well below the extended Windows path
    // ceiling. A large fixed buffer also avoids trusting mutable environment
    // variables such as SystemRoot.
    let mut buffer = vec![0_u16; 32_768];
    // SAFETY: `buffer` is writable for exactly the capacity passed to Win32.
    let length = unsafe { GetSystemDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) };
    if length == 0 {
        return Err(format!(
            "Could not resolve the trusted Windows system directory: {}",
            std::io::Error::last_os_error()
        ));
    }
    let length = length as usize;
    if length >= buffer.len() {
        return Err("Windows system directory exceeded the trusted path buffer".to_string());
    }

    let system_dir = PathBuf::from(std::ffi::OsString::from_wide(&buffer[..length]));
    let executable = system_dir.join(relative_path);
    if !system_dir.is_absolute() || !executable.is_file() {
        return Err(format!(
            "Trusted Windows system executable was not found at {}",
            executable.display()
        ));
    }
    Ok(executable)
}

/// A bare `msiexec.exe` passed to ShellExecuteW(`runas`) would permit
/// executable-search hijacking before the user approves elevation.
#[cfg(windows)]
pub(crate) fn system_msiexec_path() -> Result<PathBuf, String> {
    system_executable_path(Path::new("msiexec.exe"))
}

#[cfg(windows)]
pub(crate) fn system_powershell_path() -> Result<PathBuf, String> {
    system_executable_path(Path::new("WindowsPowerShell\\v1.0\\powershell.exe"))
}

#[cfg(windows)]
fn spawn_uninstaller(program: &Path, args: &[String]) -> Result<(), String> {
    std::process::Command::new(program)
        .args(args)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map(|_| ())
        .map_err(|error| format!("{}: {}", program.display(), error))
}

#[cfg(windows)]
fn shell_execute_elevated(program: &Path, args: &[String]) -> Result<(), String> {
    use std::os::windows::ffi::OsStrExt;
    use winapi::um::shellapi::ShellExecuteW;
    use winapi::um::winuser::SW_SHOWNORMAL;

    let wide = |value: &std::ffi::OsStr| {
        value
            .encode_wide()
            .chain(std::iter::once(0))
            .collect::<Vec<u16>>()
    };
    let verb = wide(std::ffi::OsStr::new("runas"));
    let file = wide(program.as_os_str());
    let parameters = args.join(" ");
    let parameters = wide(std::ffi::OsStr::new(&parameters));
    let directory = program.parent().filter(|path| !path.as_os_str().is_empty());
    let directory_wide = directory.map(|path| wide(path.as_os_str()));
    let directory_ptr = directory_wide
        .as_ref()
        .map_or(std::ptr::null(), |value| value.as_ptr());

    // SAFETY: every pointer references a NUL-terminated UTF-16 buffer that lives
    // through the call. The executable is registry-proven and the arguments are
    // reconstructed from a validated product GUID or fixed Inno flags.
    let result = unsafe {
        ShellExecuteW(
            std::ptr::null_mut(),
            verb.as_ptr(),
            file.as_ptr(),
            parameters.as_ptr(),
            directory_ptr,
            SW_SHOWNORMAL,
        )
    } as isize;
    if result > 32 {
        Ok(())
    } else {
        Err(format!(
            "Windows rejected the elevated uninstall request (ShellExecute code {result})"
        ))
    }
}

#[cfg(windows)]
pub(crate) fn uninstall_path(exe_path: &Path) -> CleanupReport {
    uninstall_path_impl(exe_path, true)
}

/// Advisory installer migration removes only the allowlisted binary pair. It
/// deliberately leaves receipt, PATH, ARP registration, and the shared marker
/// untouched because it runs inside an active installer transaction.
#[cfg(windows)]
pub(crate) fn uninstall_path_files_only(exe_path: &Path) -> CleanupReport {
    uninstall_path_impl(exe_path, false)
}

#[cfg(windows)]
fn empty_cleanup_report() -> CleanupReport {
    CleanupReport {
        binary_removed: false,
        binary_removal_scheduled: false,
        target_retained: false,
        sibling_removed: false,
        sibling_removal_scheduled: false,
        sibling_removal_failed: false,
        receipt_removed: false,
        path_cleaned: false,
        notes: Vec::new(),
    }
}

#[cfg(windows)]
fn uninstall_path_impl(exe_path: &Path, full_cleanup: bool) -> CleanupReport {
    let mut report = empty_cleanup_report();

    // Step 1: Remove the receipt/config directory
    // This is safe to do first since it's nd300-specific
    if full_cleanup {
        if let Some(receipt_dir) = get_receipt_dir() {
            if receipt_dir.exists() {
                match std::fs::remove_dir_all(&receipt_dir) {
                    Ok(_) => report.receipt_removed = true,
                    Err(e) => report.notes.push(format!(
                        "Could not remove receipt dir {}: {}",
                        receipt_dir.display(),
                        e
                    )),
                }
            }
        }
    }

    // Step 2: Remove sibling binaries (speedqx) from the same directory
    if let Some(bin_dir) = exe_path.parent() {
        let exe_name = exe_path
            .file_name()
            .map(|n| n.to_string_lossy().to_lowercase())
            .unwrap_or_default();

        for name in OUR_BINARIES {
            let sibling = if cfg!(windows) {
                bin_dir.join(format!("{}.exe", name))
            } else {
                bin_dir.join(name)
            };

            let sibling_lower = sibling
                .file_name()
                .map(|n| n.to_string_lossy().to_lowercase())
                .unwrap_or_default();

            // Skip the current exe (handled separately in step 4)
            if sibling_lower == exe_name {
                continue;
            }

            if sibling.exists() {
                match std::fs::remove_file(&sibling) {
                    Ok(()) => report.sibling_removed = true,
                    Err(_) if !sibling.exists() => report.sibling_removed = true,
                    Err(error) => {
                        report.notes.push(format!(
                            "Immediate sibling removal was deferred because {}: {}",
                            sibling.display(),
                            error
                        ));
                        match spawn_delayed_delete(&sibling) {
                            Ok(()) => {
                                report.sibling_removal_scheduled = true;
                                report.notes.push(format!(
                                    "Scheduled trusted delayed removal for {}",
                                    sibling.display()
                                ));
                            }
                            Err(schedule_error) => {
                                report.sibling_removal_failed = true;
                                report.notes.push(format!(
                                    "Could not schedule removal for {}: {}",
                                    sibling.display(),
                                    schedule_error
                                ));
                            }
                        }
                    }
                }
            }
        }
    }

    // Keep the primary executable in place when a sibling could not even be
    // scheduled. That preserves a retryable old pair instead of creating the
    // partial state that this helper is intended to prevent.
    if report.sibling_removal_failed {
        report.notes.push(
            "Primary binary retained because its sibling cleanup could not be scheduled"
                .to_string(),
        );
        return report;
    }

    // Step 3: Clean up PATH on Windows
    // Only remove the bin dir from PATH if only our binaries were there
    #[cfg(windows)]
    if full_cleanup {
        let bin_dir = exe_path.parent().map(|p| p.to_path_buf());
        if let Some(ref dir) = bin_dir {
            if is_sole_package_in_dir(dir) {
                match remove_from_user_path(dir) {
                    Ok(true) => report.path_cleaned = true,
                    Ok(false) => {} // wasn't in PATH, nothing to do
                    Err(e) => report.notes.push(format!("Could not clean PATH: {}", e)),
                }
            } else {
                report.notes.push(
                    "Other binaries share the install directory — PATH entry left intact"
                        .to_string(),
                );
            }
        }
    }

    // Step 4: Remove the binary itself (must be last)
    #[cfg(unix)]
    {
        // On Unix, a running binary can be unlinked — the inode persists until exit
        match std::fs::remove_file(exe_path) {
            Ok(_) => report.binary_removed = true,
            Err(e) => report.notes.push(format!("Failed to remove binary: {}", e)),
        }
    }

    #[cfg(windows)]
    {
        // A migration target is normally an old, non-running copy and should be
        // removed synchronously so it cannot win PATH resolution after a fresh
        // installer completes. The top-level uninstall path may instead name
        // this running image; Windows rejects that direct deletion, so retain
        // the trusted retry helper only for the locked-image case. The path
        // travels in an environment variable and is never shell-expanded.
        match std::fs::remove_file(exe_path) {
            Ok(()) => report.binary_removed = true,
            Err(_) if !exe_path.exists() => report.binary_removed = true,
            Err(error) => {
                report.notes.push(format!(
                    "Immediate binary removal was deferred because {}",
                    error
                ));
                match spawn_delayed_delete(exe_path) {
                    Ok(()) => report.binary_removal_scheduled = true,
                    Err(error) => report.notes.push(error),
                }
            }
        }
    }

    report
}

#[cfg(windows)]
pub(crate) fn spawn_delayed_delete(exe_path: &Path) -> Result<(), String> {
    use std::os::windows::process::CommandExt;

    // `cmd /C <script>` has non-C argv parsing: ordinary Command::args quoting
    // can corrupt an embedded quoted path, which left Cargo/portable nd300.exe
    // behind even though the helper reported as spawned. Windows PowerShell
    // accepts a constant command through argv, while the untrusted path is kept
    // entirely out of command text.
    const SCRIPT: &str = "$target=$env:ND300_DELETE_TARGET; for ($i=0; $i -lt 120; $i++) { try { [System.IO.File]::Delete($target) } catch {}; if (-not [System.IO.File]::Exists($target)) { exit 0 }; Start-Sleep -Seconds 1 }; exit 1";
    const CREATE_NO_WINDOW: u32 = 0x0800_0000;

    let powershell = system_powershell_path()?;
    std::process::Command::new(&powershell)
        .args([
            "-NoLogo",
            "-NoProfile",
            "-NonInteractive",
            "-WindowStyle",
            "Hidden",
            "-Command",
            SCRIPT,
        ])
        .env("ND300_DELETE_TARGET", exe_path.as_os_str())
        .creation_flags(CREATE_NO_WINDOW)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map(|_| ())
        .map_err(|error| {
            format!(
                "Failed to spawn trusted delayed-delete helper at {}: {}",
                powershell.display(),
                error
            )
        })
}

fn print_ok(label: &str, config: &Config) {
    println!(
        "  {} {}",
        color::green(success_icon(config), config),
        color::green(label, config),
    );
}

fn print_fail(label: &str, config: &Config) {
    println!(
        "  {} {}",
        color::red(fail_icon(config), config),
        color::red(label, config),
    );
}

/// Get the cargo-dist receipt directory for nd300.
/// - Windows: %LOCALAPPDATA%\nd300
/// - macOS/Linux: ~/.config/nd300  (XDG_CONFIG_HOME respected)
fn get_receipt_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        std::env::var("LOCALAPPDATA")
            .ok()
            .map(|base| PathBuf::from(base).join("nd300"))
    }

    #[cfg(not(windows))]
    {
        crate::platform::invoking_user::InvokingUser::detect()
            .ok()
            .map(|user| {
                let config_home = if !user.is_different_from_effective_user() {
                    std::env::var_os("XDG_CONFIG_HOME")
                        .map(PathBuf::from)
                        .filter(|path| path.is_absolute())
                        .unwrap_or_else(|| user.home().join(".config"))
                } else {
                    user.home().join(".config")
                };
                config_home.join("nd300")
            })
    }
}

/// Check if only our package's binaries (nd300, speedqx) are in the given directory.
/// If other binaries are present (e.g. cargo, rustup), we must NOT remove the
/// directory from PATH — that would break the user's Rust toolchain.
#[cfg(windows)]
pub(crate) fn is_sole_package_in_dir(dir: &Path) -> bool {
    let our_names: Vec<String> = OUR_BINARIES.iter().map(|n| format!("{}.exe", n)).collect();

    match std::fs::read_dir(dir) {
        Ok(entries) => {
            let other_exes: Vec<_> = entries
                .filter_map(|e| e.ok())
                .filter(|e| {
                    let name = e.file_name().to_string_lossy().to_lowercase();
                    name.ends_with(".exe") && !our_names.contains(&name)
                })
                .collect();
            other_exes.is_empty()
        }
        Err(_) => false,
    }
}

/// True if a single PATH entry refers to the same directory as `target`,
/// ignoring surrounding whitespace, ASCII case, and a trailing `\` or `/`.
///
/// Only the comparison is normalized — callers keep the original (untrimmed)
/// slice for any entry they retain, so non-matching paths are never rewritten.
#[cfg(windows)]
fn path_entry_matches_target(entry: &str, target: &str) -> bool {
    let norm = |s: &str| -> String { s.trim().trim_end_matches(['\\', '/']).to_lowercase() };
    let entry_norm = norm(entry);
    // An empty entry (e.g. a stray `;;`) never matches a real target dir.
    !entry_norm.is_empty() && entry_norm == norm(target)
}

/// Remove a directory from the user-level PATH environment variable (Windows registry).
/// Returns Ok(true) if the entry was found and removed, Ok(false) if it wasn't in PATH.
#[cfg(windows)]
fn remove_from_user_path(dir_to_remove: &Path) -> Result<bool, String> {
    use std::process::Command;

    // Read current user PATH from registry
    let output = Command::new("reg")
        .args(["query", "HKCU\\Environment", "/v", "PATH"])
        .output()
        .map_err(|e| format!("Failed to query registry: {}", e))?;

    let text = String::from_utf8_lossy(&output.stdout);
    // Parse the PATH value and its registry type from reg query output
    // Format: "    PATH    REG_EXPAND_SZ    value"
    let (current_path, reg_type) = match text.lines().find(|line| {
        line.contains("PATH") && (line.contains("REG_EXPAND_SZ") || line.contains("REG_SZ"))
    }) {
        Some(line) => {
            if let Some(idx) = line.find("REG_EXPAND_SZ") {
                (
                    line[idx + "REG_EXPAND_SZ".len()..].trim().to_string(),
                    "REG_EXPAND_SZ",
                )
            } else if let Some(idx) = line.find("REG_SZ") {
                (line[idx + "REG_SZ".len()..].trim().to_string(), "REG_SZ")
            } else {
                return Ok(false);
            }
        }
        None => return Ok(false), // No user PATH set
    };

    let dir_str = dir_to_remove.to_string_lossy();
    // Filter out the directory we want to remove. The comparison is
    // case-insensitive AND trailing-slash-insensitive (mirroring `same_path` in
    // update.rs) so a PATH entry with a trailing `\` or `/` still matches and is
    // removed — but we keep the ORIGINAL (untrimmed) slices for any entries we
    // retain, so we never rewrite paths we aren't removing.
    let new_parts: Vec<&str> = current_path
        .split(';')
        .filter(|part| !path_entry_matches_target(part, &dir_str))
        .filter(|part| !part.trim().is_empty())
        .collect();

    let original_count = current_path
        .split(';')
        .filter(|p| !p.trim().is_empty())
        .count();

    if new_parts.len() == original_count {
        return Ok(false); // Directory wasn't in PATH
    }

    let new_path = new_parts.join(";");

    // Write updated PATH back to registry
    let status = Command::new("reg")
        .args([
            "add",
            "HKCU\\Environment",
            "/v",
            "PATH",
            "/t",
            reg_type,
            "/d",
            &new_path,
            "/f",
        ])
        .output()
        .map_err(|e| format!("Failed to update registry: {}", e))?;

    if status.status.success() {
        // Broadcast WM_SETTINGCHANGE so Explorer picks up the change
        let _ = Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                "Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition '[DllImport(\"user32.dll\", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'; $HWND_BROADCAST = [IntPtr]0xffff; $WM_SETTINGCHANGE = 0x1a; $result = [UIntPtr]::Zero; [Win32.NativeMethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)",
            ])
            .output();
        Ok(true)
    } else {
        Err("Failed to write updated PATH to registry".to_string())
    }
}

#[cfg(test)]
mod tests {
    #[cfg(windows)]
    use super::*;

    // ── L3: PATH-entry matching ignores case, whitespace, and trailing slash ──
    #[cfg(windows)]
    #[test]
    fn path_entry_matches_target_variants() {
        let target = r"C:\x\bin";

        // Exact, trailing-backslash, trailing-forward-slash, mixed case, and
        // surrounding whitespace all match.
        assert!(path_entry_matches_target(r"C:\x\bin", target));
        assert!(path_entry_matches_target(r"C:\x\bin\", target));
        assert!(path_entry_matches_target("C:\\x\\bin/", target));
        assert!(path_entry_matches_target(r"c:\X\BIN", target));
        assert!(path_entry_matches_target("  C:\\x\\bin\\  ", target));
        assert!(path_entry_matches_target(r"C:\x\bin//", target));

        // A trailing slash on the TARGET side is normalized too.
        assert!(path_entry_matches_target(r"C:\x\bin", r"C:\x\bin\"));

        // A different (longer) directory must NOT match.
        assert!(!path_entry_matches_target(r"C:\x\bingo", target));
        assert!(!path_entry_matches_target(r"C:\x", target));
        assert!(!path_entry_matches_target("", target));
        assert!(!path_entry_matches_target("   ", target));
    }

    #[cfg(windows)]
    #[test]
    fn msi_uninstall_resolves_an_absolute_system_executable() {
        let msiexec = system_msiexec_path().expect("Windows Installer must exist in System32");
        assert!(msiexec.is_absolute());
        assert!(msiexec.is_file());
        assert_eq!(
            msiexec
                .file_name()
                .and_then(|name| name.to_str())
                .map(str::to_ascii_lowercase)
                .as_deref(),
            Some("msiexec.exe"),
        );
    }

    // ── L4: delayed-delete helper is trusted and survives image locks ─────────
    #[cfg(windows)]
    #[test]
    fn delayed_delete_resolves_an_absolute_system_powershell() {
        let powershell =
            system_powershell_path().expect("Windows PowerShell must exist below System32");
        assert!(powershell.is_absolute());
        assert!(powershell.is_file());
        assert_eq!(
            powershell
                .file_name()
                .and_then(|name| name.to_str())
                .map(str::to_ascii_lowercase)
                .as_deref(),
            Some("powershell.exe"),
        );
    }

    #[cfg(windows)]
    #[test]
    fn files_only_cleanup_removes_a_non_running_pair_synchronously() {
        use std::time::{SystemTime, UNIX_EPOCH};

        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock after epoch")
            .as_nanos();
        let directory = std::env::temp_dir().join(format!(
            "nd300-synchronous-cleanup-{}-{nonce}",
            std::process::id()
        ));
        std::fs::create_dir(&directory).expect("create cleanup fixture directory");
        let nd300 = directory.join("nd300.exe");
        let speedqx = directory.join("speedqx.exe");
        std::fs::write(&nd300, b"old nd300").expect("create old nd300");
        std::fs::write(&speedqx, b"old speedqx").expect("create old speedqx");

        let report = uninstall_path_files_only(&nd300);

        assert!(report.binary_removed, "{:#?}", report.notes);
        assert!(!report.binary_removal_scheduled, "{:#?}", report.notes);
        assert!(report.sibling_removed, "{:#?}", report.notes);
        assert!(!nd300.exists());
        assert!(!speedqx.exists());
        std::fs::remove_dir(&directory).expect("remove cleanup fixture directory");
    }

    #[cfg(windows)]
    #[test]
    fn files_only_cleanup_reports_a_locked_sibling_as_scheduled() {
        use crate::actions::update::{classify_shadow_cleanup, ShadowCleanupDecision};
        use std::os::windows::fs::OpenOptionsExt;
        use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock after epoch")
            .as_nanos();
        let directory = std::env::temp_dir().join(format!(
            "nd300-locked-sibling-cleanup-{}-{nonce}",
            std::process::id()
        ));
        std::fs::create_dir(&directory).expect("create cleanup fixture directory");
        let nd300 = directory.join("nd300.exe");
        let speedqx = directory.join("speedqx.exe");
        std::fs::write(&nd300, b"old nd300").expect("create old nd300");
        std::fs::write(&speedqx, b"old speedqx").expect("create old speedqx");
        let speedqx_lock = std::fs::OpenOptions::new()
            .read(true)
            .share_mode(0)
            .open(&speedqx)
            .expect("open speedqx without delete sharing");

        let report = uninstall_path_files_only(&nd300);

        assert!(report.binary_removed, "{:#?}", report.notes);
        assert!(!report.sibling_removed, "{:#?}", report.notes);
        assert!(report.sibling_removal_scheduled, "{:#?}", report.notes);
        assert!(!report.sibling_removal_failed, "{:#?}", report.notes);
        assert_eq!(
            classify_shadow_cleanup(&report),
            ShadowCleanupDecision::Scheduled,
            "a still-present sibling must never classify as Removed"
        );
        assert!(!nd300.exists());
        assert!(speedqx.exists());

        drop(speedqx_lock);
        let deadline = Instant::now() + Duration::from_secs(15);
        while speedqx.exists() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(100));
        }
        assert!(
            !speedqx.exists(),
            "trusted helper did not remove the released sibling"
        );
        std::fs::remove_dir(&directory).expect("remove cleanup fixture directory");
    }

    #[cfg(windows)]
    #[test]
    fn delayed_delete_retries_until_a_locked_file_is_released() {
        use std::os::windows::fs::OpenOptionsExt;
        use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock after epoch")
            .as_nanos();
        let path = std::env::temp_dir().join(format!(
            "nd300-delayed-delete-{}-{nonce}.exe",
            std::process::id()
        ));
        std::fs::write(&path, b"locked test file").expect("create locked test file");
        let lock = std::fs::OpenOptions::new()
            .read(true)
            .share_mode(0)
            .open(&path)
            .expect("open test file without delete sharing");

        let canonical_path = path.canonicalize().expect("canonicalize locked test file");
        spawn_delayed_delete(&canonical_path).expect("spawn delayed-delete helper");
        std::thread::sleep(Duration::from_secs(2));
        assert!(
            path.exists(),
            "helper must not claim a locked file was deleted"
        );
        drop(lock);

        let deadline = Instant::now() + Duration::from_secs(15);
        while path.exists() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(100));
        }
        assert!(!path.exists(), "helper did not delete the released file");
    }
}