shun 0.2.15

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

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

use walkdir::WalkDir;

use crate::config::InstallConfig;
use crate::error::ShunError;
use crate::flow::{Flow, FlowEvent};
// Only the Windows registration streams warning records; the import
// would be unused (and fatal under -D warnings) on other targets.
#[cfg(windows)]
use crate::flow::FlowLog;
use crate::payload::{MANIFEST_PATH, PayloadEntry, PayloadSource};

/// Marker file enabling portable (便捷) mode for a delivered copy.
pub const PORTABLE_MARKER: &str = ".shun-portable";

/// Name of the uninstaller binary copied into the install directory.
#[cfg(windows)]
pub const UNINSTALLER_NAME: &str = "uninstall.exe";
/// Name of the uninstaller binary copied into the install directory.
#[cfg(not(windows))]
pub const UNINSTALLER_NAME: &str = "uninstall";

/// A context-menu verb the registration backends expose on the app's
/// launchers (Explorer verbs on Windows, Desktop Actions on Linux).
#[derive(Debug, Clone, PartialEq)]
pub struct VerbSpec {
    /// Stable verb id — the registry segment / desktop-action id.
    pub key: String,

    /// Display string shown in the menu.
    pub display: String,

    /// What the verb invokes.
    pub target: VerbTarget,
}

/// What a context-menu verb invokes.
#[derive(Debug, Clone, PartialEq)]
pub enum VerbTarget {
    /// Open the install directory in the file manager.
    DataFolder,
    /// Run the copied uninstaller.
    Uninstall,
    /// Launch the app entry point with extra arguments.
    App { arguments: String },
}

/// Where the install lands: per-user (the default — HKCU / `~/.local` /
/// `~/Applications`, no elevation) or machine-wide (Windows: HKLM,
/// all-users Start Menu, public desktop; the shell self-elevates).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InstallScope {
    /// Per-user surfaces only (the default).
    #[default]
    User,
    /// Machine-wide surfaces (Windows-only today).
    Machine,
}

/// The wizard's answers to the `ask` policies, consumed by
/// [`InstallContext::apply_config`].
#[derive(Debug, Clone, Copy, Default)]
pub struct WizardAnswers {
    /// The desktop-shortcut checkbox (`ask` policy; default checked).
    pub desktop_shortcut: bool,
    /// The start-menu-shortcut checkbox (`ask` policy; default checked).
    pub start_menu_shortcut: bool,
    /// The machine-scope choice (`ask` policy; default per-user).
    pub machine: bool,
    /// The launch-after-install checkbox (`ask` policy; default checked —
    /// the NSIS done-page convention).
    pub launch_after_install: bool,
}

impl WizardAnswers {
    /// The default-checked answers (headless runs): desktop and
    /// start-menu shortcuts on, per-user scope, launch after install on.
    pub fn defaults() -> Self {
        Self {
            desktop_shortcut: true,
            start_menu_shortcut: true,
            machine: false,
            launch_after_install: true,
        }
    }
}

impl From<&crate::config::VerbConfig> for VerbSpec {
    fn from(config: &crate::config::VerbConfig) -> Self {
        use crate::config::VerbConfig;
        match config {
            VerbConfig::DataFolder { key, display } => Self {
                key: key.clone(),
                display: display.clone(),
                target: VerbTarget::DataFolder,
            },
            VerbConfig::Uninstall { key, display } => Self {
                key: key.clone(),
                display: display.clone(),
                target: VerbTarget::Uninstall,
            },
            VerbConfig::App {
                key,
                display,
                arguments,
            } => Self {
                key: key.clone(),
                display: display.clone(),
                target: VerbTarget::App {
                    arguments: arguments.clone(),
                },
            },
        }
    }
}

/// Where and how an install-mode delivery lands on this machine.
#[derive(Debug, Clone, PartialEq)]
pub struct InstallContext {
    /// Product name (shortcut titles, ARP display name, registry key).
    pub product: String,

    /// Product version (ARP display version).
    pub version: String,

    /// Publisher shown in ARP (e.g. `celestia-island`).
    pub publisher: Option<String>,

    /// Final directory of the installed payload.
    pub install_dir: PathBuf,

    /// Payload-relative path of the app entry point the shortcut targets.
    pub main_exe: Option<PathBuf>,

    /// Portable mode: skip registry, shortcuts, and uninstaller entirely;
    /// all data stays beside the executable.
    pub portable: bool,

    /// Marker file name written into the install directory for portable
    /// copies (config `portable-marker`, default `.shun-portable`).
    pub portable_marker: String,

    /// Where the install lands (per-user default; machine-wide writes
    /// HKLM and all-users surfaces and needs elevation).
    pub scope: InstallScope,

    /// Create a desktop shortcut beside the start-menu one (local mode).
    pub desktop_shortcut: bool,

    /// Create the start-menu launcher (local mode).
    pub start_menu_shortcut: bool,

