shun 0.6.0

Flow-driven payload delivery runtime — installers, flashers, and portable modes
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
//! The one wizard model every delivery face renders.
//!
//! A shell can present itself four ways — webview GUI (tauri), egui GUI,
//! TUI (ratatui), and the headless CLI — and the requirement is that they
//! all deliver the *same* wizard: the same left step rail, the same
//! location/license/install/done progression, the same shortcuts and
//! launch behavior. This module is that shared model: [`WizardState`]
//! holds everything a face paints, [`WizardCore`] moves it, and the
//! `run_install` / `run_uninstall` drivers execute the delivery exactly
//! once for all faces (the faces only choose how to render progress).
//!
//! Faces localize labels from their own tables (the model carries step
//! *keys*, not strings); flow-step text arrives as the flow's composed
//! English verbs, which faces may pass through.

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

use crate::config::{InstallConfig, ShunConfig, TargetConfig};
use crate::flow::{Flow, FlowEvent, FlowLog, FlowPhase};
use crate::payload::{ArchivePayload, MANIFEST_PATH, PayloadEntry};
use crate::targets::install::{
    InstallContext, InstallFlow, UNINSTALLER_NAME, WindowsRegistration, WizardAnswers,
    default_aumid, nest_root_dir, read_manifest, uninstall,
};

/// One wizard step. The rail order is the declaration order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
    /// Locale picker — the wizard's opening pane.
    Language,
    /// Install location (path + drive picker + candidates).
    Location,
    /// License agreement (paged documents).
    License,
    /// The running install (progress + log).
    Install,
    /// Done / failed landing page.
    Done,
}

impl Step {
    /// The rail in display order.
    pub const RAIL: [Step; 5] = [
        Step::Language,
        Step::Location,
        Step::License,
        Step::Install,
        Step::Done,
    ];

    /// The step before this one (Language has none).
    pub fn back_from(self) -> Option<Step> {
        Step::RAIL.get(self.index().checked_sub(1)?).copied()
    }

    fn index(self) -> usize {
        match self {
            Step::Language => 0,
            Step::Location => 1,
            Step::License => 2,
            Step::Install => 3,
            Step::Done => 4,
        }
    }
}

/// One line of the install log pane.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogLine {
    /// HH:MM:SS stamp.
    pub time: String,
    /// Severity-ish class the faces color by.
    pub kind: LogKind,
    pub text: String,
}

/// Log line classes (echo = plain, ok = success marker, step = phase
/// headline, error = warning/failure record).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogKind {
    Step,
    Echo,
    Ok,
    Error,
}

/// The uninstall page's phase (faces render confirm/running/done from
/// this; the model keeps it so every face offers the same flow).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UninstallPhase {
    Idle,
    Running,
    Done,
    Failed,
}

/// One writability-probed install-location candidate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirCandidate {
    /// "appdata" | "program-files" | "drive".
    pub kind: &'static str,
    pub path: String,
    pub writable: bool,
}

/// Everything a face paints. Updated only through [`WizardCore`]
/// actions and [`WizardCore::apply_event`], so every face sees the same
/// transitions.
#[derive(Debug, Clone)]
pub struct WizardState {
    /// Current step (the rail highlights it).
    pub step: Step,
    /// Wizard locale (a shell-locale string, e.g. `zh-Hans`).
    pub locale: String,
    /// The install directory shown in the location step.
    pub dir: String,
    /// Writability of `dir`: `None` while a probe is in flight or the
    /// box is empty.
    pub dir_writable: Option<bool>,
    /// Quick-pick candidates under the path field.
    pub candidates: Vec<DirCandidate>,
    /// Index into the license pager.
    pub license_index: usize,
    /// The accept checkbox.
    pub agreed: bool,
    /// Done-page shortcut answers.
    pub desktop_shortcut: bool,
    pub start_menu_shortcut: bool,
    /// Done-page immediate-launch answer.
    pub launch_after: bool,
    /// 0-100 once the flow reports percents.
    pub progress: Option<u8>,
    /// The flow's current step label (English composed verb).
    pub flow_step: String,
    /// The install log pane (bounded — old lines drop).
    pub log: Vec<LogLine>,
    /// Set when the flow failed; lands the done page on its failure
    /// variant.
    pub failure: Option<String>,
    /// The uninstall page's phase.
    pub uninstall_phase: UninstallPhase,
    /// Uninstall error text (failure variant).
    pub uninstall_error: String,
}

