cargo-truce 0.16.1

Build tool for truce audio plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
//! Windows packaging: Authenticode signing + Inno Setup installer.
//!
//! Flow: build each format (release) → stage into `target\package\windows\{suffix}\`
//! → Authenticode-sign binaries → PACE-sign AAX if present → render `.iss`
//! → run `ISCC.exe` → Authenticode-sign the installer → output to `dist\`.
//!
//! Builds are **universal by default** — both `x86_64-pc-windows-msvc` and
//! `aarch64-pc-windows-msvc` slices are produced and stitched into a single
//! Inno Setup installer that runs on both architectures. Bundle formats
//! (VST3, AAX) carry both archs in architecture-scoped subdirectories inside
//! the bundle and let the host pick at load time; single-file formats (CLAP,
//! VST2) use Inno Setup `Check:` directives to install the matching DLL for
//! the installing machine. Pass `--host-only` to skip the cross-arch build
//! for faster dev iteration (or use `--universal` explicitly as a no-op).

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::install_scope::{note_once, PkgScope};
use crate::{
    build_aax_template, cargo_build, detect_default_features, load_config, project_root,
    read_workspace_version, release_lib_for_target, resolve_aax_sdk_path, rustup_has_target,
    tmp_dir, Config, PkgFormat, PluginDef, Res, WindowsSigningConfig,
};

// ---------------------------------------------------------------------------
// Target architectures
// ---------------------------------------------------------------------------

/// Windows CPU architecture we can build for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TargetArch {
    X64,
    Arm64,
}

impl TargetArch {
    /// Architecture of the host running `cargo truce package`. Currently x64
    /// always — we don't have arm64 Windows as a supported host yet. Used to
    /// decide which archs can ship AAX (AAX template only builds for the host).
    fn host() -> Self {
        if cfg!(target_arch = "aarch64") {
            TargetArch::Arm64
        } else {
            TargetArch::X64
        }
    }

    /// Rust target triple passed to `cargo build --target`.
    fn triple(self) -> &'static str {
        match self {
            TargetArch::X64 => "x86_64-pc-windows-msvc",
            TargetArch::Arm64 => "aarch64-pc-windows-msvc",
        }
    }

    /// Short tag used in staging paths (`target/package/windows/{bundle_id}/clap/{tag}/…`).
    fn tag(self) -> &'static str {
        match self {
            TargetArch::X64 => "x64",
            TargetArch::Arm64 => "arm64",
        }
    }

    /// Arch sub-directory name inside a VST3 bundle (e.g. `Contents/x86_64-win/`).
    /// Steinberg defined `x86_64-win` and `arm64-win` for VST3 bundles on Windows.
    fn vst3_bundle_subdir(self) -> &'static str {
        match self {
            TargetArch::X64 => "x86_64-win",
            TargetArch::Arm64 => "arm64-win",
        }
    }

    /// Arch sub-directory name inside an AAX bundle (e.g. `Contents/x64/`).
    fn aax_bundle_subdir(self) -> &'static str {
        match self {
            TargetArch::X64 => "x64",
            TargetArch::Arm64 => "arm64",
        }
    }

    /// Inno Setup `Check:` predicate to guard this arch's `[Files]` entries.
    /// Returns the Pascal expression that should be true when the arch
    /// matches the machine running the installer.
    fn iss_check(self) -> &'static str {
        match self {
            TargetArch::X64 => "not IsArm64",
            TargetArch::Arm64 => "IsArm64",
        }
    }
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

pub(crate) fn cmd_package(args: &[String]) -> Res {
    let opts = parse_args(args)?;

    let config = load_config()?;
    let root = project_root();
    let version = read_workspace_version(&root).unwrap_or_else(|| "0.0.0".to_string());

    let formats = resolve_formats(&config, opts.format_str.as_deref())?;
    let plugins = resolve_plugins(&config, opts.plugin_filter.as_deref())?;
    let archs = opts.archs();
    let universal = archs.len() > 1;

    // Scope resolution: CLI > truce.toml [packaging] preferred_scope >
    // OS default (`--ask`).
    let scope = resolve_pkg_scope(opts.cli_scope, &config)?;
    eprintln!("Package scope: {}", scope.label());

    // System-only formats (AAX, VST2 on Windows) stay in the package
    // even under `--user`. The note tells the developer the end
    // user will see a UAC prompt for those. The `.iss` template
    // routes CLAP / VST3 to user paths and AAX / VST2 to system
    // paths in that mode (and bumps `PrivilegesRequired` to admin
    // so the installer can write to `{commoncf}` / `{pf}`).
    if matches!(scope, PkgScope::User) {
        for f in &formats {
            match f {
                PkgFormat::Aax => note_once(
                    "AAX is system-only; --user package keeps AAX but installs it to \
                     %COMMONPROGRAMFILES%\\Avid (end user will see one UAC prompt).",
                ),
                PkgFormat::Vst2 => note_once(
                    "VST2 on Windows is system-only; --user package keeps VST2 but installs \
                     it to %PROGRAMFILES%\\Steinberg\\VstPlugins (end user will see one UAC prompt).",
                ),
                _ => {}
            }
        }
    }

    if universal && formats.iter().any(|f| matches!(f, PkgFormat::Aax)) {
        eprintln!(
            "NOTE: AAX is host-arch-only ({}); the universal installer won't \
             carry an ARM64 AAX bundle. Avid's AAX SDK 2.9 ships x64 libs only, \
             and our template build (vcvars64 + MSVC) is x64-only. CLAP/VST2/VST3 \
             ship universally; AAX stays single-arch.",
            TargetArch::host().tag(),
        );
    }

    // Warn about missing signing credentials unless --no-sign was passed.
    if !opts.no_sign && !config.windows.signing.is_configured() {
        eprintln!(
            "WARNING: [windows.signing] has no credentials configured. Binaries and \
             installer will be unsigned. Pass --no-sign to silence this warning, or \
             set azure_account / sha1 / pfx_path under [windows.signing] in truce.toml."
        );
    }

    build_all_formats(&plugins, &formats, &archs, &root)?;

    let dist_dir = crate::target_dir(&root).join("dist");
    fs::create_dir_all(&dist_dir)?;

    for p in &plugins {
        eprintln!("\n=== Packaging: {} ({}) ===", p.name, archs_label(&archs));

        let staging = crate::target_dir(&root)
            .join("package/windows")
            .join(&p.bundle_id);
        let _ = fs::remove_dir_all(&staging);
        fs::create_dir_all(&staging)?;

        let mut all_signable: Vec<PathBuf> = Vec::new();
        for &arch in &archs {
            let staged = stage_plugin(&root, p, &config, &formats, &staging, arch)?;
            all_signable.extend(staged.signable);
        }

        if !opts.no_sign {
            // PACE-sign every AAX bundle (one per arch). PACE wraps the binary;
            // Authenticode signs the wrapped result — so PACE first.
            // `--no-pace-sign` (or `--no-sign`) skips the wraptool round-trip
            // while keeping Authenticode for smoke tests.
            if !opts.no_pace_sign && formats.iter().any(|f| matches!(f, PkgFormat::Aax)) {
                let aax_bundle = staging.join(format!("{}.aaxplugin", p.name));
                for &arch in &archs {
                    let inner_wrapper = aax_bundle
                        .join("Contents")
                        .join(arch.aax_bundle_subdir())
                        .join(format!("{}.aaxplugin", p.name));
                    if inner_wrapper.exists() {
                        pace_sign_aax(&inner_wrapper)?;
                    }
                }
            }
            sign_files(&all_signable, &config.windows.signing)?;
        }

        if opts.no_installer {
            eprintln!(
                "  Skipped installer build (--no-installer). Staging at {}",
                staging.display()
            );
            continue;
        }

        let iss = render_iss(
            &config, p, &formats, &archs, &staging, &version, &dist_dir, scope,
        );
        let iss_path = staging.join("installer.iss");
        fs::write(&iss_path, &iss)?;
        run_iscc(&iss_path)?;

        let installer = dist_dir.join(format!(
            "{}-{}-windows{}.exe",
            p.name,
            version,
            scope.dist_suffix()
        ));
        if !installer.exists() {
            return Err(format!(
                "ISCC reported success but installer is missing: {}",
                installer.display()
            )
            .into());
        }

        if !opts.no_sign {
            sign_files(std::slice::from_ref(&installer), &config.windows.signing)?;
        }
        eprintln!("  Installer: {}", installer.display());
    }

    eprintln!("\nDone. Installers in {}", dist_dir.display());
    Ok(())
}

