shun 0.6.5

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
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
//! The shun build CLI.
//!
//! - `shun pack`      — payload directory → `*.shun` archive
//! - `shun config`    — resolve and validate a delivery manifest
//! - `shun icons`     — derive per-OS icon sets from a single logo
//! - `shun sign`      — Authenticode / codesign artifacts
//! - `shun build`     — manifest + payload → single-file installer
//! - `shun msix`      — pack the payload into a signed-ready .msix
//! - `shun stage`     — build an app and stage it into its payload
//! - `shun flash list`— enumerate flash-candidate devices

use std::path::{Path, PathBuf};
use std::process::Command as StdCommand;

use clap::{Parser, Subcommand};
use shun::config::ShunConfig;
use shun::payload::pack_directory;
use shun::targets::flash::{FlashTarget, LogicalDrives};

#[derive(Parser)]
#[command(
    name = "shun",
    version,
    about = "Flow-driven payload delivery — build tool for installers and flashers"
)]
struct Cli {
    #[command(subcommand)]
    command: CliCommand,
}

#[derive(Subcommand)]
enum CliCommand {
    /// Pack a payload directory into a shun archive (*.shun).
    Pack {
        /// Directory to pack (becomes the payload root).
        payload_dir: PathBuf,
        /// Output archive path (default: <dir-name>.shun next to it).
        #[arg(short, long)]
        out: Option<PathBuf>,
    },
    /// Resolve a delivery manifest and print the effective config as JSON.
    Config {
        /// Path to a Cargo.toml (uses [package.metadata.shun]) or a
        /// standalone .toml/.json document.
        #[arg(long)]
        path: PathBuf,
    },
    /// Derive per-OS icon sets from a single logo image.
    Icons {
        /// Logo source (webp/png; square renders best).
        #[arg(long)]
        logo: PathBuf,
        /// Output directory (windows/ linux/ macos/ subfolders are created).
        #[arg(long, default_value = "icons")]
        out: PathBuf,
    },
    /// Sign binaries per the signing section of a delivery manifest.
    Sign {
        /// Files to sign.
        #[arg(required = true)]
        files: Vec<PathBuf>,
        /// Delivery manifest (Cargo.toml) or standalone config.
        #[arg(long)]
        manifest: PathBuf,
    },
    /// Build delivery artifacts: resolve the manifest, pack the payload,
    /// drive the shell build, then sign the installer. The shell binary
    /// statically links the CRT on msvc targets (+crt-static, merged
    /// into any RUSTFLAGS you set), so the artifact runs on stock
    /// Windows without the VC++ Redistributable.
    Build {
        /// Delivery manifest: a Cargo.toml with [package.metadata.shun] or
        /// a standalone .toml/.json config.
        #[arg(long)]
        manifest: PathBuf,
        /// Shell crate source directory (contains its own Cargo.toml with
        /// [package.metadata.shun] plus the UI). Defaults to ./shell.
        #[arg(long)]
        shell_src: Option<PathBuf>,
        /// Output directory for artifacts.
        #[arg(long, default_value = "dist")]
        out: PathBuf,
        /// Skip code signing even when configured.
        #[arg(long)]
        no_sign: bool,
        /// Named build variant from the manifest's `[[variant]]` tables:
        /// applies the payload/face overrides and hands the variant's env
        /// to the shell build (flavor markers, resource-pack stamps).
        #[arg(long)]
        variant: Option<String>,
        /// Rust target triple (e.g. x86_64-pc-windows-msvc) passed
        /// through to the shell build and folded into the artifact name.
        #[arg(long)]
        target: Option<String>,
    },
    /// Build an MSIX package from the payload (Windows SDK MakeAppx).
    Msix {
        /// Delivery manifest declaring [msix] (identity, publisher, ...).
        #[arg(long)]
        manifest: PathBuf,
        /// Output .msix path (default: <product>-<version>-x64.msix).
        #[arg(long)]
        out: Option<PathBuf>,
        /// Logo for the manifest assets (png/webp; optional).
        #[arg(long)]
        logo: Option<PathBuf>,
        /// Skip code signing even when configured.
        #[arg(long)]
        no_sign: bool,
    },
    /// List flash-candidate devices.
    FlashList {},
    /// Build an application and stage its binary into the payload
    /// directory declared by its delivery manifest. Everything — the
    /// cargo package, the bin name, the payload root, the entry path —
    /// is derived from the manifest; nothing is hardcoded. The staged
    /// app binary is YOURS: pin +crt-static yourself (a repo
    /// .cargo/config.toml is the usual spot) if it must run without
    /// the VC++ Redistributable — shun only pins its own binaries.
    Stage {
        /// Delivery manifest: the application's Cargo.toml carrying
        /// `[package.metadata.shun]`.
        #[arg(long)]
        manifest: PathBuf,
        /// Cargo profile to build with (default `release`).
        #[arg(long, default_value = "release")]
        profile: String,
        /// Skip the cargo build; stage an already-built binary.
        #[arg(long)]
        no_build: bool,
    },
}