/// One document of the license step: a titled markdown block, resolved
/// per locale at build time by the shell.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LicenseDoc {
    #[serde(default)]
    pub title: String,
    pub body: String,
}

/// The shared wizard: config + payload + per-locale license documents
/// plus the renderable [`WizardState`].
pub struct WizardCore {
    /// The resolved delivery configuration.
    pub config: ShunConfig,
    /// License documents keyed by shell locale.
    pub license_docs: BTreeMap<String, Vec<LicenseDoc>>,
    /// The renderable state.
    pub state: WizardState,
    /// A pairing claim cashed by the pane, delivered as the manifest's
    /// `env-file` inside the install dir at delivery time. `None` until
    /// an operator accepts a displayed code.
    pub pairing_outcome: Option<PairingOutcome>,
}

/// The claimed credential the pane hands to the delivery lane.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct PairingOutcome {
    /// The gateway the code was minted through.
    pub gateway: String,
    /// The device id the credential belongs to.
    pub node_id: String,
    /// The device secret — written once, never logged.
    pub device_secret: String,
    /// The accepting account.
    pub owner: String,
}

impl WizardCore {
    /// Assembles the wizard: default locale (the shell's configured
    /// language, else English), the writability-probed location
    /// defaults, and neutral step state.
    pub fn new(config: ShunConfig, license_docs: BTreeMap<String, Vec<LicenseDoc>>) -> Self {
        let locale = config
            .shell
            .as_ref()
            .and_then(|s| s.language.clone())
            .unwrap_or_else(|| "en".into());
        let mut core = Self {
            pairing_outcome: None,
            state: WizardState {
                step: Step::Language,
                locale,
                dir: String::new(),
                dir_writable: None,
                candidates: Vec::new(),
                license_index: 0,
                agreed: false,
                desktop_shortcut: true,
                start_menu_shortcut: true,
                launch_after: true,
                progress: None,
                flow_step: String::new(),
                log: Vec::new(),
                failure: None,
                uninstall_phase: UninstallPhase::Idle,
                uninstall_error: String::new(),
            },
            config,
            license_docs,
        };
        core.refresh_dir_defaults();
        core
    }

    /// The install-target configuration (single install target per
    /// product).
    pub fn install_target(&self) -> Result<InstallConfig, String> {
        self.config
            .targets
            .iter()
            .find_map(|t| match t {
                TargetConfig::Install(install) => Some(install.clone()),
                _ => None,
            })
            .ok_or_else(|| "this configuration declares no install target".into())
    }