    /// Launch the installed application once the install succeeded — see
    /// [`launch`]. Resolved from `install.launch-after-install`.
    pub launch_after_install: bool,

    /// Context-menu verbs to register (local mode).
    pub verbs: Vec<VerbSpec>,

    /// URL schemes the app owns (`myapp://…`), registered as protocol
    /// handlers (local mode).
    pub deep_links: Vec<String>,

    /// Grouping identity stamped on the shortcuts (Windows
    /// `System.AppUserModel.ID`); the app should pass the same value to
    /// `SetCurrentProcessExplicitAppUserModelID`.
    pub aumid: Option<String>,

    /// Payload-relative icon file the Linux launcher references.
    pub icon: Option<PathBuf>,

    /// ARP `EstimatedSize` in KiB; computed by the flow from the manifest.
    pub estimated_size_kb: u32,
}

impl InstallContext {
    /// A context with the identity fields set and every registration
    /// knob at its no-op default (no desktop shortcut, no launch after
    /// install, no verbs, no icon; the start-menu launcher is on — the
    /// historical behavior for hand-built contexts; the flow fills
    /// `estimated_size_kb`). Chain [`Self::apply_config`] to resolve the
    /// config-declared knobs.
    pub fn new(product: String, version: String, install_dir: PathBuf, portable: bool) -> Self {
        Self {
            product,
            version,
            publisher: None,
            install_dir,
            main_exe: None,
            portable,
            portable_marker: PORTABLE_MARKER.to_string(),
            scope: InstallScope::User,
            desktop_shortcut: false,
            start_menu_shortcut: true,
            launch_after_install: false,
            verbs: Vec::new(),
            deep_links: Vec::new(),
            aumid: None,
            icon: None,
            estimated_size_kb: 0,
        }
    }

    /// Applies the install-target configuration knobs onto a context:
    /// the desktop- and start-menu-shortcut, launch-after-install and
    /// install-scope policies resolved against the wizard answers (`ask`
    /// consults them; headless runs pass [`WizardAnswers::defaults`]),
    /// the context-menu verbs, the deep-link schemes, the AUMID, and the
    /// launcher icon.
    pub fn apply_config(&mut self, install: &InstallConfig, answers: WizardAnswers) {
        use crate::config::{DesktopShortcutPolicy, ScopePolicy};
        self.desktop_shortcut = match install.desktop_shortcut {
            DesktopShortcutPolicy::Always => true,
            DesktopShortcutPolicy::Never => false,
            DesktopShortcutPolicy::Ask => answers.desktop_shortcut,
        };
        self.start_menu_shortcut = match install.start_menu_shortcut {
            DesktopShortcutPolicy::Always => true,
            DesktopShortcutPolicy::Never => false,
            DesktopShortcutPolicy::Ask => answers.start_menu_shortcut,
        };
        self.launch_after_install = match install.launch_after_install {
            DesktopShortcutPolicy::Always => true,
            DesktopShortcutPolicy::Never => false,
            DesktopShortcutPolicy::Ask => answers.launch_after_install,
        };
        self.scope = match install.scope {
            ScopePolicy::User => InstallScope::User,
            ScopePolicy::Machine => InstallScope::Machine,
            ScopePolicy::Ask => {
                if answers.machine {
                    InstallScope::Machine
                } else {
                    InstallScope::User
                }
            }
        };
        self.portable_marker = install
            .portable_marker
            .clone()
            .unwrap_or_else(|| PORTABLE_MARKER.to_string());
        self.verbs = install.verbs.iter().map(VerbSpec::from).collect();
        self.deep_links = install
            .deep_links
            .iter()
            .map(|scheme| url_scheme(scheme))
            .filter(|s| !s.is_empty())
            .collect();
        self.aumid = Some(
            install
                .aumid
                .clone()
                .unwrap_or_else(|| default_aumid(self.publisher.as_deref(), &self.product)),
        );
        self.icon = install.icon.clone();
    }
}

/// Normalizes a configured deep-link scheme to a registry-safe URL
/// scheme name: lowercase, `[a-z0-9+.-]` only, trailing `://` stripped
/// (empty schemes are dropped).
pub fn url_scheme(raw: &str) -> String {
    let trimmed = raw.trim().trim_end_matches(':').trim_end_matches('/');
    trimmed
        .to_lowercase()
        .chars()
        .filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '.' | '-'))
        .collect()
}

/// The default shortcut grouping identity: `{publisher}.{product}` with
/// each segment reduced to `[A-Za-z0-9-]` runs joined by dots (AUMIDs are
/// `Company.Product` style identifiers, not free text).
pub fn default_aumid(publisher: Option<&str>, product: &str) -> String {
    let segment = |raw: &str| {
        let cleaned: String = raw
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '-' {
                    c
                } else {
                    '.'
                }
            })
            .collect();
        let collapsed: Vec<&str> = cleaned.split('.').filter(|s| !s.is_empty()).collect();
        collapsed.join("-")
    };
    match publisher {
        Some(publisher) if !segment(publisher).is_empty() => {
            format!("{}.{}", segment(publisher), segment(product))
        }
        _ => segment(product),
    }
}