fn main() {
    let cli = Cli::parse();
    if let Err(err) = run(cli.command) {
        eprintln!("error: {err}");
        std::process::exit(1);
    }
}

// ── Static CRT enforcement ───────────────────────────────────────────────

/// The rustflags fragment that statically links the CRT. A dynamically
/// linked Rust/MSVC binary imports VCRUNTIME140.dll; a stock Windows
/// machine without the VC++ Redistributable then dies on a loader dialog
/// before ANY code of ours runs — the egui degrade face included. The
/// published shells must never take that dependency (see the repo-root
/// `.cargo/config.toml` for the in-repo half of this contract).
const STATIC_CRT_FLAG: &str = "-C target-feature=+crt-static";

/// The same flag as ONE argv token — cargo passes CARGO_ENCODED_RUSTFLAGS
/// entries to rustc verbatim with no whitespace splitting, so the encoded
/// lane must append the glued spelling (a space would make rustc parse
/// `' target-feature'` as the option name and fail the build).
const STATIC_CRT_FLAG_ENCODED: &str = "-Ctarget-feature=+crt-static";

/// The 0x1f unit separator cargo uses for CARGO_ENCODED_RUSTFLAGS.
const ENCODED_SEP: char = '\u{1f}';

/// Whether a rustflags value already decides the CRT (either direction):
/// a present `crt-static` token means the caller pinned it — including an
/// explicit `-crt-static` disable, which stays caller-wins (with a warning
/// from [`warn_dynamic_crt_pin`]) rather than fighting the caller.
fn pins_crt(mut flags: impl Iterator<Item = String>) -> bool {
    flags.any(|f| f.contains("crt-static"))
}

/// [`STATIC_CRT_FLAG`] merged into a whitespace-split RUSTFLAGS value:
/// `None` when the value already decides the CRT (no change needed),
/// `Some` otherwise — the existing flags always survive. An empty value
/// is treated as unset (the empty-var-to-clear idiom is common).
fn merged_rustflags(existing: Option<&str>) -> Option<String> {
    let existing = existing?.trim();
    if existing.is_empty() || pins_crt(existing.split_whitespace().map(str::to_string)) {
        return None;
    }
    Some(format!("{existing} {STATIC_CRT_FLAG}"))
}

/// The CARGO_ENCODED_RUSTFLAGS spelling of the same merge (entries stay
/// single tokens; empty entries — a set-but-empty variable — are dropped,
/// cargo would hand rustc a lone empty-string argument otherwise).
fn merged_encoded_rustflags(existing: Option<&str>) -> Option<String> {
    let existing = existing?.trim_matches(ENCODED_SEP);
    if existing.is_empty() || pins_crt(existing.split(ENCODED_SEP).map(str::to_string)) {
        return None;
    }
    Some(format!("{existing}{ENCODED_SEP}{STATIC_CRT_FLAG_ENCODED}"))
}

/// Whether a `--target` triple (or the host, for `None`) links against
/// the dynamic MSVC CRT — the only lane that needs the flag.
fn is_msvc_target(target: Option<&str>) -> bool {
    match target {
        Some(triple) => triple.ends_with("-windows-msvc"),
        // The published binaries only ever target windows-msvc hosts;
        // GNU targets keep their static-by-default mingw runtime.
        None => cfg!(target_os = "windows") && cfg!(target_env = "msvc"),
    }
}

/// The observable half of caller-wins: an explicit `-crt-static` pin
/// ships the dynamic CRT on purpose, so say so instead of failing silent.
fn warn_dynamic_crt_pin(existing: &str) {
    if existing.contains("-crt-static") {
        eprintln!(
            "shun: RUSTFLAGS pins -crt-static — the built binary will need the \
             VC++ Redistributable (VCRUNTIME140.dll) at runtime"
        );
    }
}