    /// The main executable name: the manifest's `main-exe`, else the
    /// product name with an `.exe` suffix.
    pub fn main_exe(&self) -> String {
        self.install_target()
            .ok()
            .and_then(|i| i.main_exe)
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|| format!("{}.exe", self.config.product.name))
    }

    /// Locale change: re-keys the license pager (documents arrive from
    /// the build-time map; unknown locales keep the previous set — the
    /// face's picker only offers locales with entries).
    pub fn set_locale(&mut self, locale: impl Into<String>) {
        self.state.locale = locale.into();
        self.state.license_index = 0;
    }

    /// The license documents for a locale (English fallback, then none
    /// — the license step always renders).
    pub fn license_docs_for(&self, locale: &str) -> &[LicenseDoc] {
        let docs = self
            .license_docs
            .get(locale)
            .or_else(|| self.license_docs.get("en"));
        docs.map(|d| d.as_slice()).unwrap_or(&[])
    }

    /// Recomputes the location defaults: the candidate chain (per-user
    /// appdata → Program Files → one folder per fixed drive), the
    /// default being the first writable candidate.
    pub fn refresh_dir_defaults(&mut self) {
        let product = self.config.product.name.clone();
        let candidates = dir_candidates_for(&product);
        let paths: Vec<PathBuf> = candidates.iter().map(|(_, p)| p.clone()).collect();
        let dir = crate::fs_probe::first_writable(&paths)
            .or_else(|| paths.first().cloned())
            .unwrap_or_else(|| local_appdata().join(&product));
        self.state.dir = dir.to_string_lossy().into_owned();
        self.state.dir_writable = Some(true);
        self.state.candidates = candidates
            .into_iter()
            .map(|(kind, path)| DirCandidate {
                kind,
                writable: crate::fs_probe::is_dir_writable(&path),
                path: path.to_string_lossy().into_owned(),
            })
            .collect();
    }

    /// Sets the shown path and probes its writability (the same test
    /// `run_install` gates on).
    pub fn set_dir(&mut self, dir: impl Into<String>) {
        let dir = dir.into();
        let target = dir.trim().to_string();
        self.state.dir_writable = if target.is_empty() {
            None
        } else {
            Some(crate::fs_probe::is_dir_writable(Path::new(&target)))
        };
        self.state.dir = dir;
    }

    /// Pads one folder level under a bare filesystem root (the root-drive
    /// guard); updates the shown path when the guard rewrote it.
    /// Returns whether the path changed.
    pub fn nest_dir(&mut self, raw: &str) -> bool {
        let nested = self.nested_path(raw);
        if nested != raw.trim() {
            self.state.dir = nested;
            true
        } else {
            false
        }
    }

    /// The padded form of a path per the root-drive guard, without
    /// touching state.
    pub fn nested_path(&self, raw: &str) -> String {
        let folder = self
            .install_target()
            .ok()
            .and_then(|i| i.root_dir_folder.clone());
        nest_root_dir(
            Path::new(raw.trim()),
            &self.config.product.name,
            folder.as_deref(),
        )
        .to_string_lossy()
        .into_owned()
    }

    /// Advances one step (no-op past Done; entering Install resets the
    /// run state — callers drive the flow themselves).
    pub fn go(&mut self, step: Step) {
        if step == Step::Install {
            self.state.progress = None;
            self.state.flow_step.clear();
            self.state.log.clear();
            self.state.failure = None;
        }
        if step == Step::License {
            self.state.license_index = 0;
        }
        self.state.step = step;
    }

    /// The step before the current one (Language has none).
    pub fn back_from(&self) -> Option<Step> {
        self.state.step.back_from()
    }

    /// Folds one flow event into the renderable state: percent, current
    /// step label, structured log lines, and the failure marker. Every
    /// face pumps its events through here so their panes stay identical.
    pub fn apply_event(&mut self, event: &FlowEvent) {
        match event {
            FlowEvent::Progress {
                phase,
                step,
                percent,
                ..
            } => {
                let _ = phase;
                if !step.is_empty() {
                    self.state.flow_step = step.clone();
                }
                if let Some(p) = percent {
                    self.state.progress = Some((*p).min(100));
                }
            }
            FlowEvent::Log { record } => {
                if let Some((kind, text)) = log_line_of(record) {
                    self.push_log(kind, text);
                }
            }
            FlowEvent::Failed { message } => {
                self.state.failure = Some(message.clone());
                self.push_log(LogKind::Error, message.clone());
            }
            _ => {}
        }
    }

    /// Appends one log line (bounded: the pane keeps the last 500).
    pub fn push_log(&mut self, kind: LogKind, text: String) {
        let time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        // HH:MM:SS of the wall clock (local offset is a face concern;
        // the model keeps UTC-of-epoch, stable across threads).
        let (h, m, s) = ((time / 3600) % 24, (time / 60) % 60, time % 60);
        self.state.log.push(LogLine {
            time: format!("{h:02}:{m:02}:{s:02}"),
            kind,
            text,
        });
        if self.state.log.len() > 500 {
            self.state.log.remove(0);
        }
    }

    /// The install context for a wizard run (registration semantics per
    /// the config; the flow itself creates no shortcuts — the done page
    /// owns that answer).
    fn install_context(
        &self,
        dir: &str,
        portable: bool,
        machine: bool,
    ) -> Result<InstallContext, String> {
        let install = self.install_target()?;
        let mut ctx = InstallContext::new(
            self.config.product.name.clone(),
            self.config.product.version.clone(),
            PathBuf::from(dir),
            portable,
        );
        ctx.publisher = self.config.product.publisher.clone();
        ctx.main_exe = install.main_exe.clone();
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: false,
                start_menu_shortcut: false,
                launch_after_install: false,
                machine,
            },
        );
        Ok(ctx)
    }

    /// The uninstall context for the copied uninstaller: it sits inside
    /// the install dir, so the running executable's directory is the
    /// install target. Local-install semantics only.
    pub fn uninstall_context(&self) -> Result<InstallContext, String> {
        let exe_dir = std::env::current_exe()
            .map_err(|e| format!("cannot locate the uninstaller: {e}"))?
            .parent()
            .ok_or_else(|| "cannot locate the uninstaller directory".to_string())?
            .to_path_buf();
        let install = self.install_target()?;
        let mut ctx = InstallContext::new(
            self.config.product.name.clone(),
            self.config.product.version.clone(),
            exe_dir,
            false,
        );
        ctx.publisher = self.config.product.publisher.clone();
        ctx.main_exe = install.main_exe.clone();
        ctx.apply_config(
            &install,
            WizardAnswers {
                desktop_shortcut: false,
                start_menu_shortcut: true,
                launch_after_install: false,
                machine: false,
            },
        );
        Ok(ctx)
    }
}