/// Filesystem/registry-safe stem for a product name: the characters
/// Windows forbids in file names (`<>:"/\|?*` plus controls) become `_`,
/// and trailing dots/spaces (also illegal) are trimmed.
pub fn shortcut_stem(product: &str) -> String {
    let mut stem: String = product
        .chars()
        .map(|c| {
            if c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') {
                '_'
            } else {
                c
            }
        })
        .collect();
    while stem.ends_with('.') || stem.ends_with(' ') {
        stem.pop();
    }
    if stem.is_empty() {
        stem.push('_');
    }
    stem
}

/// The install delivery flow: extract the payload with progress, persist
/// the on-disk manifest (consumed by uninstall), then either register
/// (local mode) or drop the portable marker (portable mode).
pub struct InstallFlow<'a> {
    /// Payload to deliver.
    pub payload: &'a dyn PayloadSource,

    /// Per-OS registration backend.
    pub registration: &'a dyn Registration,

    /// Where and how the payload lands.
    pub ctx: InstallContext,
}

impl Flow for InstallFlow<'_> {
    fn run(&self, on_event: &mut dyn FnMut(FlowEvent)) -> Result<(), ShunError> {
        on_event(FlowEvent::Started);
        self.payload.extract(&self.ctx.install_dir, on_event)?;

        let manifest = serde_json::to_vec_pretty(self.payload.manifest())
            .map_err(|e| ShunError::Config(format!("manifest serialize: {e}")))?;
        std::fs::write(self.ctx.install_dir.join(MANIFEST_PATH), manifest)?;

        let mut ctx = self.ctx.clone();
        let total_bytes = PayloadEntry::total_bytes(self.payload.manifest());
        ctx.estimated_size_kb = u32::try_from(total_bytes / 1024).unwrap_or(u32::MAX);

        if ctx.portable {
            std::fs::write(ctx.install_dir.join(&ctx.portable_marker), b"")?;
        } else {
            self.registration.register_logged(&ctx, on_event)?;
        }

        on_event(FlowEvent::Completed);
        Ok(())
    }
}

/// Removes an install delivered by [`InstallFlow`]: registration trace,
/// payload files (per the on-disk manifest), marker, and the directory
/// itself once empty. Safe to call for both modes.
pub fn uninstall(ctx: &InstallContext, registration: &dyn Registration) -> Result<(), ShunError> {
    if !ctx.portable {
        registration.unregister(ctx)?;
    }

    let manifest_path = ctx.install_dir.join(MANIFEST_PATH);
    if manifest_path.exists() {
        let entries: Vec<PayloadEntry> = serde_json::from_slice(&std::fs::read(&manifest_path)?)?;
        for entry in entries {
            let _ = std::fs::remove_file(ctx.install_dir.join(entry.path));
        }
        let _ = std::fs::remove_file(&manifest_path);
        remove_empty_dirs_below(&ctx.install_dir);
    }

    let _ = std::fs::remove_file(ctx.install_dir.join(&ctx.portable_marker));

    let uninstaller = ctx.install_dir.join(UNINSTALLER_NAME);
    if uninstaller.exists() {
        schedule_self_delete(&uninstaller);
    }

    let _ = std::fs::remove_dir(&ctx.install_dir);
    Ok(())
}

/// Launches the installed application (the configured `main_exe` inside
/// the install dir), detached — the installer process may exit right
/// after. No-op when `ctx.launch_after_install` resolved false, and when
/// no entry point is declared at all.
pub fn launch(ctx: &InstallContext) -> Result<(), ShunError> {
    if !ctx.launch_after_install {
        return Ok(());
    }
    let Some(main_exe) = &ctx.main_exe else {
        return Ok(());
    };
    let exe = ctx.install_dir.join(main_exe);
    if !exe.is_file() {
        return Err(ShunError::MissingEntry(exe));
    }
    std::process::Command::new(&exe)
        .spawn()
        .map_err(ShunError::Io)?;
    Ok(())
}

/// Removes directories under `root` deepest-first (payload subdirectories
/// whose files the manifest pass just deleted), then `root` itself.
/// Failures are ignored — a non-empty directory simply stays.
fn remove_empty_dirs_below(root: &Path) {
    let mut dirs: Vec<PathBuf> = WalkDir::new(root)
        .into_iter()
        .filter_map(Result::ok)
        .filter(|e| e.file_type().is_dir() && e.path() != root)
        .map(|e| e.path().to_path_buf())
        .collect();
    dirs.sort_by_key(|p| std::cmp::Reverse(p.components().count()));
    for dir in dirs {
        let _ = std::fs::remove_dir(dir);
    }
    let _ = std::fs::remove_dir(root);
}