/// Pins the static CRT onto a child cargo invocation. Cargo's rustflags
/// precedence is CARGO_ENCODED_RUSTFLAGS > RUSTFLAGS > config files, so
/// the flag must merge into whichever variable is already in play — the
/// caller's environment, or a manifest variant env that overrides it (a
/// plain child `env` write would clobber the variant's value). Setting
/// the child RUSTFLAGS when neither is in play does shadow rustflags a
/// consumer config file would contribute to the shell build — unavoidable
/// (cargo has no append-to-config API) and deliberate: the static-CRT
/// contract outweighs unknown config rustflags here.
fn ensure_static_crt(
    cargo: &mut StdCommand,
    variant_env: &std::collections::BTreeMap<String, String>,
) {
    // A manifest variant env may pin either variable itself; those keys
    // merge here instead of riding `cargo.env` at the call site (a plain
    // child-env write would be clobbered by this pin, or would defeat it
    // through the encoded variable's precedence).
    let variant_key = |name: &str| variant_env.get(name).map(String::as_str);
    let mut merge_encoded = |existing: &str| {
        warn_dynamic_crt_pin(existing);
        match merged_encoded_rustflags(Some(existing)) {
            Some(merged) => {
                cargo.env("CARGO_ENCODED_RUSTFLAGS", merged);
            }
            None => {
                cargo.env("CARGO_ENCODED_RUSTFLAGS", existing);
            }
        }
    };
    // CARGO_ENCODED_RUSTFLAGS wins over RUSTFLAGS; a variant's value wins
    // over the caller environment on either lane.
    if let Some(existing) = variant_key("CARGO_ENCODED_RUSTFLAGS") {
        merge_encoded(existing);
        return;
    }
    if let Some(existing) = std::env::var_os("CARGO_ENCODED_RUSTFLAGS")
        .filter(|v| !v.to_string_lossy().trim_matches(ENCODED_SEP).is_empty())
    {
        let Some(existing) = existing.to_str() else {
            eprintln!(
                "shun: CARGO_ENCODED_RUSTFLAGS is not valid UTF-8; skipping the static-CRT pin"
            );
            return;
        };
        merge_encoded(existing);
        return;
    }
    let mut merge_plain = |existing: Option<&str>, from_variant: bool| {
        let Some(existing) = existing.filter(|v| !v.trim().is_empty()) else {
            // Nothing in play: set the flag — unless a variant set an
            // EMPTY RUSTFLAGS on purpose (keep the caller's clearing).
            if !from_variant {
                cargo.env("RUSTFLAGS", STATIC_CRT_FLAG);
            }
            return;
        };
        warn_dynamic_crt_pin(existing);
        match merged_rustflags(Some(existing)) {
            Some(merged) => {
                cargo.env("RUSTFLAGS", merged);
            }
            None => {
                cargo.env("RUSTFLAGS", existing);
            }
        }
    };
    match variant_key("RUSTFLAGS") {
        Some(existing) => merge_plain(Some(existing), true),
        None => merge_plain(
            std::env::var_os("RUSTFLAGS")
                .and_then(|v| v.into_string().ok())
                .as_deref(),
            false,
        ),
    }
}