fn archs_label(archs: &[TargetArch]) -> String {
    archs.iter().map(|a| a.tag()).collect::<Vec<_>>().join("+")
}

// ---------------------------------------------------------------------------
// Argument parsing
// ---------------------------------------------------------------------------

#[derive(Default)]
struct Opts {
    plugin_filter: Option<String>,
    format_str: Option<String>,
    no_sign: bool,
    /// Skip just PACE — Authenticode still runs. Useful for dev iteration when
    /// the slow PACE round-trip isn't needed but we still want a signed
    /// installer for smoke testing. `--no-sign` implies this.
    no_pace_sign: bool,
    no_installer: bool,
    /// Build only the host arch. Default is universal (x64 + ARM64) so a
    /// single `cargo truce package` run produces the release artefact users
    /// expect; `--host-only` opts out for dev iteration speed.
    host_only: bool,
    /// Install scope the resulting installer targets. `--ask` (the
    /// default) lets the end user pick at install time via Inno
    /// Setup's "Choose installation mode" page; `--user` /
    /// `--system` hard-lock to one mode.
    cli_scope: Option<PkgScope>,
}

impl Opts {
    fn archs(&self) -> Vec<TargetArch> {
        if self.host_only {
            vec![TargetArch::host()]
        } else {
            vec![TargetArch::X64, TargetArch::Arm64]
        }
    }
}

fn set_cli_scope(slot: &mut Option<PkgScope>, want: PkgScope) -> Res {
    if let Some(prev) = *slot {
        if prev != want {
            return Err("--user, --system, and --ask are mutually exclusive".into());
        }
    }
    *slot = Some(want);
    Ok(())
}

fn resolve_pkg_scope(cli: Option<PkgScope>, config: &Config) -> Result<PkgScope, crate::BoxErr> {
    if let Some(s) = cli {
        return Ok(s);
    }
    if let Some(ref raw) = config.packaging.preferred_scope {
        return PkgScope::parse_toml_value(raw).map_err(|e| -> crate::BoxErr { e.into() });
    }
    Ok(PkgScope::os_default())
}

fn parse_args(args: &[String]) -> std::result::Result<Opts, crate::BoxErr> {
    let mut opts = Opts::default();
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "-p" => {
                i += 1;
                opts.plugin_filter = Some(
                    args.get(i)
                        .cloned()
                        .ok_or("-p requires a plugin crate name")?,
                );
            }
            "--formats" => {
                i += 1;
                opts.format_str = Some(args.get(i).cloned().ok_or("--formats requires a value")?);
            }
            "--no-sign" => opts.no_sign = true,
            "--no-pace-sign" => opts.no_pace_sign = true,
            "--no-installer" => opts.no_installer = true,
            "--user" => set_cli_scope(&mut opts.cli_scope, PkgScope::User)?,
            "--system" => set_cli_scope(&mut opts.cli_scope, PkgScope::System)?,
            "--ask" => set_cli_scope(&mut opts.cli_scope, PkgScope::Ask)?,
            // Universal is the default; accepted explicitly as a no-op so
            // existing CI scripts (and cross-platform invocations) keep working.
            "--universal" => {}
            "--host-only" => opts.host_only = true,
            // --no-notarize is a macOS concept; accept and ignore on Windows so
            // cross-platform CI scripts don't break.
            "--no-notarize" => {}
            other => return Err(format!("unknown flag: {other}").into()),
        }
        i += 1;
    }
    Ok(opts)
}

fn resolve_formats(
    config: &Config,
    format_str: Option<&str>,
) -> std::result::Result<Vec<PkgFormat>, crate::BoxErr> {
    let raw = if let Some(s) = format_str {
        PkgFormat::parse_list(s)?
    } else if !config.packaging.formats.is_empty() {
        PkgFormat::parse_list(&config.packaging.formats.join(","))?
    } else {
        let available: HashSet<String> = detect_default_features();
        let mut fmts = Vec::new();
        if available.contains("clap") {
            fmts.push(PkgFormat::Clap);
        }
        if available.contains("vst3") {
            fmts.push(PkgFormat::Vst3);
        }
        if available.contains("vst2") {
            fmts.push(PkgFormat::Vst2);
        }
        if available.contains("aax") {
            fmts.push(PkgFormat::Aax);
        }
        fmts
    };

    // AU v2 / v3 are macOS-only. Drop silently: we don't want cross-platform
    // truce.toml files to error on the Windows runner just because they list
    // au2/au3 for macOS.
    let filtered: Vec<PkgFormat> = raw
        .into_iter()
        .filter(|f| !matches!(f, PkgFormat::Au2 | PkgFormat::Au3))
        .collect();

    if filtered.is_empty() {
        return Err("no Windows-eligible formats selected (AU is macOS-only)".into());
    }
    Ok(filtered)
}