/// Per-OS registration backend.
///
/// Windows implements ARP entries, uninstaller registration, and start
/// menu shortcuts. Unix backends follow platform conventions (desktop
/// entries, launcher registration) once the macOS and Linux outputs land.
pub trait Registration {
    /// Register the install: ARP entry, uninstaller, shortcuts.
    fn register(&self, ctx: &InstallContext) -> Result<(), ShunError>;

    /// [`Registration::register`] with an event sink: implementations
    /// that degrade non-fatally (a security policy denying a desktop
    /// shortcut, an AUMID stamp) stream [`FlowLog::Warning`] records
    /// here so wizard terminals can show *why* something is missing.
    /// The default wraps [`Registration::register`] silently.
    fn register_logged(
        &self,
        ctx: &InstallContext,
        on_event: &mut dyn FnMut(FlowEvent),
    ) -> Result<(), ShunError> {
        let _ = on_event;
        self.register(ctx)
    }

    /// Remove every trace [`Registration::register`] left behind.
    fn unregister(&self, ctx: &InstallContext) -> Result<(), ShunError>;
}

/// HKCU ARP key path for a product (per-user installs need no elevation).
/// The product name is stem-sanitized: a `\` would nest a subkey. The
/// same path hangs off HKLM for machine-wide installs.
pub fn arp_key_path(product: &str) -> String {
    format!(
        r"Software\Microsoft\Windows\CurrentVersion\Uninstall\{}",
        shortcut_stem(product)
    )
}

/// Windows registration backend (ARP, uninstaller self-copy, start-menu
/// and desktop shortcuts, Explorer verbs, deep links) — per-user by
/// default; `InstallScope::Machine` writes the same surfaces machine-
/// wide (HKLM, all-users Start Menu, public desktop).
#[derive(Debug, Clone, Copy, Default)]
pub struct WindowsRegistration;

#[cfg(windows)]
impl Registration for WindowsRegistration {
    fn register(&self, ctx: &InstallContext) -> Result<(), ShunError> {
        self.register_logged(ctx, &mut |_| {})
    }

    fn register_logged(
        &self,
        ctx: &InstallContext,
        on_event: &mut dyn FnMut(FlowEvent),
    ) -> Result<(), ShunError> {
        // Uninstaller: copy this binary next to the payload (skipped when
        // we are already running from the install directory, i.e. when the
        // uninstaller re-registers itself).
        let uninstaller = ctx.install_dir.join(UNINSTALLER_NAME);
        match std::env::current_exe() {
            Ok(current) if current != uninstaller => {
                std::fs::create_dir_all(&ctx.install_dir)?;
                std::fs::copy(current, &uninstaller)?;
            }
            Ok(_) => {}
            Err(e) => return Err(ShunError::Io(e)),
        }

        let root = registry_root(ctx.scope);
        let (key, _) = root.create_subkey(arp_key_path(&ctx.product))?;
        key.set_value("DisplayName", &ctx.product)?;
        key.set_value("DisplayVersion", &ctx.version)?;
        if let Some(publisher) = &ctx.publisher {
            key.set_value("Publisher", publisher)?;
        }
        key.set_value("InstallLocation", &ctx.install_dir.as_os_str())?;
        // DisplayIcon on the application executable (not the icon-less
        // uninstaller) so the Apps list shows the product icon.
        let display_icon = ctx
            .main_exe
            .as_ref()
            .map(|exe| ctx.install_dir.join(exe))
            .unwrap_or_else(|| uninstaller.clone());
        key.set_value("DisplayIcon", &display_icon.as_os_str())?;
        key.set_value(
            "UninstallString",
            &format!("\"{}\" /uninstall", uninstaller.display()),
        )?;
        // ModifyPath: 修改 re-opens the delivery wizard so the user can
        // repair (re-extract over the existing install) or reconfigure.
        key.set_value("ModifyPath", &format!("\"{}\"", uninstaller.display()))?;
        key.set_value("EstimatedSize", &ctx.estimated_size_kb)?;

        // Shortcuts: the start-menu one when the context resolved
        // `start-menu-shortcut`, plus the desktop one when the context
        // resolved `desktop-shortcut`. Both carry the AUMID (taskbar
        // grouping / pinning identity). Machine scope writes the
        // all-users Start Menu and the public desktop.
        if let Some(main_exe) = &ctx.main_exe {
            let target = ctx.install_dir.join(main_exe);
            let stem = shortcut_stem(&ctx.product);

            let mut start_menu_link = None;
            if ctx.start_menu_shortcut {
                let programs = start_menu_dir(ctx.scope)?;
                std::fs::create_dir_all(&programs)?;
                let link = programs.join(format!("{stem}.lnk"));
                write_shortcut(ctx, &target, &link, on_event)?;
                start_menu_link = Some(link);
            }

            if ctx.desktop_shortcut {
                // Best-effort: AV/EDR policies commonly deny `.lnk`
                // creation on the desktop specifically (fake-shortcut /
                // ransomware protection) — the desktop shortcut is a
                // convenience and never fails the install.
                if let Some(link) = desktop_dir(ctx.scope)
                    .ok()
                    .map(|d| d.join(format!("{stem}.lnk")))
                {
                    if let Err(e) = write_shortcut(ctx, &target, &link, on_event) {
                        warn(on_event, "desktop-shortcut-blocked", &e.to_string());
                    }
                }
            }

            register_verbs(ctx, main_exe)?;
            register_deep_links(ctx, main_exe)?;

            // Tell the shell the shortcut surfaces changed — without
            // this, a freshly written Start-menu .lnk only appears once
            // Explorer re-indexes on its own schedule.
            let mut changed = Vec::new();
            if let Some(link) = start_menu_link {
                changed.push(link);
            }
            if ctx.desktop_shortcut {
                if let Ok(desktop) = desktop_dir(ctx.scope) {
                    changed.push(desktop.join(format!("{stem}.lnk")));
                }
            }
            notify_shell_change(&changed);
        }

        Ok(())
    }