fn run(command: CliCommand) -> Result<(), String> {
    match command {
        CliCommand::Pack { payload_dir, out } => {
            let archive = pack_directory(&payload_dir).map_err(|e| e.to_string())?;
            let out = out.unwrap_or_else(|| {
                let name = payload_dir
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| "payload".to_string());
                payload_dir.join(format!("{name}.shun"))
            });
            std::fs::write(&out, &archive).map_err(|e| e.to_string())?;
            println!(
                "packed {} ({} bytes) -> {}",
                payload_dir.display(),
                archive.len(),
                out.display()
            );
            Ok(())
        }
        CliCommand::Config { path } => {
            let config = resolve_config(&path)?;
            let json = serde_json::to_vec_pretty(&config).map_err(|e| e.to_string())?;
            println!("{}", String::from_utf8_lossy(&json));
            Ok(())
        }
        CliCommand::Icons { logo, out } => {
            icons::generate(&logo, &out).map_err(|e| e.to_string())?;
            println!("icon sets written under {}", out.display());
            Ok(())
        }
        CliCommand::Sign { files, manifest } => {
            let config = resolve_config(&manifest)?;
            let signing = config.signing.clone().unwrap_or_default();
            sign::sign_files(&files, &signing).map_err(|e| e.to_string())?;
            println!("signed {} file(s)", files.len());
            Ok(())
        }
        CliCommand::Build {
            manifest,
            shell_src,
            out,
            no_sign,
            variant,
            target,
        } => {
            let mut config = resolve_config(&manifest)?;
            let mut variant_env: std::collections::BTreeMap<String, String> = Default::default();
            if let Some(name) = &variant {
                config.apply_variant(name)?;
                variant_env = config
                    .variants
                    .as_ref()
                    .and_then(|vs| vs.iter().find(|v| &v.name == name))
                    .and_then(|v| v.env.clone())
                    .unwrap_or_default();
                variant_env
                    .entry("SHUN_VARIANT".to_string())
                    .or_insert_with(|| name.clone());
            }
            let product = config.product.clone();

            // 1. Payload package (*.shun) — works for both embedded and
            //    online shells (the online installer still needs the
            //    package hosted somewhere).
            let payload_dir = manifest.parent().unwrap_or(Path::new(".")).join(
                config
                    .payload
                    .clone()
                    .unwrap_or_else(|| PathBuf::from("payload")),
            );
            let archive = pack_directory(&payload_dir).map_err(|e| e.to_string())?;

            // 2. Shell build: hand the manifest to the shell via env and
            //    let its build.rs resolve config + payload embedding.
            let shell_src = shell_src.unwrap_or_else(|| PathBuf::from("shell"));
            let shell_manifest = shell_src.join("Cargo.toml");
            let shell_package: toml::Value =
                toml::from_str(&std::fs::read_to_string(&shell_manifest).map_err(|e| {
                    format!(
                        "cannot read shell manifest {}: {e}",
                        shell_manifest.display()
                    )
                })?)
                .map_err(|e| format!("shell manifest parse: {e}"))?;
            // The artifact cargo writes is named after the [[bin]] target,
            // not the package: shells routinely rename their binary
            // (shun-demo-shell.exe for the shun_demo_shell package), so
            // resolve the first [[bin]].name and fall back to the package
            // name (the implicit bin target) only when no [[bin]] table
            // declares one.
            let shell_bin = shell_package
                .get("bin")
                .and_then(|bins| bins.as_array())
                .and_then(|bins| bins.first())
                .and_then(|bin| bin.get("name"))
                .and_then(toml::Value::as_str)
                .map(str::to_string)
                .or_else(|| {
                    shell_package
                        .get("package")
                        .and_then(|p| p.get("name"))
                        .and_then(toml::Value::as_str)
                        .map(str::to_string)
                })
                .unwrap_or_else(|| "shun-demo-shell".to_string());

            let mut cargo = StdCommand::new("cargo");
            cargo
                .args([
                    "build",
                    "--release",
                    "--manifest-path",
                    &shell_manifest.display().to_string(),
                ])
                .env(
                    "SHUN_MANIFEST",
                    std::fs::canonicalize(&manifest).map_err(|e| e.to_string())?,
                );
            if let Some(variant) = &variant {
                cargo.env("SHUN_VARIANT", variant);
                for (key, value) in &variant_env {
                    // RUSTFLAGS / CARGO_ENCODED_RUSTFLAGS ride through
                    // the static-CRT merge below instead (a plain env
                    // write here would be clobbered by — or defeat —
                    // the pin).
                    if key != "RUSTFLAGS" && key != "CARGO_ENCODED_RUSTFLAGS" {
                        cargo.env(key, value);
                    }
                }
            }
            if let Some(target) = &target {
                cargo.arg("--target").arg(target);
            }
            // The static-CRT pin rides the child env: config discovery
            // is CWD-based (a consumer-repo invocation never sees this
            // repo's .cargo/config.toml) and a caller-set RUSTFLAGS
            // would override config rustflags outright.
            if is_msvc_target(target.as_deref()) {
                ensure_static_crt(&mut cargo, &variant_env);
            }
            let status = cargo
                .status()
                .map_err(|e| format!("cargo build failed: {e}"))?;
            if !status.success() {
                return Err(format!("shell build failed (exit {status:?})"));
            }

            // 3. Collect artifacts: single-file installer + payload package.
            std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
            let target_dir = shell_src.join("..").join("target");
            let target_dir = match &target {
                Some(triple) => target_dir.join(triple),
                None => target_dir,
            };
            let target_exe = target_dir.join("release").join(format!("{shell_bin}.exe"));
            // Artifact naming carries the matrix axes: product-version
            // [-variant] [-arch] -setup.exe — the variant from the flag,
            // the arch folded from the target triple's cpu part.
            let stem_base = format!(
                "{}-{}",
                product.name.to_lowercase().replace(' ', "-"),
                product.version
            );
            let stem_variant = variant
                .as_deref()
                .map(|v| format!("-{v}"))
                .unwrap_or_default();
            let stem_arch = target
                .as_deref()
                .and_then(|triple| triple.split('-').next())
                .map(|cpu| {
                    let arch = match cpu {
                        "x86_64" => "x64",
                        "aarch64" => "arm64",
                        "i686" => "x86",
                        other => other,
                    };
                    format!("-{arch}")
                })
                .unwrap_or_default();
            let installer = out.join(format!("{stem_base}{stem_variant}{stem_arch}-setup.exe"));
            std::fs::copy(&target_exe, &installer).map_err(|e| {
                format!(
                    "copy installer failed (expected {}): {e}",
                    target_exe.display()
                )
            })?;
            let package = out.join(format!(
                "{}.shun",
                product.name.to_lowercase().replace(' ', "-")
            ));
            std::fs::write(&package, &archive).map_err(|e| e.to_string())?;

            // 4. Sign (unless disabled or unconfigured).
            if !no_sign {
                let signing = config.signing.clone().unwrap_or_default();
                if let Some(windows) = &signing.windows {
                    if windows.enabled {
                        sign::sign_files(std::slice::from_ref(&installer), &signing)
                            .map_err(|e| e.to_string())?;
                        println!("signed {}", installer.display());
                    }
                }
            }

            println!("build complete:");
            println!("  installer package: {}", package.display());
            println!("  installer binary:  {}", installer.display());
            Ok(())
        }
        CliCommand::Msix {
            manifest,
            out,
            logo,
            no_sign,
        } => {
            let config = resolve_config(&manifest)?;
            let msix = config.msix.clone().ok_or_else(|| {
                "the manifest declares no [msix] table — add identity-name, publisher and                  display-name to the delivery manifest"
                    .to_string()
            })?;
            let payload_dir = manifest.parent().unwrap_or(Path::new(".")).join(
                config
                    .payload
                    .clone()
                    .unwrap_or_else(|| PathBuf::from("payload")),
            );

            let logo_png = logo
                .as_deref()
                .map(|path| logo_png_bytes(path, msix.logo_background.as_deref()))
                .transpose()?;
            let base = out.unwrap_or_else(|| PathBuf::from("dist"));
            std::fs::create_dir_all(&base).map_err(|e| e.to_string())?;
            let out_msix = base.join(format!(
                "{}-{}-x64.msix",
                msix.identity_name.to_lowercase().replace(' ', "-"),
                config.product.version
            ));

            let inputs = shun::msix::MsixInputs {
                identity_name: &msix.identity_name,
                publisher: &msix.publisher,
                display_name: &msix.display_name,
                description: msix.description.as_deref().unwrap_or(""),
                version: &config.product.version,
                executable: msix.executable.as_deref().ok_or(
                    "the [msix] table declares no executable — add the payload-relative \
                     entry point",
                )?,
                logo_png: logo_png.as_deref(),
                logo_background: msix.logo_background.as_deref(),
            };
            shun::msix::build_msix(&payload_dir, &out_msix, &inputs).map_err(|e| e.to_string())?;

            if !no_sign {
                let signing = config.signing.clone().unwrap_or_default();
                if let Some(windows) = &signing.windows {
                    if windows.enabled {
                        sign::sign_files(std::slice::from_ref(&out_msix), &signing)
                            .map_err(|e| e.to_string())?;
                        println!("signed {}", out_msix.display());
                    }
                }
            }
            println!("msix ready: {}", out_msix.display());
            Ok(())
        }
        CliCommand::FlashList {} => {
            let devices = LogicalDrives.list_devices().map_err(|e| e.to_string())?;
            if devices.is_empty() {
                println!("no removable drives found");
                return Ok(());
            }
            println!("{:<14} {:>14}  LABEL", "ID", "SIZE (B)");
            for device in devices {
                println!("{:<14} {:>14}  {}", device.id, device.size, device.label);
            }
            Ok(())
        }
        CliCommand::Stage {
            manifest,
            profile,
            no_build,
        } => {
            stage_payload(&manifest, &profile, no_build).map_err(|e| e.to_string())?;
            Ok(())
        }
    }
}