/// An install request a face files after the done-page confirmation
/// logic resolves (or a headless caller composes from flags).
pub struct InstallRequest {
    /// "local" (today; portable carries the marker flow when enabled).
    pub mode: String,
    /// The padded install directory.
    pub dir: String,
    /// The wizard language (reaches scripts and the on-disk manifest).
    pub language: Option<String>,
    /// Machine-wide scope (HKLM / all-users surfaces). Faces without a
    /// scope toggle — and every elevated relaunch that already passed the
    /// gate — file `false`; the headless lane is the only `true` source
    /// after the UAC gate.
    pub machine: bool,
}

/// Drives one delivery through the shared path every face uses:
/// writability gate → overwrite hygiene (stop the running app, capture
/// the previous manifest) → the install flow → the stale-file sweep.
/// Faces render the emitted events (and fold them into their wizard
/// state via [`WizardCore::apply_event`]); this function never touches
/// UI state itself.
pub fn run_install(
    core: &WizardCore,
    payload: &ArchivePayload,
    request: &InstallRequest,
    on_event: &mut dyn FnMut(&FlowEvent),
) -> Result<(), String> {
    let dir = request.dir.trim().trim_end_matches('\\').to_string();
    if dir.is_empty() {
        return Err("the install directory must not be empty".into());
    }
    if !crate::fs_probe::is_dir_writable(Path::new(&dir)) {
        return Err("the target directory is not writable — pick another location".into());
    }
    let portable = request.mode != "local";
    let mut ctx = core
        .install_context(&dir, portable, request.machine)
        .map_err(|e| e.to_string())?;
    ctx.language = match request.language.as_deref() {
        Some(l) if !l.trim().is_empty() => Some(l.to_string()),
        // Repair path (no wizard answer): keep the language the
        // previous install recorded.
        _ => current_exe_dir().as_deref().and_then(manifest_language_of),
    };

    let install_dir = ctx.install_dir.clone();
    let main_exe = core.main_exe();
    let previous = read_installed_manifest(&install_dir).unwrap_or_default();
    if install_dir.join(&main_exe).is_file() {
        on_event(&FlowEvent::Progress {
            phase: FlowPhase::Prepare,
            step: format!("Stopping {main_exe}"),
            percent: None,
        });
    }
    stop_running_app(&install_dir, &main_exe);
    // Prepare-phase script hooks (docs/en/design/scripting.md): the
    // payload may carry runner scripts that hold the flow's opening —
    // the demo's screenshot-window delay rides this.
    crate::targets::install::run_phase_hooks(
        "prepare",
        &core.config,
        &ctx,
        &mut |event| on_event(&event),
        &|path| payload.read_file(path).map(|b| b.to_vec()),
    )
    .map_err(|e| e.to_string())?;
    let flow = InstallFlow {
        payload,
        registration: &WindowsRegistration,
        ctx: ctx.clone(),
    };
    let mut forwarding = |event: FlowEvent| on_event(&event);
    flow.run(&mut forwarding).map_err(|e| e.to_string())?;
    let stale = remove_stale_payload_files(&install_dir, &previous);
    if stale > 0 {
        on_event(&FlowEvent::Progress {
            phase: FlowPhase::Extract,
            step: format!("Removed {stale} stale file(s)"),
            percent: None,
        });
    }
    // post-install hooks: after the flow's Completed event but before
    // this returns — the wizard stays on the running page while they
    // run, so their log lines land in the live pane.
    crate::targets::install::run_phase_hooks(
        "post-install",
        &core.config,
        &ctx,
        &mut |event| on_event(&event),
        // The flow has extracted by now — read from the install dir
        // (the payload bytes are identical, but the on-disk copy is
        // what a repair would have run too).
        &|path| std::fs::read(install_dir.join(path)).ok(),
    )
    .map_err(|e| e.to_string())?;
    Ok(())
}