    fn unregister(&self, ctx: &InstallContext) -> Result<(), ShunError> {
        use winreg::enums::KEY_READ;

        let root = registry_root(ctx.scope);
        let arp = arp_key_path(&ctx.product);
        if root.open_subkey_with_flags(&arp, KEY_READ).is_ok() {
            root.delete_subkey(&arp)?;
        }

        if ctx.main_exe.is_some() {
            let stem = shortcut_stem(&ctx.product);
            if let Ok(programs) = start_menu_dir(ctx.scope) {
                let _ = std::fs::remove_file(programs.join(format!("{stem}.lnk")));
            }
            // The desktop shortcut is attempted unconditionally: the
            // config may have changed between install and uninstall.
            if let Ok(desktop) = desktop_dir(ctx.scope) {
                let _ = std::fs::remove_file(desktop.join(format!("{stem}.lnk")));
            }
            if let Some(main_exe) = &ctx.main_exe {
                unregister_verbs(ctx, main_exe);
            }
        }
        unregister_deep_links(ctx);
        if ctx.main_exe.is_some() {
            let stem = shortcut_stem(&ctx.product);
            let mut changed = Vec::new();
            if let Ok(programs) = start_menu_dir(ctx.scope) {
                changed.push(programs.join(format!("{stem}.lnk")));
            }
            if let Ok(desktop) = desktop_dir(ctx.scope) {
                changed.push(desktop.join(format!("{stem}.lnk")));
            }
            notify_shell_change(&changed);
        }

        // The uninstaller binary deletes itself (it is usually the process
        // being run) — see `schedule_self_delete`.
        Ok(())
    }
}

/// The registry root the install scope writes: HKCU per user, HKLM
/// machine-wide (the caller must hold an elevated token for HKLM).
#[cfg(windows)]
fn registry_root(scope: InstallScope) -> winreg::RegKey {
    use winreg::RegKey;
    use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
    match scope {
        InstallScope::User => RegKey::predef(HKEY_CURRENT_USER),
        InstallScope::Machine => RegKey::predef(HKEY_LOCAL_MACHINE),
    }
}

/// The Start Menu `Programs` directory for the scope: the user's
/// `%APPDATA%` folder, or the all-users `%ProgramData%` one.
#[cfg(windows)]
fn start_menu_dir(scope: InstallScope) -> Result<PathBuf, ShunError> {
    let (variable, which) = match scope {
        InstallScope::User => ("APPDATA", "the user start menu"),
        InstallScope::Machine => ("ProgramData", "the all-users start menu"),
    };
    std::env::var(variable)
        .map(|root| Path::new(&root).join(r"Microsoft\Windows\Start Menu\Programs"))
        .map_err(|_| ShunError::Config(format!("%{variable}% is not set ({which})")))
}

/// Streams one non-fatal degradation as a warning record (stderr too —
/// headless consoles see it inline).
#[cfg(windows)]
fn warn(on_event: &mut dyn FnMut(FlowEvent), code: &str, detail: &str) {
    eprintln!("shun: {code}: {detail}");
    on_event(FlowEvent::Log {
        record: FlowLog::Warning {
            code: code.to_string(),
            detail: detail.to_string(),
        },
    });
}

/// Notifies the shell that shortcut surfaces changed
/// (`SHChangeNotify`): per-item updates for the `.lnk` files plus one
/// association-change flush, so the Start menu, desktop, and icon
/// caches refresh immediately instead of on Explorer's own schedule —
/// the standard installer finisher.
#[cfg(windows)]
fn notify_shell_change(paths: &[PathBuf]) {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::UI::Shell::{
        SHCNE_ASSOCCHANGED, SHCNE_UPDATEITEM, SHCNF_PATH, SHChangeNotify,
    };

    unsafe {
        for path in paths {
            let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
            SHChangeNotify(
                SHCNE_UPDATEITEM as i32,
                SHCNF_PATH,
                wide.as_ptr().cast(),
                std::ptr::null(),
            );
        }
        SHChangeNotify(
            SHCNE_ASSOCCHANGED as i32,
            0,
            std::ptr::null(),
            std::ptr::null(),
        );
    }
}

