embala 0.8.0

One config, every installer — .msi, .app, .deb, .pkg, and Chocolatey .nupkg from any host OS
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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
//! `embala.toml` schema and validation.

// Section fields go live as each backend consumes them; until every backend
// exists the compiler sees some as unread.
#![allow(dead_code)]

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

use anyhow::{Context, Result, bail};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Config {
    pub package: Package,
    pub msi: Option<MsiSection>,
    pub app: Option<AppSection>,
    pub pkg: Option<PkgSection>,
    pub nupkg: Option<NupkgSection>,
    pub setup: Option<SetupSection>,
    pub sign: Option<SignSection>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Package {
    pub name: String,
    pub display_name: String,
    pub version: String,
    pub identifier: String,
    pub publisher: String,
    pub description: String,
    pub homepage: Option<String>,
    pub license: Option<String>,
    pub copyright: Option<String>,
    pub tags: Option<Vec<String>>,
    pub icon: Option<PathBuf>,
    #[serde(default)]
    pub require_license_acceptance: bool,
}

/// A payload file: `src` is resolved relative to the config file's directory,
/// `dest` is the format-specific install-relative path.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileEntry {
    pub src: PathBuf,
    pub dest: String,
    /// Drop the entry from the build when `src` is not found.
    #[serde(default)]
    pub optional: bool,
}

/// A `[pkg]` payload file: a [`FileEntry`] plus an optional install mode. Its
/// own type so `mode` fails to parse in formats that cannot honor it.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PkgFileEntry {
    pub src: PathBuf,
    pub dest: String,
    /// Permission bits, e.g. `0o600`. Absent: `0o755` if `src` is
    /// executable, else `0o644`.
    #[serde(default, deserialize_with = "permission_bits")]
    pub mode: Option<u32>,
    /// Drop the entry from the build when `src` is not found.
    #[serde(default)]
    pub optional: bool,
}

/// What [`drop_absent`] needs from either payload entry type.
trait Payload {
    fn src(&self) -> &Path;
    fn dest(&self) -> &str;
    fn optional(&self) -> bool;
}

impl Payload for FileEntry {
    fn src(&self) -> &Path {
        &self.src
    }
    fn dest(&self) -> &str {
        &self.dest
    }
    fn optional(&self) -> bool {
        self.optional
    }
}

impl Payload for PkgFileEntry {
    fn src(&self) -> &Path {
        &self.src
    }
    fn dest(&self) -> &str {
        &self.dest
    }
    fn optional(&self) -> bool {
        self.optional
    }
}

/// An `optional` entry [`drop_absent`] removed: its dest and resolved src.
struct Dropped {
    dest: String,
    src: PathBuf,
}

/// Remove every `optional` entry whose `src` (resolved against `base`) is not
/// found, printing one note per skip to stderr. Returns what was removed.
fn drop_absent<T: Payload>(section: &str, files: &mut Vec<T>, base: &Path) -> Result<Vec<Dropped>> {
    let mut dropped = Vec::new();
    let mut kept = Vec::with_capacity(files.len());
    for file in files.drain(..) {
        let src = base.join(file.src());
        if file.optional() && optional_src_absent(&src)? {
            eprintln!("{section}: skipped optional {} (not found)", src.display());
            dropped.push(Dropped {
                dest: file.dest().to_string(),
                src,
            });
        } else {
            kept.push(file);
        }
    }
    *files = kept;
    Ok(dropped)
}

/// Whether an optional `src` is absent. Only "not found" counts as absent:
/// the probe is `symlink_metadata`, not `exists`/`try_exists`, because those
/// follow symlinks and report a dangling one as absent. A dangling symlink,
/// at `src` or at its nearest existing ancestor, is a broken build input, so
/// it is an error, as is a present `src` that is not a regular file or any
/// other I/O error (e.g. permission denied).
fn optional_src_absent(src: &Path) -> Result<bool> {
    use std::io::ErrorKind::NotFound;
    // With a trailing separator or `.`, lstat follows a final symlink and a
    // dangling one reads as NotFound.
    let src = trim_trailing(src);
    match std::fs::symlink_metadata(src) {
        Ok(_) => {
            let meta = std::fs::metadata(src).map_err(|e| match e.kind() {
                NotFound => anyhow::anyhow!("optional src {} is a dangling symlink", src.display()),
                _ => {
                    anyhow::Error::new(e).context(format!("reading optional src {}", src.display()))
                }
            })?;
            if !meta.is_file() {
                bail!("optional src {} is not a regular file", src.display());
            }
            Ok(false)
        }
        Err(e) if e.kind() == NotFound => {
            // A dangling symlinked parent directory also surfaces as
            // NotFound for `src`; catch it at the nearest existing ancestor.
            let nearest = src
                .ancestors()
                .skip(1)
                .find(|a| std::fs::symlink_metadata(a).is_ok());
            if let Some(link) = nearest {
                if link.is_symlink() && std::fs::metadata(link).is_err() {
                    bail!(
                        "optional src {}: ancestor {} is a dangling symlink",
                        src.display(),
                        link.display()
                    );
                }
            }
            Ok(true)
        }
        Err(e) => Err(e).with_context(|| format!("reading optional src {}", src.display())),
    }
}

/// `path` without trailing separators or `.` components, never trimming into
/// its prefix or root (`/`, `C:\`, `\\server\share\`, `\\?\C:\`). This strips
/// text rather than rebuilding from `components()`: `PathBuf::push` re-parses
/// each component, so on Windows `C:\stage\c:credentials` would collapse to the
/// drive-relative `c:credentials`. Separators are `/` on Unix and `/` or `\`
/// on Windows, except that verbatim (`\\?\`) paths use only `\` and keep `.`
/// literally, as `components()` treats them.
fn trim_trailing(path: &Path) -> &Path {
    use std::path::Component;
    let bytes = path.as_os_str().as_encoded_bytes();
    let (mut floor, verbatim) = match path.components().next() {
        Some(Component::Prefix(p)) => (p.as_os_str().len(), p.kind().is_verbatim()),
        _ => (0, false),
    };
    let is_sep = |b: u8| (b == b'\\' && cfg!(windows)) || (b == b'/' && !verbatim);
    if bytes.get(floor).is_some_and(|&b| is_sep(b)) {
        floor += 1;
    }
    let mut end = bytes.len();
    while end > floor {
        let last = bytes[end - 1];
        let dot_component = last == b'.' && !verbatim && end >= 2 && is_sep(bytes[end - 2]);
        if !is_sep(last) && !dot_component {
            break;
        }
        end -= 1;
    }
    // SAFETY: the bytes come from `as_encoded_bytes` and are cut immediately
    // before an ASCII `/`, `\` or `.`, a boundary the encoding allows.
    Path::new(unsafe { std::ffi::OsStr::from_encoded_bytes_unchecked(&bytes[..end]) })
}