/// `shun stage` — build the declaring application and place its binary
/// at `payload`/`main-exe`. Derived entirely from the manifest:
///
/// - the cargo package name and bin name come from the manifest's own
///   `[package]` / `[[bin]]` tables;
/// - the destination comes from `[package.metadata.shun]` `payload` and
///   `main-exe`;
/// - the output directory comes from `cargo metadata` (honors
///   `CARGO_TARGET_DIR` and workspace roots).
///
/// DLL sidecars dropped beside the built binary (e.g. WebView2Loader)
/// travel into the payload too.
fn stage_payload(manifest: &Path, profile: &str, no_build: bool) -> Result<(), std::io::Error> {
    let manifest_dir = manifest
        .parent()
        .map(std::path::Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));

    // 1. Cargo identity of the application: [package] name, first
    //    [[bin]] name (defaults to the package name).
    let raw = std::fs::read_to_string(manifest)?;
    let document: toml::Value =
        toml::from_str(&raw).map_err(|e| std::io::Error::other(format!("manifest parse: {e}")))?;
    let package = document
        .get("package")
        .and_then(|p| p.get("name"))
        .and_then(toml::Value::as_str)
        .ok_or_else(|| std::io::Error::other("manifest declares no [package] name"))?
        .to_string();
    let bin = document
        .get("bin")
        .and_then(|bins| bins.as_array())
        .and_then(|bins| bins.first())
        .and_then(|bin| bin.get("name"))
        .and_then(toml::Value::as_str)
        .unwrap_or(&package)
        .to_string();

    // 2. Destination from the delivery config.
    let config = resolve_config(manifest)
        .map_err(|e| std::io::Error::other(format!("delivery manifest: {e}")))?;
    let main_exe = config
        .targets
        .iter()
        .find_map(|t| match t {
            shun::config::TargetConfig::Install(install) => install.main_exe.clone(),
            _ => None,
        })
        .or_else(|| {
            config
                .payload
                .as_ref()
                .map(|_| PathBuf::from(format_bin(&bin)))
        })
        .ok_or_else(|| {
            std::io::Error::other("manifest declares no main-exe and no install target")
        })?;
    let payload_dir = config
        .payload
        .as_ref()
        .map(|payload| manifest_dir.join(payload))
        .ok_or_else(|| std::io::Error::other("manifest declares no payload directory"))?;
    let destination = payload_dir.join(&main_exe);

    // 3. Build (unless told not to) and locate the output directory via
    //    cargo metadata.
    if !no_build {
        let status = StdCommand::new("cargo")
            .args(["build", "--manifest-path"])
            .arg(manifest)
            .arg("--profile")
            .arg(profile)
            .status()?;
        if !status.success() {
            return Err(std::io::Error::other(format!(
                "cargo build failed (exit {status:?})"
            )));
        }
    }
    let metadata = StdCommand::new("cargo")
        .args([
            "metadata",
            "--no-deps",
            "--format-version",
            "1",
            "--manifest-path",
        ])
        .arg(manifest)
        .output()?;
    if !metadata.status.success() {
        return Err(std::io::Error::other("cargo metadata failed"));
    }
    let metadata: serde_json::Value = serde_json::from_slice(&metadata.stdout)
        .map_err(|e| std::io::Error::other(format!("cargo metadata parse: {e}")))?;
    let target_dir = PathBuf::from(
        metadata
            .get("target_directory")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| std::io::Error::other("cargo metadata has no target_directory"))?,
    );
    // Profile `dev` writes to `target/debug`; every other profile writes
    // to `target/<profile>`.
    let out_dir_name = if profile == "dev" { "debug" } else { profile };
    let built_bin = target_dir.join(out_dir_name).join(format_bin(&bin));

    if !built_bin.is_file() {
        return Err(std::io::Error::other(format!(
            "built binary not found at {} — run without --no-build",
            built_bin.display()
        )));
    }

    // 4. Stage: binary + any DLL sidecars beside it.
    if let Some(parent) = destination.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::copy(&built_bin, &destination)?;
    println!(
        "staged {} -> {}",
        built_bin.display(),
        destination.display()
    );
    for entry in std::fs::read_dir(built_bin.parent().unwrap_or(&target_dir))? {
        let entry = entry?;
        let path = entry.path();
        let is_dll = path
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("dll"));
        if is_dll {
            let to = destination
                .parent()
                .unwrap_or(&payload_dir)
                .join(entry.file_name());
            std::fs::copy(&path, &to)?;
            println!("staged sidecar {} -> {}", path.display(), to.display());
        }
    }
    Ok(())
}