/// Creates a `.lnk` via mslnk, then stamps the AUMID on top through the
/// Shell property store (enhancement-only: a stamping failure never
/// blocks the install).
#[cfg(windows)]
fn write_shortcut(
    ctx: &InstallContext,
    target: &Path,
    link: &Path,
    on_event: &mut dyn FnMut(FlowEvent),
) -> Result<(), ShunError> {
    mslnk::ShellLink::new(target)
        .map_err(|e| ShunError::Config(format!("shortcut creation failed: {e}")))?
        .create_lnk(link)
        .map_err(|e| ShunError::Config(format!("shortcut creation failed: {e}")))?;
    if let Some(aumid) = &ctx.aumid {
        if let Err(e) = crate::targets::aumid::stamp(link, aumid) {
            warn(
                on_event,
                "aumid-stamp-blocked",
                &format!("{}: {e}", link.display()),
            );
        }
    }
    Ok(())
}

/// The desktop directory for the scope via `SHGetKnownFolderPath` — not
/// `%USERPROFILE%\Desktop`, which is wrong whenever the desktop is
/// redirected (OneDrive, domain policies). Machine scope resolves the
/// public desktop instead.
#[cfg(windows)]
fn desktop_dir(scope: InstallScope) -> Result<PathBuf, ShunError> {
    use windows_sys::Win32::System::Com::CoTaskMemFree;
    use windows_sys::Win32::UI::Shell::{
        FOLDERID_Desktop, FOLDERID_PublicDesktop, SHGetKnownFolderPath,
    };

    unsafe {
        let folder = match scope {
            InstallScope::User => &FOLDERID_Desktop,
            InstallScope::Machine => &FOLDERID_PublicDesktop,
        };
        let mut pwstr = std::ptr::null_mut();
        if SHGetKnownFolderPath(folder, 0, std::ptr::null_mut(), &mut pwstr) < 0 || pwstr.is_null()
        {
            return Err(ShunError::Config(
                "desktop folder lookup failed (SHGetKnownFolderPath)".into(),
            ));
        }
        let mut len = 0usize;
        while *pwstr.add(len) != 0 {
            len += 1;
        }
        let path = String::from_utf16_lossy(std::slice::from_raw_parts(pwstr as *const u16, len));
        CoTaskMemFree(pwstr.cast());
        Ok(PathBuf::from(path))
    }
}

/// Explorer-verb registry location for the entry executable:
/// `HKCU\Software\Classes\Applications\<exe file name>` — the documented
/// Application Registration surface; its verbs appear on the executable
/// and on shortcuts to it.
#[cfg(windows)]
fn applications_key(main_exe: &Path) -> String {
    let exe = main_exe
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "app.exe".into());
    format!(r"Software\Classes\Applications\{exe}")
}

#[cfg(windows)]
fn verb_command(ctx: &InstallContext, main_exe: &Path, target: &VerbTarget) -> String {
    match target {
        VerbTarget::DataFolder => format!("explorer.exe \"{}\"", ctx.install_dir.display()),
        VerbTarget::Uninstall => format!(
            "\"{}\" /uninstall",
            ctx.install_dir.join(UNINSTALLER_NAME).display()
        ),
        VerbTarget::App { arguments } => {
            let exe = ctx.install_dir.join(main_exe).display().to_string();
            let arguments = arguments.trim();
            if arguments.is_empty() {
                format!("\"{exe}\"")
            } else {
                format!("\"{exe}\" {arguments}")
            }
        }
    }
}

#[cfg(windows)]
fn register_verbs(ctx: &InstallContext, main_exe: &Path) -> Result<(), ShunError> {
    if ctx.verbs.is_empty() {
        return Ok(());
    }
    let root = registry_root(ctx.scope);
    for verb in &ctx.verbs {
        let (menu, _) = root.create_subkey(format!(
            r"{}\shell\{}",
            applications_key(main_exe),
            verb.key
        ))?;
        menu.set_value("", &verb.display)?;
        let (command, _) = root.create_subkey(format!(
            r"{}\shell\{}\command",
            applications_key(main_exe),
            verb.key
        ))?;
        command.set_value("", &verb_command(ctx, main_exe, &verb.target))?;
    }
    Ok(())
}

/// Removes the verb keys this install created, then the `shell` and
/// `Applications\<exe>` containers — but only where they are empty, so a
/// verb someone else registered under the same exe survives.
#[cfg(windows)]
fn unregister_verbs(ctx: &InstallContext, main_exe: &Path) {
    let root = registry_root(ctx.scope);
    for verb in &ctx.verbs {
        let _ = root.delete_subkey_all(format!(
            r"{}\shell\{}",
            applications_key(main_exe),
            verb.key
        ));
    }
    let _ = root.delete_subkey(format!(r"{}\shell", applications_key(main_exe)));
    let _ = root.delete_subkey(applications_key(main_exe));
}

