shun 0.2.16

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
//! 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.
    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,
    },
    /// 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.
    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);
    }
}

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,
        } => {
            let config = resolve_config(&manifest)?;
            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}"))?;
            let shell_bin = shell_package
                .get("package")
                .and_then(|p| p.get("name"))
                .and_then(toml::Value::as_str)
                .unwrap_or("shun-demo-shell")
                .to_string();

            let status = StdCommand::new("cargo")
                .args([
                    "build",
                    "--release",
                    "--manifest-path",
                    &shell_manifest.display().to_string(),
                ])
                .env(
                    "SHUN_MANIFEST",
                    std::fs::canonicalize(&manifest).map_err(|e| e.to_string())?,
                )
                .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_exe = shell_src
                .join("..")
                .join("target")
                .join("release")
                .join(format!("{shell_bin}.exe"));
            let installer = out.join(format!(
                "{}-{}-setup.exe",
                product.name.to_lowercase().replace(' ', "-"),
                product.version
            ));
            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::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],
    ];

    /// Derives per-OS icon sets from one square logo:
    /// - windows/icon.ico (multi-size, from the largest render)
    /// - 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 = image::DynamicImage::ImageRgba8(img.clone());
        ico.save_with_format(windows_dir.join("icon.ico"), image::ImageFormat::Ico)
            .map_err(|e| format!("ico encode: {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(())
    }
}

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
    }
}