/// Platform binary suffix for a cargo bin name.
#[cfg(windows)]
fn format_bin(bin: &str) -> String {
    format!("{bin}.exe")
}

#[cfg(not(windows))]
fn format_bin(bin: &str) -> String {
    bin.to_string()
}

/// Converts any logo image into PNG bytes for the MSIX assets. When a
/// plate color is configured, a transparent logo is composited onto it —
/// Windows plates transparent logos with the default system blue on
/// surfaces that ignore `BackgroundColor="transparent"` for packaged
/// desktop apps, so the brand picks the color instead.
fn logo_png_bytes(logo: &Path, background: Option<&str>) -> Result<Vec<u8>, String> {
    let img = image::open(logo)
        .map_err(|e| format!("cannot open logo: {e}"))?
        .into_rgba8();
    let img = match background.map(parse_hex_color).transpose()? {
        Some([r, g, b]) => {
            let mut plate = image::RgbaImage::from_pixel(
                img.width(),
                img.height(),
                image::Rgba([r, g, b, u8::MAX]),
            );
            image::imageops::overlay(&mut plate, &img, 0, 0);
            plate
        }
        None => img,
    };
    let mut png = Vec::new();
    img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
        .map_err(|e| format!("logo png encode: {e}"))?;
    Ok(png)
}

/// Parses a `#RRGGBB` hex color into RGB channels.
fn parse_hex_color(hex: &str) -> Result<[u8; 3], String> {
    let hex = hex.trim().trim_start_matches('#');
    if hex.len() != 6 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(format!(
            "invalid logo background {hex:?}: expected #RRGGBB hex color"
        ));
    }
    let mut channels = [0u8; 3];
    for (slot, pair) in channels.iter_mut().zip(hex.as_bytes().chunks_exact(2)) {
        let pair = std::str::from_utf8(pair).map_err(|e| e.to_string())?;
        *slot = u8::from_str_radix(pair, 16).map_err(|e| e.to_string())?;
    }
    Ok(channels)
}
fn resolve_config(path: &Path) -> Result<ShunConfig, String> {
    if path.file_name().and_then(|n| n.to_str()) == Some("Cargo.toml") {
        ShunConfig::from_cargo_manifest(path)
    } else {
        ShunConfig::from_path(path)
    }
    .map_err(|e| e.to_string())
}

mod icons {
    use std::io::Cursor;
    use std::path::Path;

    use image::imageops::FilterType;

    const SIZES: [[u32; 2]; 8] = [
        [16, 16],
        [24, 24],
        [32, 32],
        [48, 48],
        [64, 64],
        [128, 128],
        [256, 256],
        [512, 512],
    ];

    /// Layer ladder for the Windows .ico. The ICO format records each
    /// layer's dimensions in a single byte (0 meaning 256), so layers cap
    /// at 256 px — larger renders stay in the PNG ladders below.
    const ICO_SIZES: [u32; 7] = [16, 24, 32, 48, 64, 128, 256];

    /// Encodes a multi-size .ico: one PNG-compressed layer per size in
    /// the container layout (ICONDIR, one 16-byte directory entry per
    /// layer, then the image bytes). PNG layers are the Vista+ convention
    /// and need no extra encoder dependency.
    fn encode_ico(img: &image::RgbaImage, sizes: &[u32]) -> Result<Vec<u8>, String> {
        let mut layers: Vec<(u32, Vec<u8>)> = Vec::with_capacity(sizes.len());
        for &size in sizes {
            let scaled = image::imageops::resize(img, size, size, FilterType::Lanczos3);
            let mut png = Cursor::new(Vec::new());
            scaled
                .write_to(&mut png, image::ImageFormat::Png)
                .map_err(|e| format!("ico layer encode: {e}"))?;
            layers.push((size, png.into_inner()));
        }

        let mut out = Vec::new();
        out.extend_from_slice(&0u16.to_le_bytes()); // reserved
        out.extend_from_slice(&1u16.to_le_bytes()); // type: icon
        out.extend_from_slice(&(layers.len() as u16).to_le_bytes());
        let mut offset = 6 + 16 * layers.len();
        for (size, png) in &layers {
            let dim = if *size >= 256 { 0u8 } else { *size as u8 };
            out.push(dim); // width (0 = 256)
            out.push(dim); // height
            out.push(0); // palette color count
            out.push(0); // reserved
            out.extend_from_slice(&1u16.to_le_bytes()); // color planes
            out.extend_from_slice(&32u16.to_le_bytes()); // bits per pixel
            out.extend_from_slice(&(png.len() as u32).to_le_bytes());
            out.extend_from_slice(&(offset as u32).to_le_bytes());
            offset += png.len();
        }
        for (_, png) in &layers {
            out.extend_from_slice(png);
        }
        Ok(out)
    }