/// Drives the uninstall for the install dir this process sits in (the
/// uninstall page and the headless ARP path both land here).
pub fn run_uninstall(core: &WizardCore) -> Result<(), String> {
    run_uninstall_with_events(core, &mut |_| {})
}

/// The uninstall with the event stream surfaced (the headless lane
/// prints it; GUI faces drive their panes through the worker instead).
pub fn run_uninstall_with_events(
    core: &WizardCore,
    on_event: &mut dyn FnMut(&FlowEvent),
) -> Result<(), String> {
    let ctx = core.uninstall_context()?;
    // pre-uninstall hooks: after the uninstall context resolves (the
    // install dir this process sits in), before any removal work. The
    // scripts read from that dir on disk — the uninstaller carries no
    // payload, and the installed copy is what ran at install time.
    crate::targets::install::run_phase_hooks(
        "pre-uninstall",
        &core.config,
        &ctx,
        &mut |event| on_event(&event),
        &|path| std::fs::read(ctx.install_dir.join(path)).ok(),
    )
    .map_err(|e| e.to_string())?;
    uninstall(&ctx, &WindowsRegistration).map_err(|e| e.to_string())
}

/// Applies the done-page answers: creates or removes the shortcuts and
/// optionally launches the installed app. A shortcut failure never
/// invalidates the completed install (errors combine and return).
pub fn apply_finish(
    core: &WizardCore,
    dir: &str,
    desktop: Option<bool>,
    menu: Option<bool>,
    launch: bool,
) -> Result<(), String> {
    // The pairing claim rides the delivery into the install dir as the
    // manifest's env-file — write-then-rename, 0600, no-op unpaired.
    if let Some(outcome) = &core.pairing_outcome {
        let env_file = core
            .config
            .steps
            .as_ref()
            .and_then(|steps| {
                steps
                    .iter()
                    .find(|s| s.kind == crate::config::StepKind::Pairing)
                    .and_then(|s| s.pairing.as_ref())
            })
            .and_then(|p| p.env_file.clone());
        if let Some(env_file) = env_file {
            let path = std::path::Path::new(dir.trim()).join(&env_file);
            let mut body = String::new();
            use std::fmt::Write as _;
            let _ = writeln!(body, "# Written by the installer's first-run pairing step.");
            let _ = writeln!(
                body,
                "# The device credential below was issued once by the pairing"
            );
            let _ = writeln!(body, "# service; treat it like a password.");
            // Every VALUE is control/whitespace-stripped: hostile input
            // can never break the line or smuggle another one.
            let safe = |v: &str| -> String {
                v.chars()
                    .filter(|c| !c.is_control() && !c.is_whitespace())
                    .collect::<String>()
                    .trim_end_matches('/')
                    .to_string()
            };
            let _ = writeln!(body, "SERVER_URL={}", safe(&outcome.gateway));
            let _ = writeln!(body, "DEVICE_SECRET={}", safe(&outcome.device_secret));
            let _ = writeln!(body, "BOOTSTRAP_NODE_ID={}", safe(&outcome.node_id));
            let _ = writeln!(body, "BOOTSTRAP_GATEWAY={}", safe(&outcome.gateway));
            let tmp = path.with_extension("env.tmp");
            std::fs::write(&tmp, body).map_err(|e| format!("write pairing credential: {e}"))?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt as _;
                let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600));
            }
            std::fs::rename(&tmp, &path).map_err(|e| format!("install pairing credential: {e}"))?;
        }
    }
    crate::targets::shortcuts::apply_shortcut_choices(
        &shortcut_aumid_for(&core.config),
        &core.config.product.name,
        &core.main_exe(),
        desktop,
        menu,
        &core.nested_path(dir),
    )?;
    if launch {
        launch_installed(core, dir)?;
    }
    Ok(())
}