#[cfg(not(windows))]
impl Registration for WindowsRegistration {
    fn register(&self, _ctx: &InstallContext) -> Result<(), ShunError> {
        Err(ShunError::Unsupported(
            "windows registration backend (compile on windows)",
        ))
    }

    fn unregister(&self, _ctx: &InstallContext) -> Result<(), ShunError> {
        Err(ShunError::Unsupported(
            "windows registration backend (compile on windows)",
        ))
    }
}

/// Deletes `exe` after a short delay when it is the currently running
/// process (a running binary cannot delete itself outright): a detached
/// `cmd` waits ~1s then removes the file. Non-running files delete
/// directly.
#[cfg(windows)]
fn schedule_self_delete(exe: &Path) {
    // CREATE_NO_WINDOW — NOT DETACHED_PROCESS: for a console-subsystem
    // child, DETACHED means "don't inherit the parent console", and
    // Windows then allocates a fresh VISIBLE console for cmd.exe — the
    // ping flash users report after every uninstall. NO_WINDOW keeps the
    // child console-less entirely.
    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
    use std::os::windows::process::CommandExt;

    if std::env::current_exe()
        .map(|current| current == exe)
        .unwrap_or(false)
    {
        let script = format!("ping -n 2 127.0.0.1 > nul & del /q \"{}\"", exe.display());
        let _ = std::process::Command::new("cmd")
            .arg("/C")
            .raw_arg(script)
            .creation_flags(CREATE_NO_WINDOW)
            .spawn();
    } else {
        let _ = std::fs::remove_file(exe);
    }
}

#[cfg(not(windows))]
fn schedule_self_delete(exe: &Path) {
    let _ = std::fs::remove_file(exe);
}

/// Registers the configured URL schemes as per-user protocol handlers
/// (`HKCU\Software\Classes\<scheme>` with the empty `URL Protocol`
/// value that marks a protocol class, plus the open command receiving
/// the URL as `%1`). Schemes are config-declared app-owned namespaces,
/// so unregistering deletes the whole key — the NSIS convention.
#[cfg(windows)]
fn register_deep_links(ctx: &InstallContext, main_exe: &Path) -> Result<(), ShunError> {
    if ctx.deep_links.is_empty() {
        return Ok(());
    }
    let root = registry_root(ctx.scope);
    let exe = ctx.install_dir.join(main_exe);
    for scheme in &ctx.deep_links {
        let (key, _) = root.create_subkey(format!(r"Software\Classes\{scheme}"))?;
        key.set_value("", &format!("URL:{} ({scheme})", ctx.product))?;
        key.set_value("URL Protocol", &"")?;
        let (open, _) =
            root.create_subkey(format!(r"Software\Classes\{scheme}\shell\open\command"))?;
        open.set_value("", &format!("\"{}\" \"%1\"", exe.display()))?;
    }
    Ok(())
}