fn resolve_plugins<'a>(
    config: &'a Config,
    filter: Option<&str>,
) -> std::result::Result<Vec<&'a PluginDef>, crate::BoxErr> {
    Ok(if let Some(filter) = filter {
        let matched: Vec<&PluginDef> = config
            .plugin
            .iter()
            .filter(|p| p.crate_name == filter)
            .collect();
        if matched.is_empty() {
            return Err(format!(
                "No plugin with crate name '{filter}'. Available: {}",
                config
                    .plugin
                    .iter()
                    .map(|p| p.crate_name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
            .into());
        }
        matched
    } else {
        config.plugin.iter().collect()
    })
}

// ---------------------------------------------------------------------------
// Build
// ---------------------------------------------------------------------------

/// Run the cargo builds for each selected format × arch. Mirrors cmd_package
/// on macOS: one `cargo build` per format with distinct `--features` so the
/// format-specific code paths can't cross-contaminate, plus an outer loop
/// over architectures.
///
/// Within a single arch the dylib at `target/{triple}/release/{stem}.dll` is
/// overwritten by successive format builds, so we save per-format copies
/// (`{stem}_clap`, `{stem}_vst3`, `{stem}_vst2`, `{stem}_aax`) after each
/// build. Archs have separate `target/{triple}/` directories so they don't
/// clash with each other.
fn build_all_formats(
    plugins: &[&PluginDef],
    formats: &[PkgFormat],
    archs: &[TargetArch],
    root: &Path,
) -> Res {
    let dt = ""; // MACOSX_DEPLOYMENT_TARGET is ignored on Windows

    let has_clap = formats.iter().any(|f| matches!(f, PkgFormat::Clap));
    let has_vst3 = formats.iter().any(|f| matches!(f, PkgFormat::Vst3));
    let has_vst2 = formats.iter().any(|f| matches!(f, PkgFormat::Vst2));
    let has_aax = formats.iter().any(|f| matches!(f, PkgFormat::Aax));

    for &arch in archs {
        eprintln!("--- Building for {} ---", arch.tag());
        let triple = arch.triple();

        if has_clap {
            eprintln!("Building CLAP ({})...", arch.tag());
            let mut build_args: Vec<String> = vec!["--target".into(), triple.into()];
            for p in plugins {
                build_args.push("-p".into());
                build_args.push(p.crate_name.clone());
            }
            build_args.extend_from_slice(&[
                "--no-default-features".into(),
                "--features".into(),
                "clap".into(),
            ]);
            let arg_refs: Vec<&str> = build_args.iter().map(|s| s.as_str()).collect();
            cargo_build(&[], &arg_refs, dt)?;
            for p in plugins {
                let src = release_lib_for_target(root, &p.dylib_stem(), Some(triple));
                let saved =
                    release_lib_for_target(root, &format!("{}_clap", p.dylib_stem()), Some(triple));
                if src.exists() {
                    fs::copy(&src, &saved)?;
                }
            }
        }

        if has_vst3 {
            eprintln!("Building VST3 ({})...", arch.tag());
            let mut build_args: Vec<String> = vec!["--target".into(), triple.into()];
            for p in plugins {
                build_args.push("-p".into());
                build_args.push(p.crate_name.clone());
            }
            build_args.extend_from_slice(&[
                "--no-default-features".into(),
                "--features".into(),
                "vst3".into(),
            ]);
            let arg_refs: Vec<&str> = build_args.iter().map(|s| s.as_str()).collect();
            cargo_build(&[], &arg_refs, dt)?;
            for p in plugins {
                let src = release_lib_for_target(root, &p.dylib_stem(), Some(triple));
                let saved =
                    release_lib_for_target(root, &format!("{}_vst3", p.dylib_stem()), Some(triple));
                if src.exists() {
                    fs::copy(&src, &saved)?;
                }
            }
        }

        if has_vst2 {
            eprintln!("Building VST2 ({})...", arch.tag());
            let mut build_args: Vec<String> = vec!["--target".into(), triple.into()];
            for p in plugins {
                build_args.push("-p".into());
                build_args.push(p.crate_name.clone());
            }
            build_args.extend_from_slice(&[
                "--no-default-features".into(),
                "--features".into(),
                "vst2".into(),
            ]);
            let arg_refs: Vec<&str> = build_args.iter().map(|s| s.as_str()).collect();
            cargo_build(&[], &arg_refs, dt)?;
            for p in plugins {
                let src = release_lib_for_target(root, &p.dylib_stem(), Some(triple));
                let dst =
                    release_lib_for_target(root, &format!("{}_vst2", p.dylib_stem()), Some(triple));
                fs::copy(&src, &dst)?;
            }
        }

        // AAX staging is host-arch-only (see stage_aax), so only build the
        // AAX Rust cdylib for the host arch. The Rust code itself cross-
        // compiles fine — we're just avoiding orphan binaries that would
        // have nothing to pair with in the installer.
        if has_aax && arch == TargetArch::host() {
            eprintln!("Building AAX ({})...", arch.tag());
            let mut build_args: Vec<String> = vec!["--target".into(), triple.into()];
            for p in plugins {
                build_args.push("-p".into());
                build_args.push(p.crate_name.clone());
            }
            build_args.extend_from_slice(&[
                "--no-default-features".into(),
                "--features".into(),
                "aax".into(),
            ]);
            let arg_refs: Vec<&str> = build_args.iter().map(|s| s.as_str()).collect();
            cargo_build(&[], &arg_refs, dt)?;
            for p in plugins {
                let src = release_lib_for_target(root, &p.dylib_stem(), Some(triple));
                let dst =
                    release_lib_for_target(root, &format!("{}_aax", p.dylib_stem()), Some(triple));
                fs::copy(&src, &dst)?;
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Staging
// ---------------------------------------------------------------------------

struct StagedPlugin {
    /// Files to feed signtool for one arch's staging pass.
    signable: Vec<PathBuf>,
}

/// Stage a single plugin for one architecture. Multi-arch packaging calls
/// this once per arch; the bundle formats (VST3, AAX) accumulate arch-scoped
/// subdirectories in the same bundle root across calls.
fn stage_plugin(
    root: &Path,
    p: &PluginDef,
    config: &Config,
    formats: &[PkgFormat],
    staging: &Path,
    arch: TargetArch,
) -> std::result::Result<StagedPlugin, crate::BoxErr> {
    let mut signable = Vec::new();
    for fmt in formats {
        eprint!("  Staging {} ({})... ", fmt.label(), arch.tag());
        match fmt {
            PkgFormat::Clap => {
                signable.push(stage_clap(root, p, staging, arch)?);
            }
            PkgFormat::Vst3 => {
                signable.push(stage_vst3(root, p, staging, arch)?);
            }
            PkgFormat::Vst2 => {
                signable.push(stage_vst2(root, p, staging, arch)?);
            }
            PkgFormat::Aax => match stage_aax(root, p, config, staging, arch)? {
                Some((wrapper, dylib)) => {
                    signable.push(dylib);
                    signable.push(wrapper);
                }
                None => {
                    eprintln!("skipped (AAX template is built for host arch only)");
                    continue;
                }
            },
            PkgFormat::Au2 | PkgFormat::Au3 => {
                return Err("AU is macOS-only; should have been filtered".into());
            }
        }
        eprintln!("ok");
    }
    Ok(StagedPlugin { signable })
}

fn stage_clap(
    root: &Path,
    p: &PluginDef,
    staging: &Path,
    arch: TargetArch,
) -> std::result::Result<PathBuf, crate::BoxErr> {
    let dll = release_lib_for_target(
        root,
        &format!("{}_clap", p.dylib_stem()),
        Some(arch.triple()),
    );
    if !dll.exists() {
        return Err(format!("Missing: {}", dll.display()).into());
    }
    let dst_dir = staging.join("clap").join(arch.tag());
    fs::create_dir_all(&dst_dir)?;
    let dst = dst_dir.join(format!("{}.clap", p.name));
    fs::copy(&dll, &dst)?;
    Ok(dst)
}

fn stage_vst3(
    root: &Path,
    p: &PluginDef,
    staging: &Path,
    arch: TargetArch,
) -> std::result::Result<PathBuf, crate::BoxErr> {
    // VST3 on Windows is a bundle directory. Multi-arch bundles carry both
    // arch subdirs side-by-side — the host picks at load time.
    let dll = release_lib_for_target(
        root,
        &format!("{}_vst3", p.dylib_stem()),
        Some(arch.triple()),
    );
    if !dll.exists() {
        return Err(format!("Missing: {}", dll.display()).into());
    }
    let bundle_root = staging.join("vst3");
    let bundle = bundle_root.join(format!("{}.vst3", p.name));
    let arch_dir = bundle.join("Contents").join(arch.vst3_bundle_subdir());
    fs::create_dir_all(&arch_dir)?;
    let inner = arch_dir.join(format!("{}.vst3", p.name));
    fs::copy(&dll, &inner)?;
    Ok(inner)
}

fn stage_vst2(
    root: &Path,
    p: &PluginDef,
    staging: &Path,
    arch: TargetArch,
) -> std::result::Result<PathBuf, crate::BoxErr> {
    let dll = release_lib_for_target(
        root,
        &format!("{}_vst2", p.dylib_stem()),
        Some(arch.triple()),
    );
    if !dll.exists() {
        return Err(format!("Missing: {}", dll.display()).into());
    }
    let dst_dir = staging.join("vst2").join(arch.tag());
    fs::create_dir_all(&dst_dir)?;
    let dst = dst_dir.join(format!("{}.dll", p.name));
    fs::copy(&dll, &dst)?;
    Ok(dst)
}

/// Build/stage the AAX bundle for one architecture. Returns
/// `Some((wrapper_binary, resources_dylib))` on success so both get
/// Authenticode-signed, or `None` when the arch can't be staged (today,
/// anything that isn't the host arch — see below).
///
/// For universal builds the host-arch pass writes under
/// `{Name}.aaxplugin/Contents/{x64,arm64}/` + `Contents/Resources/`.
///
/// ### Cross-arch AAX is intentionally skipped
///
/// The AAX template (`TruceAAXTemplate.aaxplugin`) is a C++ bundle that
/// links against Avid's AAX SDK libraries. Our `build_aax_template()` runs
/// cmake + MSVC via `vcvars64.bat`, which produces an x64 binary. To
/// produce an ARM64 template we'd need both:
///
/// 1. A cross-compile path via `vcvars_arm64.bat` / `vcvarsx86_arm64.bat`.
/// 2. ARM64 `AAX_SDK_Interface.lib` / `AAXLibrary.lib` from Avid. As of
///    AAX SDK 2.9 Avid ships x64 libs only — attempting to link arm64
///    objects against the x64 libs will fail at link time.
///
/// Rather than silently shipping an x64 template inside the arm64 bundle
/// subdir (which would fail to load at runtime), we skip AAX staging for
/// non-host archs and warn. CLAP/VST2/VST3 still ship universally; AAX
/// stays host-arch-only.
fn stage_aax(
    root: &Path,
    p: &PluginDef,
    config: &Config,
    staging: &Path,
    arch: TargetArch,
) -> std::result::Result<Option<(PathBuf, PathBuf)>, crate::BoxErr> {
    if arch != TargetArch::host() {
        return Ok(None);
    }

    // Build the template .aaxplugin wrapper if it isn't there yet.
    let template = tmp_dir().join("aax_template/build/TruceAAXTemplate.aaxplugin");
    if !template.exists() {
        if let Some(sdk_path) = resolve_aax_sdk_path(config) {
            eprintln!("AAX: building template with SDK at {}", sdk_path.display());
            // On Windows, AAX stays host-arch regardless (SDK 2.9 ships x64
            // libs only — see stage_aax comments). `universal_mac` is a no-op.
            build_aax_template(root, &sdk_path, false)?;
        } else {
            return Err(
                "AAX SDK not configured. Set [windows].aax_sdk_path in truce.toml or \
                 AAX_SDK_PATH env var."
                    .into(),
            );
        }
    }
    if !template.exists() {
        return Err("AAX template build succeeded but binary not found".into());
    }

    let dylib = release_lib_for_target(
        root,
        &format!("{}_aax", p.dylib_stem()),
        Some(arch.triple()),
    );
    if !dylib.exists() {
        return Err(format!(
            "Missing AAX Rust cdylib for {}: {}",
            arch.tag(),
            dylib.display()
        )
        .into());
    }

    let bundle_root = staging.join("aax");
    let bundle = bundle_root.join(format!("{}.aaxplugin", p.name));
    let contents = bundle.join("Contents");
    let arch_dir = contents.join(arch.aax_bundle_subdir());
    let resources_dir = contents.join("Resources");
    fs::create_dir_all(&arch_dir)?;
    fs::create_dir_all(&resources_dir)?;

    let wrapper = arch_dir.join(format!("{}.aaxplugin", p.name));
    // Arch-tagged dylib so multi-arch bundles don't collide in Resources/.
    // The bridge C++ code scans Resources/*.dll via FindFirstFileA and loads
    // the first one whose arch matches the current process — arch tagging
    // in the filename is purely for storage; the binary's own arch header
    // determines what LoadLibrary accepts.
    let resource_dll = resources_dir.join(format!("{}_aax_{}.dll", p.dylib_stem(), arch.tag()));
    fs::copy(&template, &wrapper)?;
    fs::copy(&dylib, &resource_dll)?;

    Ok(Some((wrapper, resource_dll)))
}

// ---------------------------------------------------------------------------
// Authenticode signing (signtool.exe)
// ---------------------------------------------------------------------------

fn sign_files(files: &[PathBuf], config: &WindowsSigningConfig) -> Res {
    if files.is_empty() {
        return Ok(());
    }
    if !config.is_configured() {
        // No creds — emit a single notice and carry on. The warning at the top
        // of cmd_package already covered the "why."
        return Ok(());
    }
    let signtool = locate_signtool()
        .ok_or("signtool.exe not found on PATH. Install the Windows 10 SDK or Windows 11 SDK.")?;

    let mut args: Vec<String> = vec![
        "sign".into(),
        "/fd".into(),
        "SHA256".into(),
        "/tr".into(),
        config.resolved_timestamp_url().to_string(),
        "/td".into(),
        "SHA256".into(),
    ];

    // Credential source — Azure wins, then thumbprint, then pfx.
    if let (Some(account), Some(profile)) = (&config.azure_account, &config.azure_profile) {
        let dlib = config.azure_dlib.clone().unwrap_or_else(default_azure_dlib);
        let metadata_path = tmp_dir().join("truce_azure_signing_metadata.json");
        let metadata = format!(
            r#"{{
  "Endpoint": "https://eus.codesigning.azure.net/",
  "CodeSigningAccountName": "{account}",
  "CertificateProfileName": "{profile}"
}}"#,
            account = account,
            profile = profile,
        );
        fs::write(&metadata_path, metadata)?;
        args.extend_from_slice(&[
            "/dlib".into(),
            dlib,
            "/dmdf".into(),
            metadata_path.display().to_string(),
        ]);
    } else if let Some(sha1) = &config.sha1 {
        args.extend_from_slice(&["/sha1".into(), sha1.clone()]);
        if let Some(store) = &config.cert_store {
            args.extend_from_slice(&["/s".into(), store.clone()]);
        }
    } else if let Some(pfx) = &config.pfx_path {
        args.extend_from_slice(&["/f".into(), pfx.clone()]);
        if let Ok(pw) = std::env::var("TRUCE_PFX_PASSWORD") {
            args.extend_from_slice(&["/p".into(), pw]);
        }
    }

    for f in files {
        args.push(f.display().to_string());
    }

    eprintln!("  signtool: signing {} file(s)", files.len());
    let status = Command::new(&signtool).args(&args).status()?;
    if !status.success() {
        return Err("signtool failed".into());
    }
    Ok(())
}

fn default_azure_dlib() -> String {
    r"C:\Program Files\Microsoft Trusted Signing Client\bin\x64\Azure.CodeSigning.Dlib.dll"
        .to_string()
}

fn locate_signtool() -> Option<PathBuf> {
    if let Ok(p) = which("signtool.exe") {
        return Some(p);
    }
    let candidates = [r"C:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe"];
    for c in &candidates {
        let p = PathBuf::from(c);
        if p.exists() {
            return Some(p);
        }
    }
    let sdk_bin = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin");
    if let Ok(entries) = fs::read_dir(&sdk_bin) {
        let mut best: Option<PathBuf> = None;
        for e in entries.flatten() {
            let candidate = e.path().join(r"x64\signtool.exe");
            if candidate.exists() {
                match &best {
                    None => best = Some(candidate),
                    Some(current) => {
                        if candidate > *current {
                            best = Some(candidate);
                        }
                    }
                }
            }
        }
        if best.is_some() {
            return best;
        }
    }
    None
}

pub(crate) fn locate_iscc() -> Option<PathBuf> {
    if let Ok(p) = which("ISCC.exe") {
        return Some(p);
    }
    for c in [
        r"C:\Program Files (x86)\Inno Setup 6\ISCC.exe",
        r"C:\Program Files\Inno Setup 6\ISCC.exe",
    ] {
        let p = PathBuf::from(c);
        if p.exists() {
            return Some(p);
        }
    }
    None
}

pub(crate) fn locate_wraptool() -> Option<PathBuf> {
    if let Ok(p) = which("wraptool.exe") {
        return Some(p);
    }
    None
}

fn which(name: &str) -> Result<PathBuf, std::io::Error> {
    let path = std::env::var_os("PATH")
        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "PATH not set"))?;
    for dir in std::env::split_paths(&path) {
        let candidate = dir.join(name);
        if candidate.is_file() {
            return Ok(candidate);
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        name.to_string(),
    ))
}

// ---------------------------------------------------------------------------
// PACE / iLok signing (AAX)
// ---------------------------------------------------------------------------

fn pace_sign_aax(bundle: &Path) -> Res {
    let Some(wraptool) = locate_wraptool() else {
        eprintln!(
            "  wraptool.exe not found — AAX bundle is unsigned for PACE. \
             Pro Tools Developer will still load it; release builds need PACE."
        );
        return Ok(());
    };
    let pace_account = match std::env::var("PACE_ACCOUNT") {
        Ok(v) => v,
        Err(_) => {
            eprintln!(
                "  PACE_ACCOUNT env var not set — skipping PACE signing. \
                 Pro Tools Developer will still load the bundle."
            );
            return Ok(());
        }
    };
    let pace_signid = match std::env::var("PACE_SIGN_ID") {
        Ok(v) => v,
        Err(_) => {
            eprintln!("  PACE_SIGN_ID env var not set — skipping PACE signing.");
            return Ok(());
        }
    };

    eprintln!("  wraptool: PACE-signing {}", bundle.display());
    let status = Command::new(&wraptool)
        .args([
            "sign",
            "--account",
            &pace_account,
            "--signid",
            &pace_signid,
            "--allowsigningservice",
            "--in",
            bundle.to_str().unwrap(),
            "--out",
            bundle.to_str().unwrap(),
        ])
        .status()?;
    if !status.success() {
        return Err("wraptool failed".into());
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Inno Setup
// ---------------------------------------------------------------------------

#[allow(clippy::too_many_arguments)]
fn render_iss(
    config: &Config,
    p: &PluginDef,
    formats: &[PkgFormat],
    archs: &[TargetArch],
    staging: &Path,
    version: &str,
    dist_dir: &Path,
    scope: PkgScope,
) -> String {
    let publisher = config
        .windows
        .packaging
        .publisher
        .as_deref()
        .unwrap_or(&config.vendor.name);
    let publisher_url = config
        .windows
        .packaging
        .publisher_url
        .clone()
        .or_else(|| config.vendor.url.clone())
        .unwrap_or_default();

    let app_id = config
        .windows
        .packaging
        .app_id
        .clone()
        .unwrap_or_else(|| format!("{}.{}", config.vendor.id, p.bundle_id));

    let root = project_root();

    let installer_icon = config
        .windows
        .packaging
        .installer_icon
        .as_ref()
        .map(|s| root.join(s))
        .filter(|p| p.exists());
    let welcome_bmp = config
        .windows
        .packaging
        .welcome_bmp
        .as_ref()
        .map(|s| root.join(s))
        .filter(|p| p.exists());
    let license_rtf = config
        .windows
        .packaging
        .license_rtf
        .as_ref()
        .map(|s| root.join(s))
        .filter(|p| p.exists());

    let universal = archs.len() > 1;

    let mut setup = String::new();
    setup.push_str("[Setup]\r\n");
    setup.push_str(&format!("AppId={{{{{}}}}}\r\n", iss_escape(&app_id)));
    setup.push_str(&format!("AppName={}\r\n", iss_escape(&p.name)));
    setup.push_str(&format!("AppVersion={}\r\n", iss_escape(version)));
    setup.push_str(&format!("AppPublisher={}\r\n", iss_escape(publisher)));
    if !publisher_url.is_empty() {
        setup.push_str(&format!(
            "AppPublisherURL={}\r\n",
            iss_escape(&publisher_url)
        ));
    }
    setup.push_str(&format!(
        "DefaultDirName={{commonpf}}\\{}\\{}\r\n",
        iss_escape(publisher),
        iss_escape(&p.name),
    ));
    setup.push_str("DisableDirPage=yes\r\n");
    setup.push_str(&format!("OutputDir={}\r\n", iss_escape_path(dist_dir)));
    setup.push_str(&format!(
        "OutputBaseFilename={}-{}-windows\r\n",
        iss_escape(&p.name),
        iss_escape(version),
    ));
    setup.push_str("Compression=lzma2\r\n");
    setup.push_str("SolidCompression=yes\r\n");
    if universal {
        // x64compatible includes both x64 and ARM64 hosts; that's what we want
        // for a universal installer. Inno Setup 6.3+ exposes IsArm64 so [Files]
        // entries can split on arch.
        setup.push_str("ArchitecturesInstallIn64BitMode=x64compatible\r\n");
        setup.push_str("ArchitecturesAllowed=x64compatible\r\n");
    } else {
        // Single-arch x64 installer. Explicitly rule out ARM64 so the installer
        // doesn't run on machines where none of its binaries would work.
        setup.push_str("ArchitecturesInstallIn64BitMode=x64compatible\r\n");
        setup.push_str("ArchitecturesAllowed=x64compatible and not arm64\r\n");
    }
    // PrivilegesRequired drives whether the installer relaunches
    // itself elevated before the wizard even appears.
    //   --user   → `lowest` if no system-only payloads (AAX, VST2);
    //              `admin` otherwise — AAX / VST2 still need to write
    //              under %COMMONPROGRAMFILES%/%PROGRAMFILES% so the
    //              whole installer escalates once for them while
    //              CLAP / VST3 still target user paths.
    //   --system → `admin`. UAC on launch, lands under system paths.
    //   --ask    → `admin` + `PrivilegesRequiredOverridesAllowed=...`
    //              shows the "Choose installation mode" page and
    //              relaunches elevated only if the user picks all-users.
    let has_system_only_format = formats
        .iter()
        .any(|f| matches!(f, PkgFormat::Aax | PkgFormat::Vst2));
    match scope {
        PkgScope::User if has_system_only_format => {
            setup.push_str("PrivilegesRequired=admin\r\n");
        }
        PkgScope::User => {
            setup.push_str("PrivilegesRequired=lowest\r\n");
        }
        PkgScope::System => {
            setup.push_str("PrivilegesRequired=admin\r\n");
        }
        PkgScope::Ask => {
            setup.push_str("PrivilegesRequired=admin\r\n");
            setup.push_str("PrivilegesRequiredOverridesAllowed=commandline dialog\r\n");
        }
    }
    setup.push_str("WizardStyle=modern\r\n");
    setup.push_str("UninstallDisplayName=");
    setup.push_str(&iss_escape(&p.name));
    setup.push_str("\r\n");
    if let Some(icon) = &installer_icon {
        setup.push_str(&format!("SetupIconFile={}\r\n", iss_escape_path(icon)));
    }
    if let Some(bmp) = &welcome_bmp {
        setup.push_str(&format!("WizardImageFile={}\r\n", iss_escape_path(bmp)));
    }
    if let Some(rtf) = &license_rtf {
        setup.push_str(&format!("LicenseFile={}\r\n", iss_escape_path(rtf)));
    }
    setup.push_str("\r\n");

    // [Types] — full vs custom
    setup.push_str("[Types]\r\n");
    setup.push_str("Name: \"full\"; Description: \"Full installation\"\r\n");
    setup.push_str(
        "Name: \"custom\"; Description: \"Custom installation\"; Flags: iscustom\r\n\r\n",
    );

    // [Components] — one per format.
    setup.push_str("[Components]\r\n");
    for fmt in formats {
        let (name, desc, types) = iss_component_spec(fmt);
        setup.push_str(&format!(
            "Name: \"{}\"; Description: \"{}\"; Types: {}\r\n",
            name, desc, types
        ));
    }
    setup.push_str("\r\n");

    // [Files] — one block per format × arch.
    setup.push_str("[Files]\r\n");
    for fmt in formats {
        for &arch in archs {
            let block = iss_files_block(fmt, p, staging, arch, universal, scope);
            setup.push_str(&block);
        }
    }
    setup.push_str("\r\n");

    // [UninstallDelete] — per-format (bundle dirs get wholesale cleanup).
    setup.push_str("[UninstallDelete]\r\n");
    for fmt in formats {
        for line in iss_uninstall_lines(fmt, &p.name, scope) {
            setup.push_str(&line);
            setup.push_str("\r\n");
        }
    }

    setup
}

fn iss_component_spec(fmt: &PkgFormat) -> (&'static str, &'static str, &'static str) {
    match fmt {
        PkgFormat::Clap => ("clap", "CLAP (Reaper, Bitwig)", "full"),
        PkgFormat::Vst3 => ("vst3", "VST3 (most DAWs)", "full"),
        PkgFormat::Vst2 => ("vst2", "VST2 (legacy — Reaper, older hosts)", "custom"),
        PkgFormat::Aax => ("aax", "AAX (Pro Tools)", "full"),
        PkgFormat::Au2 | PkgFormat::Au3 => unreachable!("AU is filtered out on Windows"),
    }
}

/// Build the `[Files]` entries for one format × arch. For single-file formats
/// (CLAP, VST2) we gate with a `Check:` directive so only the matching arch's
/// DLL is installed on a given machine. Bundle formats (VST3, AAX) install
/// both archs side-by-side; the host picks at load time.
///
/// Scope-driven destinations:
/// - `--system` and `--user` use a single hard-coded DestDir.
/// - `--ask` emits *two* entries for CLAP / VST3 (system + user) gated on
///   `IsAdminInstallMode` so the runtime install mode picks one. AAX always
///   stays system-rooted with `Check: IsAdminInstallMode` — end users who
///   pick "for me only" simply don't get AAX (per the install-scope doc).
fn iss_files_block(
    fmt: &PkgFormat,
    p: &PluginDef,
    staging: &Path,
    arch: TargetArch,
    universal: bool,
    scope: PkgScope,
) -> String {
    // For single-arch installers the Check: directive is unnecessary — drop it
    // so the output .iss stays simple.
    let arch_check = if universal {
        Some(arch.iss_check())
    } else {
        None
    };

    match fmt {
        PkgFormat::Clap => {
            let src = staging
                .join("clap")
                .join(arch.tag())
                .join(format!("{}.clap", p.name));
            let src_quoted = iss_escape_path(&src);
            iss_dual_dest(
                scope,
                &src_quoted,
                "{commoncf}\\CLAP",
                "{localappdata}\\Programs\\Common\\CLAP",
                "clap",
                arch_check,
                /* is_dir= */ false,
            )
        }
        PkgFormat::Vst3 => {
            // Bundle: copy just this arch's sub-directory. No Check: — hosts
            // of either arch can coexist on ARM64 machines (x64 hosts run via
            // emulation), so both sub-dirs should always be present.
            let src_dir = staging
                .join("vst3")
                .join(format!("{}.vst3", p.name))
                .join("Contents")
                .join(arch.vst3_bundle_subdir());
            let src_glob = src_dir.join("*");
            let src_quoted = iss_escape_path(&src_glob);
            let name = iss_escape(&p.name);
            let subdir = arch.vst3_bundle_subdir();
            let system_dest = format!("{{commoncf}}\\VST3\\{name}.vst3\\Contents\\{subdir}");
            let user_dest = format!(
                "{{localappdata}}\\Programs\\Common\\VST3\\{name}.vst3\\Contents\\{subdir}"
            );
            iss_dual_dest(
                scope,
                &src_quoted,
                &system_dest,
                &user_dest,
                "vst3",
                /* arch_check = */ None,
                /* is_dir = */ true,
            )
        }
        PkgFormat::Vst2 => {
            // Windows VST2 has no settled per-user path; in `--ask` mode
            // the doc keeps it system-only with `Check: IsAdminInstallMode`,
            // so end users in for-me-only mode simply don't receive VST2.
            // `--user` already filtered it out before render_iss is called.
            let src = staging
                .join("vst2")
                .join(arch.tag())
                .join(format!("{}.dll", p.name));
            let src_quoted = iss_escape_path(&src);
            iss_admin_only(
                scope,
                &src_quoted,
                "{pf}\\Steinberg\\VstPlugins",
                "vst2",
                arch_check,
                /* is_dir = */ false,
            )
        }
        PkgFormat::Aax => {
            // AAX bundle: arch subdir + arch-tagged resource DLL. Non-host
            // arches are skipped at stage time (see stage_aax); if the arch
            // subdir doesn't exist in staging, don't emit an .iss reference
            // to it — ISCC would fail on a missing Source otherwise.
            let src_arch_dir = staging
                .join("aax")
                .join(format!("{}.aaxplugin", p.name))
                .join("Contents")
                .join(arch.aax_bundle_subdir());
            if !src_arch_dir.exists() {
                return String::new();
            }
            let src_arch_glob = src_arch_dir.join("*");
            let resource_dll = staging
                .join("aax")
                .join(format!("{}.aaxplugin", p.name))
                .join("Contents")
                .join("Resources")
                .join(format!("{}_aax_{}.dll", p.dylib_stem(), arch.tag()));
            let name = iss_escape(&p.name);
            let subdir = arch.aax_bundle_subdir();
            let bundle_root = format!("{{commoncf}}\\Avid\\Audio\\Plug-Ins\\{name}.aaxplugin");
            let mut out = String::new();
            out.push_str(&iss_admin_only(
                scope,
                &iss_escape_path(&src_arch_glob),
                &format!("{bundle_root}\\Contents\\{subdir}"),
                "aax",
                /* arch_check = */ None,
                /* is_dir = */ true,
            ));
            out.push_str(&iss_admin_only(
                scope,
                &iss_escape_path(&resource_dll),
                &format!("{bundle_root}\\Contents\\Resources"),
                "aax",
                /* arch_check = */ None,
                /* is_dir = */ false,
            ));
            out
        }
        PkgFormat::Au2 | PkgFormat::Au3 => unreachable!(),
    }
}

/// Emit the `[Files]` line(s) for a system-or-user-aware destination.
/// Under `--ask` two lines are produced, branched on `IsAdminInstallMode`.
fn iss_dual_dest(
    scope: PkgScope,
    src_quoted: &str,
    system_dest: &str,
    user_dest: &str,
    component: &str,
    arch_check: Option<&str>,
    is_dir: bool,
) -> String {
    let dir_flags = if is_dir {
        " recursesubdirs createallsubdirs"
    } else {
        ""
    };
    let arch_clause = arch_check.map(|c| format!(" and {c}")).unwrap_or_default();
    match scope {
        PkgScope::System => {
            let arch = arch_check
                .map(|c| format!(" Check: {c};"))
                .unwrap_or_default();
            format!(
                "Source: \"{src_quoted}\"; DestDir: \"{system_dest}\"; \
                 Components: {component};{arch} \
                 Flags: ignoreversion overwritereadonly{dir_flags}\r\n"
            )
        }
        PkgScope::User => {
            let arch = arch_check
                .map(|c| format!(" Check: {c};"))
                .unwrap_or_default();
            format!(
                "Source: \"{src_quoted}\"; DestDir: \"{user_dest}\"; \
                 Components: {component};{arch} \
                 Flags: ignoreversion overwritereadonly{dir_flags}\r\n"
            )
        }
        PkgScope::Ask => {
            // Two entries, branched on IsAdminInstallMode. Inno Setup
            // sets it after the "Choose installation mode" page; only
            // one of the two `Check:` predicates fires per install.
            format!(
                "Source: \"{src_quoted}\"; DestDir: \"{system_dest}\"; \
                 Components: {component}; Check: IsAdminInstallMode{arch_clause}; \
                 Flags: ignoreversion overwritereadonly{dir_flags}\r\n\
                 Source: \"{src_quoted}\"; DestDir: \"{user_dest}\"; \
                 Components: {component}; Check: (not IsAdminInstallMode){arch_clause}; \
                 Flags: ignoreversion overwritereadonly{dir_flags}\r\n"
            )
        }
    }
}

/// Emit the `[Files]` line for a payload that is always system-rooted
/// (AAX, Windows VST2). `--system` and `--user` (which has already
/// bumped `PrivilegesRequired` to admin in the caller) both copy
/// unconditionally; `--ask` gates on `IsAdminInstallMode` so end users
/// who pick "for me only" see CLAP/VST3 land in user paths and AAX /
/// VST2 simply skip.
fn iss_admin_only(
    scope: PkgScope,
    src_quoted: &str,
    system_dest: &str,
    component: &str,
    arch_check: Option<&str>,
    is_dir: bool,
) -> String {
    let dir_flags = if is_dir {
        " recursesubdirs createallsubdirs"
    } else {
        ""
    };
    let arch_clause = arch_check.map(|c| format!(" and {c}")).unwrap_or_default();
    match scope {
        PkgScope::System | PkgScope::User => {
            let arch = arch_check
                .map(|c| format!(" Check: {c};"))
                .unwrap_or_default();
            format!(
                "Source: \"{src_quoted}\"; DestDir: \"{system_dest}\"; \
                 Components: {component};{arch} \
                 Flags: ignoreversion overwritereadonly{dir_flags}\r\n"
            )
        }
        PkgScope::Ask => format!(
            "Source: \"{src_quoted}\"; DestDir: \"{system_dest}\"; \
             Components: {component}; Check: IsAdminInstallMode{arch_clause}; \
             Flags: ignoreversion overwritereadonly{dir_flags}\r\n"
        ),
    }
}

fn iss_uninstall_lines(fmt: &PkgFormat, plugin_name: &str, scope: PkgScope) -> Vec<String> {
    let name = iss_escape(plugin_name);
    let system = match fmt {
        PkgFormat::Vst3 => Some(format!("{{commoncf}}\\VST3\\{name}.vst3")),
        PkgFormat::Aax => Some(format!(
            "{{commoncf}}\\Avid\\Audio\\Plug-Ins\\{name}.aaxplugin"
        )),
        _ => None,
    };
    let user = match fmt {
        PkgFormat::Vst3 => Some(format!(
            "{{localappdata}}\\Programs\\Common\\VST3\\{name}.vst3"
        )),
        // AAX has no per-user uninstall path (always system).
        _ => None,
    };
    let component = match fmt {
        PkgFormat::Vst3 => "vst3",
        PkgFormat::Aax => "aax",
        _ => return Vec::new(),
    };
    let mut out = Vec::new();
    if let Some(p) = system.as_ref() {
        if matches!(scope, PkgScope::System | PkgScope::Ask) {
            out.push(format!(
                "Type: filesandordirs; Name: \"{p}\"; Components: {component}"
            ));
        }
    }
    if let Some(p) = user.as_ref() {
        if matches!(scope, PkgScope::User | PkgScope::Ask) {
            out.push(format!(
                "Type: filesandordirs; Name: \"{p}\"; Components: {component}"
            ));
        }
    }
    out
}

fn run_iscc(iss_path: &Path) -> Res {
    let iscc = locate_iscc().ok_or(
        "ISCC.exe not found. Install Inno Setup 6 from https://jrsoftware.org/isinfo.php \
         or pass --no-installer to skip installer generation.",
    )?;
    eprintln!("  iscc: {}", iss_path.display());
    let status = Command::new(&iscc).arg(iss_path).status()?;
    if !status.success() {
        return Err("ISCC.exe failed".into());
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// .iss value escaping
// ---------------------------------------------------------------------------

fn iss_escape(s: &str) -> String {
    s.replace('"', "\"\"")
}

fn iss_escape_path(p: &Path) -> String {
    let s = p.display().to_string();
    let s = s.replace('/', "\\");
    iss_escape(&s)
}

// ---------------------------------------------------------------------------
// Doctor hook
// ---------------------------------------------------------------------------

pub(crate) fn doctor() {
    match locate_iscc() {
        Some(p) => eprintln!("    ✅ Inno Setup 6 (ISCC.exe) at {}", p.display()),
        None => {
            eprintln!("    ⚠️  ISCC.exe not found — install Inno Setup 6 to produce installers")
        }
    }
    match locate_signtool() {
        Some(p) => eprintln!("    ✅ signtool.exe at {}", p.display()),
        None => {
            eprintln!("    ⚠️  signtool.exe not found — install Windows 10/11 SDK for Authenticode")
        }
    }
    match locate_wraptool() {
        Some(p) => eprintln!("    ✅ wraptool.exe (PACE) at {}", p.display()),
        None => eprintln!("    ℹ️  wraptool.exe not found — only needed for signed AAX builds"),
    }

    // ARM64 readiness. Universal is the default, so missing ARM64 toolchain
    // downgrades to a warning (packages with `--host-only` still work).
    let has_rust_arm64 = rustup_has_target("aarch64-pc-windows-msvc");
    let has_msvc_arm64 = has_arm64_msvc_toolchain();
    match (has_rust_arm64, has_msvc_arm64) {
        (true, true) => eprintln!(
            "    ✅ ARM64 cross-compile available — `cargo truce package` will produce dual-arch installers by default"
        ),
        (true, false) => eprintln!(
            "    ⚠️  Rust has aarch64-pc-windows-msvc but VS is missing the ARM64 MSVC toolchain — C++ shims won't cross-compile. Install \"MSVC v143 - VS 2022 C++ ARM64/ARM64EC build tools\" via the VS Installer, or pass `--host-only` to skip ARM64."
        ),
        (false, true) => eprintln!(
            "    ⚠️  VS has ARM64 MSVC but the Rust target isn't installed — run: rustup target add aarch64-pc-windows-msvc (or pass `--host-only` to skip)"
        ),
        (false, false) => eprintln!(
            "    ⚠️  ARM64 cross-compile not set up. `cargo truce package` defaults to universal and will fail without it — add the Rust target and the VS ARM64 toolchain, or pass `--host-only` to skip ARM64."
        ),
    }
}

/// Look for an `arm64` lib directory under any VS MSVC toolchain version.
/// Presence of the lib dir is a reliable signal that the "ARM64 build tools"
/// component was installed. We don't require the cross-compiler binary to
/// live in a specific path — cc/build will locate it via vcvars_arm64.bat
/// when the Rust target triple requests it.
fn has_arm64_msvc_toolchain() -> bool {
    for vs_root in crate::vs_install_paths() {
        let msvc_root = vs_root.join(r"VC\Tools\MSVC");
        if let Ok(versions) = fs::read_dir(&msvc_root) {
            for v in versions.flatten() {
                if v.path().join(r"lib\arm64").is_dir() {
                    return true;
                }
            }
        }
    }
    false
}