/// The install context for the machine-scope elevation gate: the gate
/// resolves the target's scope and relays the wizard language to the
/// elevated copy, so it needs a full context — but the shortcut answers
/// ride the relaunch flags (the elevated copy runs the headless lane,
/// which applies its own conventional defaults), and the flow itself
/// never creates shortcuts. One construction, shared by every face.
pub fn elevation_context(
    config: &ShunConfig,
    dir: &str,
    portable: bool,
    machine: bool,
    language: Option<&str>,
) -> Result<InstallContext, String> {
    let install = config
        .targets
        .iter()
        .find_map(|t| match t {
            TargetConfig::Install(install) => Some(install.clone()),
            _ => None,
        })
        .ok_or("this configuration declares no install target")?;
    let mut ctx = InstallContext::new(
        config.product.name.clone(),
        config.product.version.clone(),
        PathBuf::from(dir),
        portable,
    );
    ctx.publisher = config.product.publisher.clone();
    ctx.main_exe = install.main_exe.clone();
    ctx.language = language
        .map(str::to_string)
        .filter(|l| !l.trim().is_empty());
    ctx.apply_config(
        &install,
        WizardAnswers {
            desktop_shortcut: false,
            start_menu_shortcut: false,
            launch_after_install: false,
            machine,
        },
    );
    Ok(ctx)
}

/// Launches the freshly installed main executable through the delivery
/// helper (best-effort detached spawn).
pub fn launch_installed(core: &WizardCore, dir: &str) -> Result<(), String> {
    let install = core.install_target()?;
    let dir = nest_root_dir(
        Path::new(dir.trim().trim_end_matches('\\')),
        &core.config.product.name,
        install.root_dir_folder.as_deref(),
    );
    let mut ctx = InstallContext::new(
        core.config.product.name.clone(),
        core.config.product.version.clone(),
        dir,
        false,
    );
    ctx.main_exe = install.main_exe.clone();
    ctx.launch_after_install = true;
    crate::targets::install::launch(&ctx).map_err(|e| e.to_string())
}

/// The shortcut grouping identity: the manifest's `aumid` when declared,
/// else shun's `{publisher}.{product}` default.
pub fn shortcut_aumid_for(config: &ShunConfig) -> String {
    let configured = config.targets.iter().find_map(|t| match t {
        TargetConfig::Install(install) => install.aumid.clone(),
        _ => None,
    });
    configured
        .unwrap_or_else(|| default_aumid(config.product.publisher.as_deref(), &config.product.name))
}

/// The per-user data home (`%LOCALAPPDATA%` / XDG data home).
pub fn local_appdata() -> PathBuf {
    #[cfg(windows)]
    {
        std::env::var_os("LOCALAPPDATA")
            .map(PathBuf::from)
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_default())
    }
    #[cfg(not(windows))]
    {
        if let Some(home) = std::env::var_os("XDG_DATA_HOME").filter(|v| !v.is_empty()) {
            return PathBuf::from(home);
        }
        match std::env::var_os("HOME") {
            Some(home) if !home.is_empty() => PathBuf::from(home).join(".local").join("share"),
            _ => std::env::current_dir().unwrap_or_default(),
        }
    }
}

/// The directory holding the running executable.
pub fn current_exe_dir() -> Option<PathBuf> {
    std::env::current_exe()
        .ok()
        .and_then(|exe| exe.parent().map(Path::to_path_buf))
}

/// The writability-probed location candidates for a product (the
/// command layer's thin entry — faces that hold a [`WizardCore`] get the
/// same list through [`WizardCore::refresh_dir_defaults`]).
pub fn location_defaults(product: &str) -> Vec<DirCandidate> {
    dir_candidates_for(product)
        .into_iter()
        .map(|(kind, path)| DirCandidate {
            kind,
            writable: crate::fs_probe::is_dir_writable(&path),
            path: path.to_string_lossy().into_owned(),
        })
        .collect()
}