    /// Derives per-OS icon sets from one square logo:
    /// - windows/icon.ico (multi-size, layers within the 256 px ICO
    ///   ceiling)
    /// - linux/*.png (full size ladder)
    /// - macos/icon.iconset/*.png (Apple iconset layout for iconutil)
    pub fn generate(logo: &Path, out: &Path) -> Result<(), String> {
        let img = image::open(logo).map_err(|e| format!("cannot open logo: {e}"))?;
        let img = img.into_rgba8();
        let largest = SIZES.iter().map(|s| s[0]).max().unwrap_or(512);
        let img = if img.width() != largest || img.height() != largest {
            image::imageops::resize(&img, largest, largest, FilterType::Lanczos3)
        } else {
            img
        };

        let windows_dir = out.join("windows");
        std::fs::create_dir_all(&windows_dir).map_err(|e| e.to_string())?;
        let ico = encode_ico(&img, &ICO_SIZES)?;
        std::fs::write(windows_dir.join("icon.ico"), ico).map_err(|e| format!("ico write: {e}"))?;

        let linux_dir = out.join("linux");
        std::fs::create_dir_all(&linux_dir).map_err(|e| e.to_string())?;
        for [w, h] in SIZES {
            let scaled = image::imageops::resize(&img, w, h, FilterType::Lanczos3);
            scaled
                .save(linux_dir.join(format!("icon_{w}x{h}.png")))
                .map_err(|e| format!("png encode: {e}"))?;
        }

        let macos_dir = out.join("macos").join("shun.iconset");
        std::fs::create_dir_all(&macos_dir).map_err(|e| e.to_string())?;
        for [w, h] in SIZES {
            let scaled = image::imageops::resize(&img, w, h, FilterType::Lanczos3);
            scaled
                .save(macos_dir.join(format!("icon_{w}x{h}.png")))
                .map_err(|e| format!("png encode: {e}"))?;
            let (w2, h2) = (w * 2, h * 2);
            let scaled2 = image::imageops::resize(&img, w2, h2, FilterType::Lanczos3);
            scaled2
                .save(macos_dir.join(format!("icon_{w}x{h}@2x.png")))
                .map_err(|e| format!("png encode: {e}"))?;
        }

        // macOS: `iconutil -c icns shun.iconset` on any mac produces the
        // .icns; Linux CI can use `icnsutil`. Documented in the CLI guide.
        Ok(())
    }

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

        /// A source beyond the ICO ceiling (512 px, as shun icons itself
        /// renders) encodes cleanly: every layer parses back as a PNG at
        /// or below the 256 px format limit, with a consistent container.
        #[test]
        fn ico_layers_stay_within_the_format_ceiling() {
            let img = image::RgbaImage::from_pixel(512, 512, image::Rgba([12, 34, 56, 255]));
            let bytes = encode_ico(&img, &ICO_SIZES).expect("ico encodes");

            assert_eq!(&bytes[0..2], &[0, 0], "reserved");
            assert_eq!(&bytes[2..4], &[1, 0], "type: icon");
            let count = u16::from_le_bytes([bytes[4], bytes[5]]) as usize;
            assert_eq!(count, ICO_SIZES.len());

            let mut cursor = 6 + 16 * count;
            for (i, size) in ICO_SIZES.iter().enumerate() {
                let entry = &bytes[6 + 16 * i..6 + 16 * i + 16];
                let expect = if *size >= 256 { 0 } else { *size as u8 };
                assert_eq!(entry[0], expect, "layer {size} width byte (0 = 256)");
                assert_eq!(entry[1], expect, "layer {size} height byte");
                let len = u32::from_le_bytes(entry[8..12].try_into().unwrap()) as usize;
                let offset = u32::from_le_bytes(entry[12..16].try_into().unwrap()) as usize;
                assert_eq!(offset, cursor, "layer {size} offset");
                assert_eq!(
                    &bytes[offset..offset + 8],
                    b"\x89PNG\r\n\x1a\n",
                    "png layer"
                );
                cursor = offset + len;
            }
            assert_eq!(bytes.len(), cursor, "no trailing bytes");
        }
    }
}

mod sign {
    #[cfg(windows)]
    use std::path::Path;
    use std::path::PathBuf;

    #[cfg(windows)]
    use super::StdCommand;
    use shun::config::SigningConfig;