#[cfg(windows)]
fn unregister_deep_links(ctx: &InstallContext) {
    if ctx.deep_links.is_empty() {
        return;
    }
    let root = registry_root(ctx.scope);
    for scheme in &ctx.deep_links {
        let _ = root.delete_subkey_all(format!(r"Software\Classes\{scheme}"));
    }
}

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

    #[test]
    fn stems_replace_filename_illegal_characters() {
        assert_eq!(shortcut_stem("Plain-Name"), "Plain-Name");
        assert_eq!(shortcut_stem("ShunDemo/Test *2"), "ShunDemo_Test _2");
        assert_eq!(shortcut_stem(r"Back\slash"), "Back_slash");
        // Trailing dots and spaces are also illegal in file names.
        assert_eq!(shortcut_stem("App. "), "App");
        assert_eq!(shortcut_stem("///"), "___");
    }

    #[test]
    fn arp_keys_use_the_sanitized_stem() {
        assert_eq!(
            arp_key_path(r"App\Nested"),
            r"Software\Microsoft\Windows\CurrentVersion\Uninstall\App_Nested"
        );
    }

    #[test]
    fn aumids_are_identifier_segments() {
        assert_eq!(
            default_aumid(Some("celestia-island"), "ShunDemo"),
            "celestia-island.ShunDemo"
        );
        assert_eq!(default_aumid(Some("A & B Co"), "My App"), "A-B-Co.My-App");
        assert_eq!(default_aumid(None, "Widget"), "Widget");
        assert_eq!(default_aumid(Some("///"), "Widget"), "Widget");
    }

    #[test]
    fn apply_config_resolves_the_registration_knobs() {
        use crate::config::{DesktopShortcutPolicy, InstallConfig, VerbConfig};

        let mut ctx = InstallContext::new(
            "Shun Demo".into(),
            "0.0.1".into(),
            PathBuf::from("."),
            false,
        );
        ctx.publisher = Some("celestia-island".into());
        assert!(
            !ctx.launch_after_install,
            "the baseline context launches nothing"
        );

        let mut install = InstallConfig {
            desktop_shortcut: DesktopShortcutPolicy::Never,
            start_menu_shortcut: DesktopShortcutPolicy::Never,
            aumid: Some("explicit.aumid".into()),
            verbs: vec![VerbConfig::DataFolder {
                key: "open-data".into(),
                display: "Open data".into(),
            }],
            ..InstallConfig::default()
        };
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: true,
                start_menu_shortcut: true,
                machine: false,
                launch_after_install: true,
            },
        );
        assert!(!ctx.desktop_shortcut, "never wins over the wizard answer");
        assert!(
            !ctx.start_menu_shortcut,
            "never wins over the wizard answer"
        );
        assert_eq!(ctx.aumid.as_deref(), Some("explicit.aumid"));
        assert_eq!(ctx.verbs.len(), 1);
        assert_eq!(ctx.verbs[0].target, VerbTarget::DataFolder);

        // The portable marker defaults to the shun convention and can be
        // pointed at a product's own marker name.
        assert_eq!(ctx.portable_marker, PORTABLE_MARKER);
        install.portable_marker = Some(".portable".into());
        ctx.apply_config(&install, WizardAnswers::defaults());
        assert_eq!(ctx.portable_marker, ".portable");
        install.portable_marker = None;
        ctx.apply_config(&install, WizardAnswers::defaults());
        assert_eq!(ctx.portable_marker, PORTABLE_MARKER);

        install.desktop_shortcut = DesktopShortcutPolicy::Always;
        ctx.apply_config(&install, WizardAnswers::defaults());
        assert!(ctx.desktop_shortcut, "always wins over the wizard answer");

        install.desktop_shortcut = DesktopShortcutPolicy::Ask;
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: false,
                start_menu_shortcut: false,
                machine: false,
                launch_after_install: true,
            },
        );
        assert!(!ctx.desktop_shortcut, "ask follows the wizard answer");

        // The start-menu shortcut mirrors the desktop one: always wins,
        // ask follows the wizard answer.
        install.start_menu_shortcut = DesktopShortcutPolicy::Always;
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: false,
                start_menu_shortcut: false,
                machine: false,
                launch_after_install: true,
            },
        );
        assert!(
            ctx.start_menu_shortcut,
            "always wins over the wizard answer"
        );

        install.start_menu_shortcut = DesktopShortcutPolicy::Ask;
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: false,
                start_menu_shortcut: true,
                machine: false,
                launch_after_install: true,
            },
        );
        assert!(ctx.start_menu_shortcut, "ask follows the wizard answer");
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: false,
                start_menu_shortcut: false,
                machine: false,
                launch_after_install: true,
            },
        );
        assert!(!ctx.start_menu_shortcut, "ask follows the wizard answer");

        // The launch-after-install policy mirrors the shortcut ones:
        // `always` / `never` pin it, `ask` follows the wizard answer.
        install.launch_after_install = DesktopShortcutPolicy::Always;
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: true,
                start_menu_shortcut: true,
                machine: false,
                launch_after_install: false,
            },
        );
        assert!(
            ctx.launch_after_install,
            "always wins over the wizard answer"
        );

        install.launch_after_install = DesktopShortcutPolicy::Never;
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: true,
                start_menu_shortcut: true,
                machine: false,
                launch_after_install: true,
            },
        );
        assert!(
            !ctx.launch_after_install,
            "never wins over the wizard answer"
        );

        install.launch_after_install = DesktopShortcutPolicy::Ask;
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: true,
                start_menu_shortcut: true,
                machine: false,
                launch_after_install: true,
            },
        );
        assert!(ctx.launch_after_install, "ask follows the wizard answer");
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: true,
                start_menu_shortcut: true,
                machine: false,
                launch_after_install: false,
            },
        );
        assert!(!ctx.launch_after_install, "ask follows the wizard answer");

        // Without an explicit AUMID the default is generated from the
        // identity.
        install.aumid = None;
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: true,
                start_menu_shortcut: true,
                machine: false,
                launch_after_install: true,
            },
        );
        assert_eq!(ctx.aumid.as_deref(), Some("celestia-island.Shun-Demo"));

        // Deep-link schemes normalize to registry-safe form.
        install.deep_links = vec!["MyApp://".into(), " shundemo ".into(), "///".into()];
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: true,
                start_menu_shortcut: true,
                machine: false,
                launch_after_install: true,
            },
        );
        assert_eq!(
            ctx.deep_links,
            vec!["myapp".to_string(), "shundemo".to_string()]
        );
    }

    #[test]
    fn url_schemes_normalize_to_lowercase_identifiers() {
        assert_eq!(url_scheme("MyApp://"), "myapp");
        assert_eq!(url_scheme(" Web+Extension.1 "), "web+extension.1");
        assert_eq!(url_scheme("has spaces"), "hasspaces");
        assert_eq!(url_scheme("///"), "");
    }
}