/// The default install location: the first writable candidate, else the
/// per-user appdata folder.
pub fn default_location(product: &str) -> String {
    let candidates = dir_candidates_for(product);
    let paths: Vec<PathBuf> = candidates.iter().map(|(_, p)| p.clone()).collect();
    crate::fs_probe::first_writable(&paths)
        .or_else(|| paths.first().cloned())
        .unwrap_or_else(|| local_appdata().join(product))
        .to_string_lossy()
        .into_owned()
}

/// The root-drive guard for a bare path, config-aware (free-function
/// form for the command layer).
pub fn pad_root_dir(config: &ShunConfig, raw: &str) -> String {
    let folder = config.targets.iter().find_map(|t| match t {
        TargetConfig::Install(install) => install.root_dir_folder.clone(),
        _ => None,
    });
    nest_root_dir(
        Path::new(raw.trim()),
        &config.product.name,
        folder.as_deref(),
    )
    .to_string_lossy()
    .into_owned()
}

/// The candidate chain behind the location defaults, in pick priority
/// order: per-user appdata, Program Files, one folder per fixed drive.
fn dir_candidates_for(product: &str) -> Vec<(&'static str, PathBuf)> {
    use crate::fs_probe::DriveKind;

    let appdata = ("appdata", local_appdata().join(product));
    let program_files = (
        "program-files",
        std::env::var_os("ProgramFiles")
            .filter(|v| !v.is_empty())
            .map_or_else(|| PathBuf::from(r"C:\Program Files"), PathBuf::from)
            .join(product),
    );
    let fixed = crate::fs_probe::list_drives()
        .into_iter()
        .filter(|drive| drive.kind == DriveKind::Fixed)
        .map(|drive| ("drive", drive.mount.join(product)));
    std::iter::once(appdata)
        .chain(std::iter::once(program_files))
        .chain(fixed)
        .collect()
}

/// The wizard language a previous install recorded in its on-disk
/// manifest; `None` when absent or unparsable.
fn manifest_language_of(install_dir: &Path) -> Option<String> {
    read_manifest(install_dir)
        .ok()
        .and_then(|m| m.language)
        .filter(|l| !l.trim().is_empty())
}

/// Stops a running main executable before an overwrite install replaces
/// its payload: Windows locks a running image, so the extraction would
/// fail with os error 5. Returns whether a previous install was found.
#[cfg(windows)]
pub fn stop_running_app(install_dir: &Path, main_exe: &str) -> bool {
    use std::os::windows::process::CommandExt;

    if !install_dir.join(main_exe).is_file() {
        return false;
    }
    let _ = std::process::Command::new("taskkill")
        .args(["/F", "/IM", main_exe])
        .creation_flags(0x0800_0000) // CREATE_NO_WINDOW
        .status();
    std::thread::sleep(std::time::Duration::from_millis(800));
    true
}

/// Non-Windows: no image-name file lock to fight.
#[cfg(not(windows))]
pub fn stop_running_app(_install_dir: &Path, _main_exe: &str) -> bool {
    false
}

/// The installer-owned files that live in the install dir but are never
/// payload entries (compared case-insensitively — Windows resolves
/// paths that way).
fn is_installer_artifact(path: &Path) -> bool {
    let name = path.to_string_lossy().to_lowercase();
    name == MANIFEST_PATH || name == UNINSTALLER_NAME || name == ".shun-portable"
}

/// Whether a manifest entry path may be joined under the install dir
/// for deletion: archive-relative and free of `..`.
fn entry_path_is_unsafe(path: &Path) -> bool {
    path.components().any(|c| {
        matches!(
            c,
            std::path::Component::Prefix(_)
                | std::path::Component::RootDir
                | std::path::Component::ParentDir
        )
    })
}

/// The on-disk payload manifest a previous install left behind.
fn read_installed_manifest(install_dir: &Path) -> Option<Vec<PayloadEntry>> {
    let bytes = std::fs::read(install_dir.join(MANIFEST_PATH)).ok()?;
    serde_json::from_slice(&bytes).ok()
}