    /// Signs each file per the platform profile. Windows: signtool from
    /// PATH or the newest Windows Kits install; timestamping via RFC 3161.
    pub fn sign_files(files: &[PathBuf], signing: &SigningConfig) -> Result<(), String> {
        #[cfg(windows)]
        {
            let Some(windows) = &signing.windows else {
                return Err("no windows signing profile in the delivery manifest".into());
            };
            if !windows.enabled {
                return Err("windows signing is disabled in the manifest".into());
            }
            let signtool = find_signtool().ok_or_else(|| {
                "signtool.exe not found (install the Windows SDK or add it to PATH)".to_string()
            })?;
            for file in files {
                let mut cmd = StdCommand::new(&signtool);
                cmd.arg("sign").arg("/fd").arg("SHA256");
                cmd.arg("/tr").arg(&windows.timestamp_url);
                cmd.arg("/td").arg("SHA256");
                if let Some(thumbprint) = &windows.thumbprint {
                    cmd.arg("/sha1").arg(thumbprint);
                } else {
                    cmd.arg("/a");
                }
                cmd.arg(file);
                let status = cmd
                    .status()
                    .map_err(|e| format!("cannot run signtool: {e}"))?;
                if !status.success() {
                    return Err(format!("signtool failed for {}", file.display()));
                }
                println!("signed {}", file.display());
            }
            Ok(())
        }
        #[cfg(not(windows))]
        {
            let _ = (files, signing);
            Err("signing is only implemented for windows in this build".into())
        }
    }

    #[cfg(windows)]
    fn find_signtool() -> Option<PathBuf> {
        // 1. PATH.
        if let Ok(path_var) = std::env::var("PATH") {
            for dir in std::env::split_paths(&path_var) {
                let candidate = dir.join("signtool.exe");
                if candidate.is_file() {
                    return Some(candidate);
                }
            }
        }
        // 2. Newest Windows Kits installation.
        let kits_root = std::env::var("ProgramFiles(x86)")
            .map(|root| Path::new(&root).join("Windows Kits").join("10").join("bin"))
            .ok()?;
        let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits_root)
            .ok()?
            .filter_map(Result::ok)
            .map(|e| e.path())
            .filter(|p| p.is_dir())
            .collect();
        versions.sort();
        for version in versions.iter().rev() {
            let candidate = version.join("x64").join("signtool.exe");
            if candidate.is_file() {
                return Some(candidate);
            }
        }
        None
    }
}

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

    /// The merges preserve caller flags, never duplicate the pin, and
    /// treat set-but-empty values as unset (the empty-var-to-clear
    /// idiom). The encoded lane appends ONE token — cargo passes those
    /// entries to rustc verbatim, so a space inside would fail the
    /// child build with `unknown codegen option: ' target-feature'`.
    #[test]
    fn merges_preserve_flags_and_stay_single_token() {
        assert_eq!(merged_rustflags(None), None);
        assert_eq!(merged_rustflags(Some("")), None);
        assert_eq!(merged_rustflags(Some("   ")), None);
        assert_eq!(
            merged_rustflags(Some("-C debuginfo=0")).as_deref(),
            Some("-C debuginfo=0 -C target-feature=+crt-static")
        );
        // Already pinned (either direction) — caller wins, no change.
        assert_eq!(merged_rustflags(Some(STATIC_CRT_FLAG)), None);
        assert_eq!(
            merged_rustflags(Some("-C target-feature=-crt-static -Zx")),
            None
        );

        assert_eq!(merged_encoded_rustflags(None), None);
        // Set-but-empty (bare separators included) degrades to unset.
        assert_eq!(merged_encoded_rustflags(Some("")), None);
        assert_eq!(merged_encoded_rustflags(Some("")), None);
        assert_eq!(
            merged_encoded_rustflags(Some("-Clink-arg=/x")).as_deref(),
            Some(format!("-Clink-arg=/x{ENCODED_SEP}{STATIC_CRT_FLAG_ENCODED}").as_str()),
        );
        // The appended entry carries no space — one argv token.
        assert!(!STATIC_CRT_FLAG_ENCODED.contains(' '));
        assert!(
            !merged_encoded_rustflags(Some("-Clink-arg=/x"))
                .unwrap()
                .rsplit(ENCODED_SEP)
                .next()
                .unwrap()
                .contains(' ')
        );
        assert_eq!(
            merged_encoded_rustflags(Some(format!("-Ca{ENCODED_SEP}{STATIC_CRT_FLAG}").as_str())),
            None,
        );
    }

    /// Only the msvc lane takes the pin: GNU targets keep their
    /// static-by-default mingw runtime, non-Windows has no VC++ CRT.
    #[test]
    fn pin_targets_only_msvc() {
        assert!(is_msvc_target(Some("x86_64-pc-windows-msvc")));
        assert!(is_msvc_target(Some("aarch64-pc-windows-msvc")));
        assert!(!is_msvc_target(Some("x86_64-pc-windows-gnu")));
        assert!(!is_msvc_target(Some("x86_64-unknown-linux-gnu")));
    }
}