/// Fail when a config field names a dest only a skipped optional entry
/// provided, instead of building a package that points at nothing. `kept` is
/// every dest still in the build (another entry may provide the same dest).
fn ensure_not_dropped<'a>(
    section: &str,
    dropped: &[Dropped],
    kept: &[&str],
    refs: impl IntoIterator<Item = (String, &'a str)>,
) -> Result<()> {
    for (field, dest) in refs {
        if kept.contains(&dest) {
            continue;
        }
        if let Some(d) = dropped.iter().find(|d| d.dest == dest) {
            bail!(
                "{section}: {field} {dest:?} is an optional file that was absent ({} not found)",
                d.src.display()
            );
        }
    }
    Ok(())
}

/// A `[pkg]` directory declared to set its mode or to ship it empty.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PkgDirEntry {
    pub dest: String,
    /// Permission bits, e.g. `0o700`. Absent: `0o755`.
    #[serde(default, deserialize_with = "permission_bits")]
    pub mode: Option<u32>,
}

/// Accept only `0o000`-`0o777`: setuid, setgid and sticky are not supported.
fn permission_bits<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> std::result::Result<Option<u32>, D::Error> {
    let mode = u32::deserialize(deserializer)?;
    if mode > 0o777 {
        return Err(serde::de::Error::custom(format!(
            "mode {mode:#o} must be permission bits only (0o000-0o777)"
        )));
    }
    Ok(Some(mode))
}

/// Windows Installer only supports 64-bit targets in embala; 32-bit configs
/// are rejected at parse time (unknown variant).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum MsiArch {
    #[serde(rename = "x86_64")]
    X86_64,
    #[serde(rename = "aarch64")]
    Aarch64,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct MsiSection {
    pub arch: MsiArch,
    pub files: Vec<FileEntry>,
    pub main_executable: String,
    /// Installs `executable` (default `main-executable`) as a Windows service
    /// (ServiceInstall/ServiceControl tables; name rules are checked by
    /// embala-msi).
    pub service: Option<MsiService>,
    /// Append the install directory to the system PATH.
    #[serde(default)]
    pub add_to_path: bool,
}