/// Deletes the files the PREVIOUS payload delivered that the new one no
/// longer carries; best-effort, run only after a successful flow.
fn remove_stale_payload_files(install_dir: &Path, previous: &[PayloadEntry]) -> usize {
    if previous.is_empty() {
        return 0;
    }
    let mut removed = 0usize;
    for entry in previous {
        let path = Path::new(&entry.path);
        if entry_path_is_unsafe(path) || is_installer_artifact(path) {
            continue;
        }
        if std::fs::remove_file(install_dir.join(path)).is_ok() {
            removed += 1;
        }
    }
    if removed > 0 {
        prune_empty_dirs_below(install_dir);
    }
    removed
}

/// Removes empty directories under `root`, deepest first.
fn prune_empty_dirs_below(root: &Path) {
    fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                let path = entry.path();
                collect(&path, out);
                out.push(path);
            }
        }
    }
    let mut dirs = Vec::new();
    collect(root, &mut dirs);
    for dir in dirs {
        let _ = std::fs::remove_dir(dir);
    }
}

/// Composes one log pane line from a structured record (English verbs —
/// faces may pass through or re-localize by kind).
fn log_line_of(record: &FlowLog) -> Option<(LogKind, String)> {
    match record {
        FlowLog::FileWrite { path } => Some((LogKind::Echo, format!("write {}", path.display()))),
        FlowLog::FileReuse { path } => Some((LogKind::Echo, format!("reuse {}", path.display()))),
        FlowLog::Warning { code, detail } => {
            let text = if code.is_empty() {
                detail.clone()
            } else if detail.is_empty() {
                code.clone()
            } else {
                format!("{code}: {detail}")
            };
            (!text.is_empty()).then_some((LogKind::Error, text))
        }
        FlowLog::ScriptBegin { name, .. } => {
            Some((LogKind::Step, format!("running script {name}")))
        }
        FlowLog::ScriptLine { line, .. } => Some((LogKind::Echo, line.clone())),
        FlowLog::CommandDone { command, .. } => Some((LogKind::Ok, format!("done {command}"))),
    }
}

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

    fn core_with(config_json: &str) -> WizardCore {
        let config: crate::config::ShunConfig = serde_json::from_str(config_json).unwrap();
        WizardCore::new(config, BTreeMap::new())
    }

    #[test]
    fn rail_order_is_stable() {
        assert_eq!(Step::RAIL[0], Step::Language);
        assert_eq!(Step::RAIL[4], Step::Done);
        assert_eq!(Step::Language.back_from(), None);
        let mut core = core_with(BASIC);
        core.go(Step::License);
        assert_eq!(core.back_from(), Some(Step::Location));
    }

    #[test]
    fn entering_install_resets_the_run_state() {
        let mut core = core_with(BASIC);
        core.state.progress = Some(42);
        core.state.failure = Some("old".into());
        core.push_log(LogKind::Echo, "old line".into());
        core.go(Step::Install);
        assert_eq!(core.state.progress, None);
        assert_eq!(core.state.failure, None);
        assert!(core.state.log.is_empty());
    }

    #[test]
    fn apply_event_folds_percent_label_and_log() {
        let mut core = core_with(BASIC);
        core.apply_event(&FlowEvent::Progress {
            phase: FlowPhase::Extract,
            step: "Extracting app.exe".into(),
            percent: Some(42),
        });
        core.apply_event(&FlowEvent::Log {
            record: FlowLog::FileWrite {
                path: PathBuf::from("app.exe"),
            },
        });
        assert_eq!(core.state.progress, Some(42));
        assert_eq!(core.state.flow_step, "Extracting app.exe");
        assert_eq!(core.state.log.len(), 1);
        assert_eq!(core.state.log[0].kind, LogKind::Echo);
    }

    #[test]
    fn main_exe_falls_back_to_the_product_name() {
        let core = core_with(BASIC);
        assert_eq!(core.main_exe(), "app.exe");
    }

    const BASIC: &str =
        r#"{"product":{"name":"app","version":"1.0"},"targets":[{"kind":"install","local":true}]}"#;
}