impl MsiSection {
    /// Drop absent optional files; `main-executable` and the service
    /// executable must not name one.
    pub fn drop_absent_optional(&mut self, base: &Path) -> Result<()> {
        let dropped = drop_absent("msi", &mut self.files, base)?;
        let kept: Vec<&str> = self.files.iter().map(|f| f.dest.as_str()).collect();
        let service = self.service.as_ref().and_then(|s| s.executable.as_deref());
        ensure_not_dropped(
            "msi",
            &dropped,
            &kept,
            [("main-executable".to_string(), self.main_executable.as_str())]
                .into_iter()
                .chain(service.map(|e| ("service executable".to_string(), e))),
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ServiceStart {
    Auto,
    Demand,
    Disabled,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct MsiService {
    pub name: String,
    pub display_name: Option<String>,
    pub description: Option<String>,
    pub start: ServiceStart,
    pub arguments: Option<String>,
    /// Dest of the file the service runs; defaults to `main-executable`.
    pub executable: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct AppSection {
    pub executable: PathBuf,
    pub icon: Option<PathBuf>,
    pub minimum_system_version: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct PkgSection {
    pub files: Vec<PkgFileEntry>,
    /// Directories to create with an explicit mode, even if empty.
    #[serde(default)]
    pub directories: Vec<PkgDirEntry>,
    pub install_location: String,
    /// Marks the package installable into the user's home directory
    /// (`installer -target CurrentUserHomeDirectory`) — the sudo-free test hook.
    #[serde(default)]
    pub enable_user_home: bool,
    /// `pkgbuild --scripts` directory (relative to the config dir): packed
    /// whole; top-level `preinstall`/`postinstall` run as install hooks.
    pub scripts: Option<PathBuf>,
}

impl PkgSection {
    /// Drop absent optional files. Nothing else in `[pkg]` names a file dest.
    pub fn drop_absent_optional(&mut self, base: &Path) -> Result<()> {
        drop_absent("pkg", &mut self.files, base).map(drop)
    }

    /// The `embala-pkg` spec for this section, with `src` and `scripts`
    /// resolved against `base` (the config file's directory).
    pub fn spec(&self, package: &Package, base: &Path) -> embala_pkg::PkgSpec {
        embala_pkg::PkgSpec {
            name: package.name.clone(),
            display_name: package.display_name.clone(),
            identifier: package.identifier.clone(),
            version: package.version.clone(),
            install_location: self.install_location.clone(),
            enable_user_home: self.enable_user_home,
            files: self
                .files
                .iter()
                .map(|f| embala_pkg::FileSpec {
                    src: base.join(&f.src),
                    dest: f.dest.clone(),
                    mode: f.mode,
                })
                .collect(),
            directories: self
                .directories
                .iter()
                .map(|d| embala_pkg::DirSpec {
                    dest: d.dest.clone(),
                    mode: d.mode,
                })
                .collect(),
            scripts: self.scripts.as_ref().map(|s| base.join(s)),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum NupkgStyle {
    Embedded,
    Download,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct NupkgSection {
    pub style: NupkgStyle,
    #[serde(default)]
    pub files: Vec<FileEntry>,
    pub url: Option<String>,
    pub checksum: Option<String>,
    pub project_source_url: Option<String>,
    pub package_source_url: Option<String>,
    pub release_notes: Option<String>,
    pub icon_url: Option<String>,
    pub license_url: Option<String>,
}

impl NupkgSection {
    /// Drop absent optional files. Download style never reads `src`, and
    /// validation rejects `optional` there, so it has nothing to drop.
    pub fn drop_absent_optional(&mut self, base: &Path) -> Result<()> {
        drop_absent("nupkg", &mut self.files, base).map(drop)
    }
}

/// Windows setup.exe selects the embedded stub by arch; only 64-bit targets
/// exist (unknown variants are rejected at parse time).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, clap::ValueEnum)]
pub enum SetupArch {
    #[serde(rename = "x86_64")]
    #[value(name = "x86_64")]
    X86_64,
    #[serde(rename = "aarch64")]
    #[value(name = "aarch64")]
    Aarch64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum InstallMode {
    #[default]
    PerUser,
    PerMachine,
    UserChoice,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum ShortcutLocation {
    #[default]
    StartMenu,
    Desktop,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Component {
    pub id: String,
    pub label: String,
    pub description: Option<String>,
    #[serde(default)]
    pub default: bool,
    #[serde(default)]
    pub files: Vec<FileEntry>,
}

/// A declarative uninstall option (spec R2): a labelled checkbox the uninstaller
/// confirm dialog shows, readable from `uninstall.lua` via `ui.selected(id)`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct UninstallOptionEntry {
    pub id: String,
    pub label: String,
    #[serde(default)]
    pub default: bool,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Shortcut {
    pub name: String,
    /// Dest (relative to install dir) the shortcut targets.
    pub target: String,
    pub args: Option<String>,
    pub icon: Option<String>,
    #[serde(default)]
    pub location: ShortcutLocation,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct SetupSection {
    pub arch: SetupArch,
    pub files: Vec<FileEntry>,
    /// Dest of the shortcut target + ARP DisplayIcon, relative to install dir.
    pub main_executable: Option<String>,
    /// Stub icon (PNG/ICO), relative to the config dir; falls back to
    /// `[package].icon` (the `[app]` convention) when unset (spec R7).
    pub icon: Option<PathBuf>,
    /// Wizard banner (BMP, magic `BM`), relative to the config dir, patched as
    /// the `EMBALA_BANNER` resource (spec R7).
    pub banner: Option<PathBuf>,
    #[serde(default)]
    pub install_mode: InstallMode,
    /// Path (relative to the config dir) to a license text file.
    pub license: Option<PathBuf>,
    #[serde(default)]
    pub components: Vec<Component>,
    #[serde(default)]
    pub shortcuts: Vec<Shortcut>,
    /// Declarative uninstall options (spec R2). Allowed with both declarative and
    /// raw-`script` configs (they concern uninstall, not install lowering).
    #[serde(default)]
    pub uninstall_options: Vec<UninstallOptionEntry>,
    /// Escape-hatch path to a raw `install.lua` (relative to the config dir).
    pub script: Option<PathBuf>,
    pub uninstall_script: Option<PathBuf>,
}

impl SetupSection {
    /// Every dest a completed install would carry (top-level + component files).
    /// Used to check shortcut/main-executable targets resolve (spec R20).
    fn installed_dests(&self) -> Vec<&str> {
        self.files
            .iter()
            .chain(self.components.iter().flat_map(|c| c.files.iter()))
            .map(|f| f.dest.as_str())
            .collect()
    }

    /// Drop absent optional files, top-level and per component, before
    /// lowering sees them; `main-executable` (shortcut, ARP DisplayIcon,
    /// finish-page run) and shortcut targets must not name one.
    pub fn drop_absent_optional(&mut self, base: &Path) -> Result<()> {
        let mut dropped = drop_absent("setup", &mut self.files, base)?;
        for component in &mut self.components {
            dropped.extend(drop_absent("setup", &mut component.files, base)?);
        }
        let main = self
            .main_executable
            .as_deref()
            .map(|m| ("main-executable".to_string(), m));
        let targets = self
            .shortcuts
            .iter()
            .map(|s| (format!("shortcut {:?} target", s.name), s.target.as_str()));
        ensure_not_dropped(
            "setup",
            &dropped,
            &self.installed_dests(),
            main.into_iter().chain(targets),
        )
    }
}

/// User-supplied signing commands (spec R5/R6). embala never implements a
/// signature format — it only shells out to `command` with `$f` = the
/// artifact's absolute path.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct SignSection {
    pub windows: Option<WindowsSign>,
    pub macos: Option<MacosSign>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct WindowsSign {
    pub command: String,
    /// Path (relative to the config dir) to a pre-signed bare uninstall stub;
    /// when set, embala embeds it instead of signing the embedded stub itself.
    pub signed_stub: Option<PathBuf>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct MacosSign {
    pub command: String,
}

impl Config {
    /// `version` (the CLI's `--version`) replaces `[package].version` before
    /// validation, so an override gets the same version check as the file.
    pub fn load(path: &Path, version: Option<&str>) -> Result<Self> {
        let text = std::fs::read_to_string(path)
            .with_context(|| format!("reading config {}", path.display()))?;
        let mut config: Config =
            toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
        if let Some(version) = version {
            config.package.version = version.to_string();
        }
        config.validate()?;
        Ok(config)
    }

    fn validate(&self) -> Result<()> {
        let p = &self.package;
        if p.name.is_empty()
            || !p
                .name
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
        {
            bail!("package.name must match [a-z0-9-]+ (got {:?})", p.name);
        }
        // An optional fourth component is a build number. MSI and VERSIONINFO
        // store it as a 16-bit field, so it is capped at 65535.
        let version_parts: Vec<&str> = p.version.split('.').collect();
        if !(3..=4).contains(&version_parts.len())
            || version_parts
                .iter()
                .any(|s| s.is_empty() || !s.chars().all(|c| c.is_ascii_digit()))
            || version_parts
                .get(3)
                .is_some_and(|build| build.parse::<u16>().is_err())
        {
            bail!(
                "package.version must be numeric x.y.z or x.y.z.build (build <= 65535) — \
                 MSI requires it (got {:?})",
                p.version
            );
        }
        let id_segments: Vec<&str> = p.identifier.split('.').collect();
        if id_segments.len() < 2
            || id_segments
                .iter()
                .any(|s| s.is_empty() || !s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
        {
            bail!(
                "package.identifier must be reverse-DNS-like, e.g. com.example.app (got {:?})",
                p.identifier
            );
        }
        // Tags are space-joined into the nuspec <tags> element, so whitespace
        // inside one tag would silently split it.
        for tag in p.tags.iter().flatten() {
            if tag.is_empty() || tag.chars().any(char::is_whitespace) {
                bail!(
                    "package.tags entries must be non-empty and contain no whitespace (got {:?})",
                    tag
                );
            }
        }
        if let Some(nupkg) = &self.nupkg {
            match nupkg.style {
                NupkgStyle::Download if nupkg.url.is_none() || nupkg.checksum.is_none() => {
                    bail!("nupkg: style \"download\" requires both url and checksum");
                }
                NupkgStyle::Embedded if nupkg.url.is_some() || nupkg.checksum.is_some() => {
                    bail!("nupkg: url/checksum are only valid with style \"download\"");
                }
                _ => {}
            }
            if nupkg.style == NupkgStyle::Download && nupkg.files.iter().any(|f| f.optional) {
                bail!("nupkg: optional has no effect with style \"download\" (src is never read)");
            }
            if p.require_license_acceptance && nupkg.license_url.is_none() {
                bail!(
                    "package.require-license-acceptance = true requires nupkg.license-url \
                     (Chocolatey rejects the package otherwise)"
                );
            }
        }
        if let Some(setup) = &self.setup {
            validate_setup(setup)?;
        }
        if let Some(pkg) = &self.pkg {
            // Layout rules (dest shape, duplicates, file/directory
            // conflicts) belong to embala-pkg; run them now so a bad [pkg]
            // fails before any format builds. No filesystem access.
            embala_pkg::validate(&pkg.spec(p, Path::new("")))?;
        }
        if let Some(sign) = &self.sign {
            // signed-stub existence is a build-time check (needs the config dir);
            // it lives in `build_setup`, mirroring `validate_setup_paths`.
            for (platform, command) in [
                ("windows", sign.windows.as_ref().map(|w| &w.command)),
                ("macos", sign.macos.as_ref().map(|m| &m.command)),
            ] {
                if let Some(command) = command {
                    if command.is_empty() || !command.contains("$f") {
                        bail!(
                            "sign.{platform}: command must be non-empty and contain $f (got {:?})",
                            command
                        );
                    }
                }
            }
        }
        Ok(())
    }
}

/// Structural `[setup]` validation (spec R20), no filesystem access. The `src`-
/// existence and `license`-path checks need the config-dir base and so live in
/// `build_setup` (`main.rs`), which resolves it.
fn validate_setup(setup: &SetupSection) -> Result<()> {
    // A raw script owns install behavior; the declarative sugar it would
    // conflict with must not also be present (surface it, don't silently drop).
    if setup.script.is_some()
        && (!setup.components.is_empty()
            || !setup.shortcuts.is_empty()
            || setup.main_executable.is_some())
    {
        bail!(
            "setup: `script` cannot be combined with `components`, `shortcuts`, or \
             `main-executable` — the raw script owns that behavior"
        );
    }
    let mut ids = std::collections::BTreeSet::new();
    for component in &setup.components {
        if !ids.insert(component.id.as_str()) {
            bail!("setup: duplicate component id {:?}", component.id);
        }
    }
    // Uninstall options: non-empty unique ids, non-empty labels (spec R2). The
    // ids reach `ui.selected(id)` at uninstall, so a blank/dup id is a hard error.
    let mut opt_ids = std::collections::BTreeSet::new();
    for option in &setup.uninstall_options {
        if option.id.is_empty() {
            bail!("setup: uninstall-option id must be non-empty");
        }
        if option.label.is_empty() {
            bail!(
                "setup: uninstall-option {:?} label must be non-empty",
                option.id
            );
        }
        if !opt_ids.insert(option.id.as_str()) {
            bail!("setup: duplicate uninstall-option id {:?}", option.id);
        }
    }
    let dests = setup.installed_dests();
    if let Some(main) = &setup.main_executable {
        if !dests.contains(&main.as_str()) {
            bail!(
                "setup: main-executable {:?} is not among the installed file dests",
                main
            );
        }
    }
    for shortcut in &setup.shortcuts {
        if !dests.contains(&shortcut.target.as_str()) {
            bail!(
                "setup: shortcut {:?} target {:?} is not among the installed file dests",
                shortcut.name,
                shortcut.target
            );
        }
    }
    Ok(())
}

/// Filesystem `[setup]` validation (spec R20): every `src` and the optional
/// `license`/`script` paths must exist, resolved relative to `base` (the config
/// file's directory). Called from `build_setup`, which knows `base`.
pub fn validate_setup_paths(setup: &SetupSection, base: &Path) -> Result<()> {
    let srcs = setup
        .files
        .iter()
        .chain(setup.components.iter().flat_map(|c| c.files.iter()))
        .map(|f| &f.src);
    for src in srcs {
        let resolved = base.join(src);
        if !resolved.exists() {
            bail!("setup: payload src {} does not exist", resolved.display());
        }
    }
    for (field, path) in [
        ("license", &setup.license),
        ("script", &setup.script),
        ("uninstall-script", &setup.uninstall_script),
        ("icon", &setup.icon),
        ("banner", &setup.banner),
    ] {
        if let Some(path) = path {
            let resolved = base.join(path);
            if !resolved.exists() {
                bail!("setup: {field} path {} does not exist", resolved.display());
            }
        }
    }
    // The banner is patched as a raw bitmap resource, so reject anything that is
    // not a BMP up front rather than shipping a broken wizard (spec R7).
    if let Some(banner) = &setup.banner {
        let resolved = base.join(banner);
        let head = std::fs::read(&resolved)?;
        if !head.starts_with(b"BM") {
            bail!(
                "setup: banner {} must be a BMP (magic \"BM\")",
                resolved.display()
            );
        }
    }
    Ok(())
}

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

    fn fixture_toml() -> String {
        std::fs::read_to_string(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../fixtures/hello/embala.toml"
        ))
        .expect("fixture config")
    }

    fn parse(text: &str) -> Result<Config> {
        let config: Config = toml::from_str(text)?;
        config.validate()?;
        Ok(config)
    }

    #[test]
    fn fixture_config_parses_with_all_sections() {
        let config = parse(&fixture_toml()).expect("fixture must be valid");
        assert_eq!(config.package.name, "hello");
        assert_eq!(config.package.identifier, "ca.hrndz.embala.hello");
        assert!(config.msi.is_some());
        assert!(config.app.is_some());
        assert!(config.pkg.is_some());
        assert!(config.nupkg.is_some());
        assert!(config.setup.is_some());
        // Phase 4: the fixture carries the nupkg metadata end-to-end. Keep the
        // [package].icon fallback path exercised — the fixture no longer sets
        // [app].icon, so the .app builder must fall back to [package].icon.
        assert_eq!(
            config.package.copyright.as_deref(),
            Some("© 2026 Carlos Hernandez")
        );
        assert_eq!(
            config.package.tags.as_deref(),
            Some(&["cli".to_string(), "embala".to_string(), "demo".to_string()][..])
        );
        assert_eq!(config.package.icon.as_deref(), Some(Path::new("icon.png")));
        // require-license-acceptance stays unset so the choco-install gate is
        // acceptance-prompt-free.
        assert!(!config.package.require_license_acceptance);
        assert!(config.app.as_ref().unwrap().icon.is_none());
        let nupkg = config.nupkg.as_ref().unwrap();
        assert_eq!(
            nupkg.license_url.as_deref(),
            Some("https://github.com/hurricanehrndz/embala/blob/main/LICENSE")
        );
        assert_eq!(
            nupkg.icon_url.as_deref(),
            Some("https://github.com/hurricanehrndz/embala/raw/main/fixtures/hello/icon.png")
        );
        let msi = config.msi.unwrap();
        assert_eq!(msi.arch, MsiArch::X86_64);
        // Disabled, so installing the (non-service) fixture exe never tries
        // to start it.
        let service = msi.service.unwrap();
        assert_eq!(service.name, "embala-hello");
        assert_eq!(service.start, ServiceStart::Disabled);
        assert!(msi.add_to_path);
        assert_eq!(
            config.pkg.unwrap().scripts.as_deref(),
            Some(Path::new("scripts"))
        );
        let setup = config.setup.unwrap();
        assert_eq!(setup.arch, SetupArch::X86_64);
        // install-mode defaults to per-user when omitted (spec R18).
        assert_eq!(setup.install_mode, InstallMode::PerUser);
        // The fixture drives the declarative (lowered) path, not the raw-script
        // escape hatch: main-executable + license + a component, no `script`.
        assert_eq!(setup.main_executable.as_deref(), Some("hello.exe"));
        assert_eq!(setup.license.as_deref(), Some(Path::new("license.txt")));
        assert!(setup.script.is_none());
        assert_eq!(setup.components.len(), 1);
        assert_eq!(setup.components[0].id, "docs");
        assert!(setup.components[0].default);
        assert_eq!(setup.components[0].files[0].dest, "readme.txt");
    }

    /// The fixture with its Phase-4 metadata keys stripped, so the mutation
    /// tests below can splice their own variants without colliding
    /// (duplicate-key) with the metadata the fixture now carries end-to-end.
    fn fixture_toml_without_metadata() -> String {
        const STRIPPED: &[&str] = &[
            "copyright =",
            "tags =",
            "icon =",
            "project-source-url =",
            "package-source-url =",
            "release-notes =",
            "icon-url =",
            "license-url =",
        ];
        fixture_toml()
            .lines()
            .filter(|line| {
                let key = line.trim_start();
                !STRIPPED.iter().any(|prefix| key.starts_with(prefix))
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Splice extra keys into the fixture's `[package]` table (after
    /// `license`) and its `[nupkg]` table (after `style`).
    fn with_metadata(package_keys: &str, nupkg_keys: &str) -> String {
        fixture_toml_without_metadata()
            .replace(
                "license = \"MIT\"",
                &format!("license = \"MIT\"\n{package_keys}"),
            )
            .replace(
                "style = \"embedded\"",
                &format!("style = \"embedded\"\n{nupkg_keys}"),
            )
    }

    #[test]
    fn new_metadata_keys_parse() {
        let config = parse(&with_metadata(
            "copyright = \"© 2026 Carlos Hernandez\"\n\
             tags = [\"cli\", \"demo\"]\n\
             icon = \"icon.png\"\n\
             require-license-acceptance = true",
            "project-source-url = \"https://github.com/hurricanehrndz/embala\"\n\
             package-source-url = \"https://github.com/hurricanehrndz/embala-packages\"\n\
             release-notes = \"First release.\"\n\
             icon-url = \"https://example.com/icon.png\"\n\
             license-url = \"https://example.com/LICENSE\"",
        ))
        .expect("new metadata keys must parse");
        let p = &config.package;
        assert_eq!(p.copyright.as_deref(), Some("© 2026 Carlos Hernandez"));
        assert_eq!(
            p.tags.as_deref(),
            Some(&["cli".to_string(), "demo".to_string()][..])
        );
        assert_eq!(p.icon.as_deref(), Some(Path::new("icon.png")));
        assert!(p.require_license_acceptance);
        let n = config.nupkg.unwrap();
        assert_eq!(
            n.project_source_url.as_deref(),
            Some("https://github.com/hurricanehrndz/embala")
        );
        assert_eq!(
            n.package_source_url.as_deref(),
            Some("https://github.com/hurricanehrndz/embala-packages")
        );
        assert_eq!(n.release_notes.as_deref(), Some("First release."));
        assert_eq!(n.icon_url.as_deref(), Some("https://example.com/icon.png"));
        assert_eq!(
            n.license_url.as_deref(),
            Some("https://example.com/LICENSE")
        );
    }

    #[test]
    fn require_license_acceptance_needs_a_license_url() {
        let err = parse(&with_metadata("require-license-acceptance = true", ""))
            .unwrap_err()
            .to_string();
        assert!(err.contains("requires nupkg.license-url"), "{err}");
        parse(&with_metadata(
            "require-license-acceptance = true",
            "license-url = \"https://example.com/LICENSE\"",
        ))
        .expect("license-url satisfies the coupling rule");
    }

    #[test]
    fn whitespace_in_a_tag_is_rejected() {
        let err = parse(&with_metadata("tags = [\"cli tool\"]", ""))
            .unwrap_err()
            .to_string();
        assert!(err.contains("no whitespace"), "{err}");
    }

    #[test]
    fn non_numeric_version_is_rejected() {
        let text = fixture_toml().replace("version = \"0.1.0\"", "version = \"0.1.0-beta\"");
        let err = parse(&text).unwrap_err().to_string();
        assert!(err.contains("numeric x.y.z"), "unexpected error: {err}");
    }

    #[test]
    fn build_number_is_accepted_up_to_sixteen_bits() {
        // Why: CI stamps a build number as the fourth component; MSI and
        // VERSIONINFO hold it in 16 bits, so anything larger would be truncated.
        let with =
            |v: &str| fixture_toml().replace("version = \"0.1.0\"", &format!("version = \"{v}\""));
        assert_eq!(
            parse(&with("0.1.0.65535")).unwrap().package.version,
            "0.1.0.65535"
        );
        for bad in ["0.1.0.65536", "0.1.0.", "0.1.0.1.2"] {
            let err = parse(&with(bad)).unwrap_err().to_string();
            assert!(err.contains("x.y.z.build"), "{bad}: {err}");
        }
    }

    #[test]
    fn unknown_key_is_rejected() {
        let text = format!("{}\n[msi2]\narch = \"x86_64\"\n", fixture_toml());
        assert!(parse(&text).is_err());
    }

    #[test]
    fn thirty_two_bit_arch_is_rejected() {
        let text = fixture_toml().replace("arch = \"x86_64\"", "arch = \"x86\"");
        assert!(parse(&text).is_err());
    }

    #[test]
    fn unknown_service_start_is_rejected() {
        // Why: the start type maps onto a fixed SCM enum; a typo must not
        // silently become some default.
        let text = fixture_toml().replace("start = \"disabled\"", "start = \"boot\"");
        assert!(parse(&text).is_err());
        let text = fixture_toml().replace("start = \"disabled\"", "start = \"auto\"");
        let service = parse(&text).unwrap().msi.unwrap().service.unwrap();
        assert_eq!(service.start, ServiceStart::Auto);
    }

    #[test]
    fn download_style_requires_url_and_checksum() {
        let text = fixture_toml().replace("style = \"embedded\"", "style = \"download\"");
        let err = parse(&text).unwrap_err().to_string();
        assert!(
            err.contains("requires both url and checksum"),
            "unexpected error: {err}"
        );
    }

    /// A `[setup]` block with the full R18 surface for the validation tests.
    const SETUP_FULL: &str = r#"
[setup]
arch = "x86_64"
main-executable = "hello.exe"
install-mode = "user-choice"
files = [{ src = "dist/hello.exe", dest = "hello.exe" }]
components = [{ id = "core", label = "Core", default = true, files = [{ src = "dist/hello.exe", dest = "extra.exe" }] }]
shortcuts = [{ name = "Hello", target = "hello.exe", location = "desktop" }]
"#;

    fn with_setup(block: &str) -> String {
        // Drop the fixture's own [setup] section, then append the test block.
        let base = fixture_toml();
        let cut = base.find("\n[setup]").unwrap_or(base.len());
        format!("{}{}", &base[..cut], block)
    }

    #[test]
    fn full_setup_section_parses() {
        let config = parse(&with_setup(SETUP_FULL)).expect("full setup section must be valid");
        let setup = config.setup.unwrap();
        assert_eq!(setup.install_mode, InstallMode::UserChoice);
        assert_eq!(setup.components.len(), 1);
        assert_eq!(setup.shortcuts[0].location, ShortcutLocation::Desktop);
    }

    #[test]
    fn unknown_setup_arch_is_rejected() {
        let text = with_setup(SETUP_FULL).replace("arch = \"x86_64\"", "arch = \"x86\"");
        assert!(parse(&text).is_err());
    }

    #[test]
    fn main_executable_not_in_dests_is_rejected() {
        let text = with_setup(SETUP_FULL).replace(
            "main-executable = \"hello.exe\"",
            "main-executable = \"nope.exe\"",
        );
        let err = parse(&text).unwrap_err().to_string();
        assert!(err.contains("not among the installed file dests"), "{err}");
    }

    #[test]
    fn duplicate_component_ids_are_rejected() {
        let block = r#"
[setup]
arch = "x86_64"
files = [{ src = "dist/hello.exe", dest = "hello.exe" }]
components = [
  { id = "core", label = "A" },
  { id = "core", label = "B" },
]
"#;
        let err = parse(&with_setup(block)).unwrap_err().to_string();
        assert!(err.contains("duplicate component id"), "{err}");
    }

    #[test]
    fn uninstall_options_parse() {
        let block = r#"
[setup]
arch = "x86_64"
main-executable = "hello.exe"
files = [{ src = "dist/hello.exe", dest = "hello.exe" }]
uninstall-options = [
  { id = "purge-data", label = "Delete all data", default = false },
  { id = "keep-logs", label = "Keep logs" },
]
"#;
        let config = parse(&with_setup(block)).expect("uninstall-options must parse");
        let setup = config.setup.unwrap();
        assert_eq!(setup.uninstall_options.len(), 2);
        assert_eq!(setup.uninstall_options[0].id, "purge-data");
        assert!(!setup.uninstall_options[0].default);
        assert_eq!(setup.uninstall_options[1].label, "Keep logs");
    }

    #[test]
    fn duplicate_uninstall_option_ids_are_rejected() {
        let block = r#"
[setup]
arch = "x86_64"
files = [{ src = "dist/hello.exe", dest = "hello.exe" }]
uninstall-options = [
  { id = "purge-data", label = "A" },
  { id = "purge-data", label = "B" },
]
"#;
        let err = parse(&with_setup(block)).unwrap_err().to_string();
        assert!(err.contains("duplicate uninstall-option id"), "{err}");
    }

    #[test]
    fn empty_uninstall_option_id_or_label_is_rejected() {
        let empty_id = r#"
[setup]
arch = "x86_64"
files = [{ src = "dist/hello.exe", dest = "hello.exe" }]
uninstall-options = [{ id = "", label = "A" }]
"#;
        assert!(
            parse(&with_setup(empty_id))
                .unwrap_err()
                .to_string()
                .contains("id must be non-empty")
        );
        let empty_label = r#"
[setup]
arch = "x86_64"
files = [{ src = "dist/hello.exe", dest = "hello.exe" }]
uninstall-options = [{ id = "purge-data", label = "" }]
"#;
        assert!(
            parse(&with_setup(empty_label))
                .unwrap_err()
                .to_string()
                .contains("label must be non-empty")
        );
    }

    #[test]
    fn banner_without_bm_magic_is_rejected() {
        // Why: the banner is patched into the stub as a raw bitmap resource, so a
        // non-BMP would ship a broken wizard; reject it at validation (spec R7).
        let dir = std::env::temp_dir().join("embala-banner-magic-test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("dist")).unwrap();
        std::fs::write(dir.join("dist/hello.exe"), b"MZ").unwrap();
        std::fs::write(dir.join("bad.bmp"), b"NOTBMP").unwrap();
        std::fs::write(dir.join("good.bmp"), b"BM and pixels").unwrap();

        let block = r#"
[setup]
arch = "x86_64"
banner = "bad.bmp"
files = [{ src = "dist/hello.exe", dest = "hello.exe" }]
"#;
        let config: Config = toml::from_str(&with_setup(block)).unwrap();
        let err = validate_setup_paths(config.setup.as_ref().unwrap(), &dir)
            .unwrap_err()
            .to_string();
        assert!(err.contains("must be a BMP"), "{err}");

        let good = with_setup(block).replace("bad.bmp", "good.bmp");
        let config: Config = toml::from_str(&good).unwrap();
        validate_setup_paths(config.setup.as_ref().unwrap(), &dir).expect("BM magic accepted");
    }

    #[test]
    fn script_with_sugar_is_rejected() {
        let block = r#"
[setup]
arch = "x86_64"
script = "install.lua"
files = [{ src = "dist/hello.exe", dest = "hello.exe" }]
shortcuts = [{ name = "Hello", target = "hello.exe" }]
"#;
        let err = parse(&with_setup(block)).unwrap_err().to_string();
        assert!(err.contains("cannot be combined with"), "{err}");
    }

    /// The fixture with its `[pkg]` files line swapped for `files`, plus
    /// any extra `[pkg]` keys.
    fn with_pkg(files: &str, extra: &str) -> String {
        fixture_toml().replace(
            "files = [{ src = \"hello.sh\", dest = \"bin/embala-hello\" }]",
            &format!("files = {files}\n{extra}"),
        )
    }

    #[test]
    fn pkg_modes_and_directories_parse() {
        let text = with_pkg(
            r#"[{ src = "hello.sh", dest = "etc/credentials", mode = 0o600 }, { src = "hello.sh", dest = "bin/embala-hello" }]"#,
            r#"directories = [{ dest = "keys", mode = 0o700 }, { dest = "empty" }]"#,
        );
        let pkg = parse(&text).expect("pkg modes must parse").pkg.unwrap();
        assert_eq!(pkg.files[0].mode, Some(0o600));
        assert_eq!(
            pkg.files[1].mode, None,
            "absent mode keeps the exec-bit rule"
        );
        assert_eq!(pkg.directories[0].dest, "keys");
        assert_eq!(pkg.directories[0].mode, Some(0o700));
        assert_eq!(pkg.directories[1].mode, None);
    }

    #[test]
    fn pkg_mode_beyond_permission_bits_is_rejected() {
        // Why: setuid/setgid/sticky would grant privilege on install; they are
        // not supported, so they must fail loudly rather than be masked.
        for mode in ["0o4755", "0o2755", "0o1777"] {
            let file = with_pkg(
                &format!(r#"[{{ src = "hello.sh", dest = "bin/embala-hello", mode = {mode} }}]"#),
                "",
            );
            let err = format!("{:#}", parse(&file).unwrap_err());
            assert!(err.contains("permission bits only"), "{mode}: {err}");
            let dir = with_pkg(
                r#"[{ src = "hello.sh", dest = "bin/embala-hello" }]"#,
                &format!(r#"directories = [{{ dest = "keys", mode = {mode} }}]"#),
            );
            assert!(parse(&dir).is_err(), "directory {mode}");
        }
    }

    #[test]
    fn mode_outside_pkg_fails_to_parse() {
        // Why: only .pkg can honor a mode; elsewhere it must not be silently
        // dropped.
        let msi = fixture_toml().replace(
            "files = [{ src = \"dist/hello.exe\", dest = \"hello.exe\" }]\n# Registers",
            "files = [{ src = \"dist/hello.exe\", dest = \"hello.exe\", mode = 0o600 }]\n# Registers",
        );
        assert_ne!(msi, fixture_toml(), "replacement must hit [msi] files");
        let err = format!("{:#}", parse(&msi).unwrap_err());
        assert!(err.contains("unknown field `mode`"), "{err}");
    }

    #[test]
    fn pkg_directory_conflicts_are_rejected() {
        let files = r#"[{ src = "hello.sh", dest = "bin/embala-hello" }]"#;
        for (directories, needle) in [
            (
                r#"[{ dest = "keys" }, { dest = "keys" }]"#,
                "share the dest",
            ),
            (r#"[{ dest = "bin/embala-hello" }]"#, "share the dest"),
            (
                r#"[{ dest = "bin/embala-hello/keys" }]"#,
                "both a file and a directory",
            ),
            (r#"[{ dest = "../keys" }]"#, "relative"),
        ] {
            let text = with_pkg(files, &format!("directories = {directories}"));
            let err = format!("{:#}", parse(&text).unwrap_err());
            assert!(err.contains(needle), "{directories}: {err}");
        }
    }

    /// Fresh per-test dir holding `dist/hello.exe`, the only payload present.
    fn optional_dir(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("embala-optional-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("dist")).unwrap();
        std::fs::write(dir.join("dist/hello.exe"), b"MZ").unwrap();
        dir
    }

    const ABSENT: &str = r#"{ src = "absent.exe", dest = "agent.exe", optional = true }"#;

    #[test]
    fn optional_parses_on_every_file_entry_and_defaults_off() {
        let text = fixture_toml()
            .replace(
                r#"files = [{ src = "hello.sh", dest = "bin/embala-hello" }]"#,
                r#"files = [{ src = "hello.sh", dest = "bin/embala-hello", mode = 0o600, optional = true }]"#,
            )
            .replace(
                r#"{ src = "readme.txt", dest = "readme.txt" }"#,
                r#"{ src = "readme.txt", dest = "readme.txt", optional = true }"#,
            );
        let config = parse(&text).expect("optional must parse");
        let pkg = &config.pkg.as_ref().unwrap().files[0];
        assert!(pkg.optional);
        assert_eq!(pkg.mode, Some(0o600));
        let setup = config.setup.as_ref().unwrap();
        assert!(setup.components[0].files[0].optional);
        assert!(!setup.files[0].optional, "optional defaults to false");
    }

    #[test]
    fn optional_with_download_style_is_rejected() {
        // Why: download style never reads src, so optional could only ever
        // change the build by removing the one entry the URL needs.
        let text = fixture_toml()
            .replace(
                "style = \"embedded\"",
                "style = \"download\"\nurl = \"https://e.x/a.exe\"\nchecksum = \"00\"",
            )
            .replace(
                r#"files = [{ src = "dist/hello.exe", dest = "hello.exe" }]

[setup]"#,
                r#"files = [{ src = "dist/hello.exe", dest = "hello.exe", optional = true }]

[setup]"#,
            );
        let err = parse(&text).unwrap_err().to_string();
        assert!(err.contains("no effect with style \"download\""), "{err}");
    }

    #[test]
    fn absent_optional_files_are_dropped_and_others_kept() {
        let dir = optional_dir("drop");
        let mut setup: SetupSection = toml::from_str(&format!(
            r#"arch = "x86_64"
main-executable = "hello.exe"
files = [{{ src = "dist/hello.exe", dest = "hello.exe", optional = true }}, {ABSENT}]
components = [{{ id = "extra", label = "Extra", files = [{ABSENT}] }}]"#
        ))
        .unwrap();
        setup.drop_absent_optional(&dir).unwrap();
        assert_eq!(setup.installed_dests(), ["hello.exe"]);
        assert!(setup.components[0].files.is_empty());
    }

    #[test]
    fn references_to_a_dropped_optional_file_are_rejected() {
        // Why: a shortcut, ARP icon, MSI entry point or service pointing at a
        // file the package does not ship is a broken install, not a skip.
        let dir = optional_dir("refs");
        let hello = r#"{ src = "dist/hello.exe", dest = "hello.exe" }"#;
        for (field, setup) in [
            (
                "main-executable",
                format!(
                    "arch = \"x86_64\"\nmain-executable = \"agent.exe\"\nfiles = [{hello}, {ABSENT}]"
                ),
            ),
            (
                "shortcut \"Agent\" target",
                format!(
                    "arch = \"x86_64\"\nfiles = [{hello}]\n\
                     components = [{{ id = \"a\", label = \"A\", files = [{ABSENT}] }}]\n\
                     shortcuts = [{{ name = \"Agent\", target = \"agent.exe\" }}]"
                ),
            ),
        ] {
            let mut setup: SetupSection = toml::from_str(&setup).unwrap();
            let err = setup.drop_absent_optional(&dir).unwrap_err().to_string();
            assert!(
                err.contains(&format!("setup: {field} \"agent.exe\"")),
                "{err}"
            );
            assert!(err.contains("optional file that was absent"), "{err}");
        }
        for (field, msi) in [
            ("main-executable", "main-executable = \"agent.exe\""),
            (
                "service executable",
                "main-executable = \"hello.exe\"\n\
                 service = { name = \"a\", start = \"auto\", executable = \"agent.exe\" }",
            ),
        ] {
            let mut msi: MsiSection = toml::from_str(&format!(
                "arch = \"x86_64\"\n{msi}\nfiles = [{hello}, {ABSENT}]"
            ))
            .unwrap();
            let err = msi.drop_absent_optional(&dir).unwrap_err().to_string();
            assert!(
                err.contains(&format!("msi: {field} \"agent.exe\"")),
                "{err}"
            );
        }
    }

    #[test]
    fn a_reference_another_entry_still_provides_is_kept() {
        let dir = optional_dir("shared-dest");
        let mut msi: MsiSection = toml::from_str(
            r#"arch = "x86_64"
main-executable = "hello.exe"
files = [{ src = "absent.exe", dest = "hello.exe", optional = true }, { src = "dist/hello.exe", dest = "hello.exe" }]"#,
        )
        .unwrap();
        msi.drop_absent_optional(&dir).unwrap();
        assert_eq!(msi.files.len(), 1);
    }

    #[test]
    fn only_not_found_counts_as_absent() {
        let dir = optional_dir("probe");
        assert!(optional_src_absent(&dir.join("missing")).unwrap());
        assert!(optional_src_absent(&dir.join("no/such/dir/file")).unwrap());
        assert!(!optional_src_absent(&dir.join("dist/hello.exe")).unwrap());
        let err = optional_src_absent(&dir.join("dist")).unwrap_err();
        assert!(err.to_string().contains("not a regular file"), "{err}");
    }

    #[cfg(unix)]
    #[test]
    fn dangling_symlink_is_an_error_not_a_skip() {
        // Why: exists()/try_exists() report a dangling link as absent; a
        // broken staging step must fail the build, not quietly drop a file.
        let dir = optional_dir("dangling");
        std::os::unix::fs::symlink(dir.join("gone"), dir.join("link")).unwrap();
        let err = optional_src_absent(&dir.join("link")).unwrap_err();
        assert!(err.to_string().contains("dangling symlink"), "{err}");
        let err = optional_src_absent(&dir.join("link/credentials")).unwrap_err();
        assert!(err.to_string().contains("dangling symlink"), "{err}");
        // A trailing separator makes lstat follow the link and report
        // NotFound, which must not read as an absent file.
        for spelling in ["link/", "link/."] {
            let err = optional_src_absent(&dir.join(spelling)).unwrap_err();
            assert!(err.to_string().contains("dangling symlink"), "{err}");
        }
        std::os::unix::fs::symlink(dir.join("dist/hello.exe"), dir.join("good")).unwrap();
        assert!(!optional_src_absent(&dir.join("good")).unwrap());
    }

    #[test]
    fn sign_section_parses() {
        let text = format!(
            "{}\n[sign.windows]\ncommand = \"osslsigncode sign -in $f -out $f\"\n\
             signed-stub = \"signed-stub.exe\"\n[sign.macos]\ncommand = \"rcodesign sign $f\"\n",
            fixture_toml()
        );
        let config = parse(&text).expect("sign section must parse");
        let sign = config.sign.unwrap();
        assert_eq!(
            sign.windows.as_ref().unwrap().signed_stub.as_deref(),
            Some(Path::new("signed-stub.exe"))
        );
        assert_eq!(sign.macos.unwrap().command, "rcodesign sign $f");
    }

    #[test]
    fn sign_command_without_placeholder_is_rejected() {
        let text = format!(
            "{}\n[sign.windows]\ncommand = \"osslsigncode sign cert.pfx\"\n",
            fixture_toml()
        );
        let err = parse(&text).unwrap_err().to_string();
        assert!(err.contains("must be non-empty and contain $f"), "{err}");
    }

    /// `trim_trailing` as a string, compared exactly: `Path`'s `==` ignores
    /// trailing separators, which is what these tests check.
    fn trimmed(path: &str) -> &str {
        trim_trailing(Path::new(path)).to_str().unwrap()
    }

    #[test]
    fn trim_trailing_strips_only_trailing_separators_and_dots() {
        assert_eq!(trimmed("dir/link/"), "dir/link");
        assert_eq!(trimmed("dir/link/."), "dir/link");
        assert_eq!(trimmed("dir/link//././/"), "dir/link");
        assert_eq!(trimmed("dir/./link"), "dir/./link");
        assert_eq!(trimmed("dir/link"), "dir/link");
        // A `:` mid-path is kept, not re-parsed as a drive.
        assert_eq!(trimmed("stage/c:credentials/."), "stage/c:credentials");
        assert_eq!(trimmed("dir/.."), "dir/..");
        assert_eq!(trimmed("dir/link."), "dir/link.");
        assert_eq!(trimmed("/"), "/");
        assert_eq!(trimmed("/."), "/");
        assert_eq!(trimmed("."), ".");
        assert_eq!(trimmed("./"), ".");
    }

    #[cfg(not(windows))]
    #[test]
    fn trim_trailing_keeps_backslash_on_unix() {
        assert_eq!(trimmed("dir/link\\"), "dir/link\\");
    }

    #[cfg(windows)]
    #[test]
    fn trim_trailing_windows_paths() {
        // Backslash, alone or mixed with `/`.
        assert_eq!(trimmed(r"stage\link\"), r"stage\link");
        assert_eq!(trimmed(r"stage\link\."), r"stage\link");
        assert_eq!(trimmed(r"stage\link/.\"), r"stage\link");
        // Drive-absolute: the root stays, a `:` component is kept.
        assert_eq!(
            trimmed(r"C:\stage\c:credentials\"),
            r"C:\stage\c:credentials"
        );
        assert_eq!(
            trimmed(r"C:\stage\c:credentials\."),
            r"C:\stage\c:credentials"
        );
        assert_eq!(trimmed(r"C:\"), r"C:\");
        assert_eq!(trimmed(r"C:\."), r"C:\");
        assert_eq!(trimmed("C:/"), "C:/");
        // Drive-relative: never trimmed into the prefix.
        assert_eq!(trimmed(r"C:link\"), r"C:link");
        assert_eq!(trimmed(r"C:link\."), r"C:link");
        assert_eq!(trimmed("C:"), "C:");
        assert_eq!(trimmed("C:."), "C:.");
        // UNC: the share root stays.
        assert_eq!(
            trimmed(r"\\server\share\dir\link\."),
            r"\\server\share\dir\link"
        );
        assert_eq!(trimmed(r"\\server\share\"), r"\\server\share\");
        // Verbatim: only `\` separates and `.` is literal.
        assert_eq!(
            trimmed(r"\\?\C:\stage\c:credentials\"),
            r"\\?\C:\stage\c:credentials"
        );
        assert_eq!(trimmed(r"\\?\C:\"), r"\\?\C:\");
        assert_eq!(trimmed(r"\\?\C:\dir\link/"), r"\\?\C:\dir\link/");
        assert_eq!(trimmed(r"\\?\C:\dir\."), r"\\?\C:\dir\.");
        assert_eq!(
            trimmed(r"\\?\UNC\server\share\link\"),
            r"\\?\UNC\server\share\link"
        );
    }
}