bevy-dlc 1.18.26

DLC (downloadable content) management for Bevy games
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
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
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
use bevy::winit::WinitPlugin;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// Windows exposes a hidden-file flag that we skip; on Unix/macOS the
// conventional “hidden” file is simply one whose name begins with a dot.
// Guard the import so the code still builds on non-Windows platforms.
#[cfg(target_os = "windows")]
use winapi::um::fileapi::GetFileAttributesA;
#[cfg(target_os = "windows")]
use winapi::um::winnt::FILE_ATTRIBUTE_HIDDEN;

#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
use libc::{UF_HIDDEN, stat};
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;

/// Checks if the specified file is hidden.
fn is_hidden(path: &PathBuf) -> bool {
    let file_name = path.file_name().and_then(|s| s.to_str());
    if file_name.map_or(false, |s| s.starts_with('.')) {
        return true;
    }

    let path_str = match path.to_str() {
        Some(s) => s,
        None => return true, // treat non-UTF-8 paths as hidden to avoid packing them
    };
    let path_c = match std::ffi::CString::new(path_str) {
        Ok(c) => c,
        Err(_) => return true, // treat paths with null bytes as hidden to avoid packing them
    };

    #[cfg(target_os = "windows")]
    {
        let attributes = unsafe { GetFileAttributesA(path_c.as_ptr()) };
        if attributes == u32::MAX {
            return true; // treat inaccessible files as hidden to avoid packing them
        }
        return (attributes & FILE_ATTRIBUTE_HIDDEN) != 0;
    }

    #[cfg(target_os = "macos")]
    {
        let mut file_stat: stat = unsafe { std::mem::zeroed() };
        let ret = unsafe { libc::stat(path_c.as_ptr(), &mut file_stat) };
        if ret != 0 {
            return true; // treat inaccessible files as hidden to avoid packing them
        }

        return (file_stat.st_flags & UF_HIDDEN as u32) != 0;
    }

    #[cfg(target_os = "linux")]
    {
        // just check if the file name starts with a dot which is done above
    }

    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
    {
        return false; // treat unsupported OS as not hidden
    }
}

use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bevy::prelude::*;
use bevy::{asset::AssetServer, log::LogPlugin};

use clap::{Parser, Subcommand};

use bevy_dlc::{
    DLC_PACK_VERSION_LATEST, EncryptionKey, PackItem, extract_dlc_ids_from_license,
    extract_encrypt_key_from_license, extract_product_from_license,
    pack_encrypted_pack_with_metadata, parse_encrypted_pack, parse_encrypted_pack_info,
    prelude::*,
};
use owo_colors::{AnsiColors, OwoColorize};
use secure_gate::RevealSecret;

mod repl;
mod watch;

#[derive(Parser)]
#[command(
    author,
    about = "bevy-dlc helper: pack and unpack .dlcpack containers",
    long_about = "Utility for creating, inspecting and extracting bevy-dlc encrypted containers."
)]
struct Cli {
    /// don't perform file changes, just show what would happen
    #[arg(long, global = true)]
    dry_run: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    #[command(
        about = "Print version information",
        long_about = "Display version information for bevy-dlc and the encrypted pack format. If a .dlcpack file is supplied, also display the embedded pack version.",
        alias = "v"
    )]
    Version {
        /// Optional path to a .dlcpack file; when supplied the command will
        /// also report the encrypted-pack version embedded in the file.
        #[arg(value_name = "DLC", help = "Optional .dlcpack path")]
        dlc: Option<PathBuf>,
    },
    #[command(
        about = "Pack assets into a .dlcpack bundle",
        long_about = "Encrypts the provided input files into a single bevy-dlc .dlcpack bundle. Use --list to preview container metadata.",
        alias = "p"
    )]
    Pack {
        /// Product identifier to embed in the private key.
        #[arg(value_name = "PRODUCT")]
        product: String,
        /// DLC identifier to embed in the container/private key
        #[arg(
            help = "Identifier embedded into the container and private key (e.g. expansion_1)",
            value_name = "DLC_ID"
        )]
        dlc_id: String,
        /// Supply an explicit list of files to include (overrides directory recursion)
        #[arg(value_name = "FILES...", last = true)]
        files: Vec<PathBuf>,
        /// print container metadata instead of writing
        #[arg(
            short,
            long,
            help = "Show the metadata the container would contain and exit; no file or private key will be produced."
        )]
        list: bool,
        /// output path (defaults to <dlc_id>.dlcpack). If the supplied path has no extension it is treated as a directory and the generated file will be written to `<OUT>/<dlc_id>.dlcpack`.
        #[arg(
            short,
            long,
            help = "Destination path for the generated .dlcpack (default: <dlc_id>.dlcpack). If the path has no extension it will be treated as a directory.",
            value_name = "OUT"
        )]
        out: Option<PathBuf>,

        /// Manual type overrides (ext=TypePath pairs)
        #[arg(
            long = "types",
            help = "Override asset types: ext=TypePath (e.g., json=my_game::LevelData)",
            long_help = "Manually specify TypePath for extensions that Bevy doesn't recognize.\nFormat: --types json=my_game::LevelData --types csv=my_game::CsvData\nThese take precedence over auto-detected types from Bevy's loaders.",
            value_name = "EXT=TYPE",
            num_args = 1..
        )]
        types: Option<Vec<String>>,

        /// Pack-level metadata entries in the form key=value. Values are parsed as JSON when possible and fall back to strings.
        #[arg(
            long = "metadata",
            help = "Pack metadata entry as key=value. Values are parsed as JSON when possible.",
            value_name = "KEY=VALUE",
            num_args = 1..
        )]
        metadata: Option<Vec<String>>,

        /// Optional public key to use for verifying/printing an externally-supplied license
        #[arg(
            long = "pubkey",
            help = "Optional public key (base64url or file) used to verify a supplied signed license or to print alongside a supplied license",
            value_name = "PUBKEY"
        )]
        pubkey: Option<String>,

        /// Optional pre-generated SignedLicense (compact token). When provided with `--pubkey` the license will be verified.
        #[arg(
            short,
            long = "signed-license",
            help = "Optional SignedLicense token to use instead of generating a new one",
            value_name = "SIGNED_LICENSE"
        )]
        signed_license: Option<String>,
    },

    #[command(
        about = "List contents of a .dlcpack (prints entries/metadata)",
        long_about = "Display detailed metadata for the entries inside a .dlcpack. If given a directory, lists all .dlcpack files inside.",
        alias = "ls"
    )]
    List {
        /// path to a .dlcpack file (or directory)
        #[arg(
            value_name = "DLC",
            help = "Path to a .dlcpack file, or a directory containing .dlcpack files (recursive)"
        )]
        dlc: PathBuf,
    },

    /// Check a `.dlcpack` against a signed license / public key.
    #[command(
        about = "Validate a .dlcpack file against a signed license and public key",
        long_about = "Checks that the .dlcpack's embedded DLC id is covered by the signed license, and that the signature is valid for the given public key. If the license does not include the DLC id but is otherwise valid, the command will attempt to extend the license with the missing DLC id (if a private key is available) and print the extended token.",
        alias = "validate",
        alias = "c"
    )]
    Check {
        /// path to a .dlcpack file
        #[arg(value_name = "DLC")]
        dlc: PathBuf,
        /// Product name (used to read `<product>.slicense` / `<product>.pubkey` if not supplied)
        #[arg(short, long, value_name = "PRODUCT")]
        product: Option<String>,
        /// Optional SignedLicense token to validate (compact form)
        #[arg(short, long = "signed-license", value_name = "SIGNED_LICENSE")]
        signed_license: Option<String>,
        /// Optional public key (base64url or file) used to verify the signed license
        #[arg(long = "pubkey", value_name = "PUBKEY")]
        pubkey: Option<String>,
    },

    #[command(
        about = "Generate a product .slicense and .pubkey.",
        long_about = "Create a signed-license token and write <product>.slicense and <product>.pubkey; these files are used as defaults by other commands when present.",
        alias = "g"
    )]
    Generate {
        /// Product name to bind the license to (also used to name the output files)
        #[arg(value_name = "PRODUCT")]
        product: String,
        /// DLC ids to include in the signed license
        #[arg(value_name = "DLCS", num_args = 1..)]
        dlcs: Vec<String>,
        /// Output directory for the generated .slicense and .pubkey files (defaults to current directory)
        #[arg(short, long, value_name = "OUT_DIR")]
        out_dir: Option<PathBuf>,
        /// Overwrite existing files if present
        #[arg(short, long)]
        force: bool,
    },

    #[command(
        about = "Generate a random 32-character AES-256 key",
        long_about = "Generate a cryptographically random 32-character key for use with include_signed_license_aes!. The key is printed as exactly 32 printable ASCII characters, matching the requirement of bevy_dlc_macro.",
        alias = "aes"
    )]
    AesKey,

    #[command(
        about = "Interactive REPL to edit an existing .dlcpack metadata (add/remove entries, merge another pack, etc.)",
        long_about = "Modify the manifest of an existing .dlcpack (change types, remove entries) without re-encrypting the content. If a key/license is provided, you can also add new files."
    )]
    Edit {
        /// path to a .dlcpack file
        #[arg(value_name = "DLC")]
        dlc: PathBuf,
        /// Optional SignedLicense token to unlock re-encryption (for 'add' command)
        #[arg(short, long = "signed-license", value_name = "SIGNED_LICENSE")]
        signed_license: Option<String>,
        /// Optional public key (base64url or file) used to verify the signed license
        #[arg(long = "pubkey", value_name = "PUBKEY")]
        pubkey: Option<String>,
        /// Optional product name (used to find .slicense/.pubkey defaults)
        #[arg(short, long, value_name = "PRODUCT")]
        product: Option<String>,
        /// Optional one-shot REPL command (e.g. `ls`); use `--` to separate from flags
        #[arg(value_name = "REPL_CMD", last = true)]
        command: Vec<String>,
    },
    #[command(
        about = "Find a .dlcpack file with specified DLC id in a directory",
        long_about = "Search for .dlcpack files in a directory (recursively) for a matching DLC id in their manifest. This is useful for locating files when you only have the DLC id and not the filename."
    )]
    Find {
        /// DLC id to search for in .dlcpack files
        #[arg(value_name = "DLC_ID")]
        dlc_id: String,
        /// Directory to search for .dlcpack files (recursive)
        #[arg(value_name = "DIR")]
        dir: PathBuf,
        /// Max depth for recursive search (default: 5)
        #[arg(short = 'd', long, default_value_t = 5)]
        max_depth: usize,
    },
    #[command(
        about = "Watch real source files and repack changed entries back into their .dlcpack files",
        long_about = "Scans the current directory recursively for .dlcpack files, resolves their archived entry paths against real files on disk, and watches those real files for changes. When a tracked source file changes, the matching entry is re-packed into the originating .dlcpack."
    )]
    Watch {
        /// Only watch the .dlcpack whose embedded DLC id matches this value.
        #[arg(long = "dlc-id", value_name = "DLC_ID")]
        dlc_id: Option<String>,
    },
}

pub(crate) fn parse_metadata_value(raw: &str) -> serde_json::Value {
    serde_json::from_str(raw).unwrap_or_else(|_| serde_json::Value::String(raw.to_string()))
}

pub(crate) fn parse_metadata_assignments(
    assignments: &[String],
) -> Result<bevy_dlc::PackMetadata, Box<dyn std::error::Error>> {
    let mut metadata = bevy_dlc::PackMetadata::new();
    for assignment in assignments {
        let (key, raw_value) = assignment.split_once('=').ok_or_else(|| {
            format!(
                "invalid metadata entry '{}'; expected key=value",
                assignment
            )
        })?;
        let key = key.trim();
        if key.is_empty() {
            return Err(format!(
                "invalid metadata entry '{}'; key cannot be empty",
                assignment
            )
            .into());
        }
        metadata.insert(key.to_string(), parse_metadata_value(raw_value.trim()));
    }
    Ok(metadata)
}

fn print_pack_metadata(metadata: &bevy_dlc::PackMetadata, metadata_locked: bool) {
    if metadata_locked {
        println!(
            "{} encrypted (DLC key required to inspect)",
            "metadata:".blue()
        );
        return;
    }

    if metadata.is_empty() {
        println!("{} none", "metadata:".blue());
        return;
    }

    println!("{}", "metadata:".blue());
    for (key, value) in metadata {
        let rendered =
            serde_json::to_string(value).unwrap_or_else(|_| "<unprintable metadata>".to_string());
        println!(" - {} = {}", key, rendered);
    }
}

/// Recursively collect files under `dir`. If `ext_filter` is Some(ext), only
/// files matching that extension are returned.
fn collect_files_recursive(
    dir: &std::path::Path,
    out: &mut Vec<std::path::PathBuf>,
    ext_filter: Option<&str>,
    max_depth: usize,
) -> std::io::Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        let name = entry.file_name();
        let name_str = name.to_string_lossy();

        if path.is_dir() {
            // Skip hidden directories and common build/dependency artifacts to avoid searching too much
            if name_str.starts_with('.') || name_str == "target" || name_str == "node_modules" {
                continue;
            }
            if max_depth > 0 {
                collect_files_recursive(&path, out, ext_filter, max_depth - 1)?;
            }
        } else if path.is_file() {
            if is_hidden(&path) {
                continue;
            }

            let file_ext = path
                .extension()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_ascii_lowercase();

            match ext_filter {
                Some(filter) => {
                    // Targeted search: return files matching the requested extension only.
                    if file_ext.eq_ignore_ascii_case(filter) {
                        out.push(path);
                    }
                }
                None => {
                    // Asset-collection mode: skip non-asset / binary artifacts so they
                    // are never accidentally packed.
                    const EXCLUDED_EXTENSIONS: &[&str] = &[
                        "dlcpack", "slicense", "pubkey", "exe", "dll", "so", "dylib", "pdb", "ilk",
                        "exp", "lib", "a", "o", "rlib",
                    ];
                    if !EXCLUDED_EXTENSIONS.contains(&file_ext.as_str()) {
                        out.push(path);
                    }
                }
            }
        }
    }
    Ok(())
}

/// Parse manual type overrides from CLI arguments.
///
/// Expects format: `ext=TypePath` (e.g., `json=my_game::LevelData`)
fn parse_type_overrides(overrides: &[String]) -> HashMap<String, String> {
    let mut map = HashMap::new();
    for entry in overrides {
        if let Some((ext, type_path)) = entry.split_once('=') {
            map.insert(ext.to_ascii_lowercase(), type_path.to_string());
        }
    }
    map
}

/// Print signed license and public-key information, and optionally write
/// `<product>.slicense` and `<product>.pubkey` when `write_files` is true and
/// `product` is provided.
///
/// - Prints the compact `SignedLicense` token (format: `payload_base64url.signature_base64url`).
/// - DOES NOT print private seeds or raw symmetric keys; treat the token as
///   sensitive and provision it securely.
fn print_signed_license_and_pubkey(
    signedlicense: &str,
    dlc_key: &DlcKey,
    write_files: bool,
    product: Option<&str>,
    out_dir: Option<&std::path::Path>,
) {
    let pubkey_b64 = URL_SAFE_NO_PAD.encode(dlc_key.get_public_key().0);
    if !write_files {
        println!("{}:\n{}", "SIGNED LICENSE".green().bold(), signedlicense);
        println!("{}: {}", "PUB KEY".blue().bold(), pubkey_b64);
    } else {
        if let Some(prod) = product {
            let dir = out_dir.unwrap_or_else(|| std::path::Path::new("."));
            if !dir.exists() {
                if let Err(e) = std::fs::create_dir_all(dir) {
                    print_error(&format!(
                        "failed to create output directory {}: {}",
                        dir.display(),
                        e
                    ));
                    return;
                }
            }
            let slicense_path = dir.join(format!("{}.slicense", prod));
            let pubkey_path = dir.join(format!("{}.pubkey", prod));
            if let Err(e) = std::fs::write(&slicense_path, signedlicense) {
                print_error(&format!(
                    "failed to write {}: {}",
                    slicense_path.display(),
                    e
                ));
            }
            if let Err(e) = std::fs::write(&pubkey_path, pubkey_b64) {
                print_error(&format!("failed to write {}: {}", pubkey_path.display(), e));
            }
        } else {
            print_warning("no product name supplied; skipping file write");
        }
    }
}

/// Resolve TypePath for file paths using Bevy's `AssetServer`.
///
/// This relies on runtime loader registrations; use `--types` to override
/// missing loaders.
async fn resolve_type_paths_from_bevy(
    app: &mut App,
    paths: &[PathBuf],
    overrides: &HashMap<String, String>,
) -> Result<HashMap<PathBuf, String>, Box<dyn std::error::Error>> {
    // collect unique extensions to query
    let mut extensions_to_query: Vec<String> = Vec::new();
    for path in paths {
        if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
            let ext_lower = ext.to_ascii_lowercase();
            if !overrides.contains_key(&ext_lower) && !extensions_to_query.contains(&ext_lower) {
                extensions_to_query.push(ext_lower);
            }
        }
    }

    // strict AssetServer-only resolution
    let mut ext_map: HashMap<String, String> = HashMap::new();
    {
        let world = app.world();
        let asset_server_ref = world
            .get_resource::<AssetServer>()
            .ok_or("AssetServer resource not found")?;
        let asset_server = asset_server_ref.clone();

        for ext in &extensions_to_query {
            // run one frame so plugins/systems can perform registrations
            app.update();

            match asset_server.get_asset_loader_with_extension(ext).await {
                Ok(loader) => {
                    let type_name = loader.asset_type_name();
                    ext_map.insert(ext.clone(), type_name.to_string());
                }
                Err(_) => {
                    return Err(format!(
                        "no AssetLoader registered for extension '{}'; either add the plugin that provides the loader or pass --types {}=TypePath",
                        ext, ext
                    ).into());
                }
            }
        }
    }

    // Build final path -> type_path map (manual overrides take precedence)
    let mut result = HashMap::new();
    for path in paths {
        if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
            let ext_lower = ext.to_ascii_lowercase();
            if let Some(tp) = overrides.get(&ext_lower) {
                result.insert(path.clone(), tp.clone());
            } else if let Some(tp) = ext_map.get(&ext_lower) {
                result.insert(path.clone(), tp.clone());
            }
        }
    }

    Ok(result)
}

fn print_pack_entries(version: usize, ents: &[(String, bevy_dlc::EncryptedAsset)]) {
    if version as u8 == DLC_PACK_VERSION_LATEST {
        for (p, enc) in ents.iter() {
            println!(
                " - {} (ext={}) type={}",
                p,
                enc.original_extension,
                enc.type_path.clone().unwrap_or("None".to_string())
            );
        }
    } else {
        println!(
            "Version {} is not supported anymore. Repack your DLC assets using the 'pack' command.",
            version
        );
    }
}

/// If `val` is a path to an existing file, return its trimmed contents;
/// otherwise return `val` unchanged. This lets `--pubkey` and `--signed-license`
/// accept either a raw token/base64url string or a file path.
fn resolve_file_or_value(val: String) -> String {
    let path = std::path::Path::new(&val);
    if path.is_file() {
        std::fs::read_to_string(path)
            .ok()
            .map(|s| s.trim().to_string())
            .unwrap_or(val)
    } else {
        val
    }
}

/// Helper: Resolve pubkey and signed license from CLI args or defaults files
fn resolve_pubkey_and_license(
    pubkey: Option<String>,
    signed_license: Option<String>,
    product: &str,
) -> (Option<String>, Option<String>) {
    resolve_pubkey_and_license_with_search_roots(
        pubkey,
        signed_license,
        product,
        &[PathBuf::from(".")],
    )
}

fn resolve_pubkey_and_license_with_search_roots(
    pubkey: Option<String>,
    signed_license: Option<String>,
    product: &str,
    search_roots: &[PathBuf],
) -> (Option<String>, Option<String>) {
    let pubkey = pubkey.map(resolve_file_or_value);
    let signed_license = signed_license.map(resolve_file_or_value);

    let resolved_pubkey = pubkey.or_else(|| find_product_file_in_search_roots(product, "pubkey", search_roots));
    let resolved_license =
        signed_license.or_else(|| find_product_file_in_search_roots(product, "slicense", search_roots));

    (resolved_pubkey, resolved_license)
}

/// Helper: Derive encryption key from signed license or generate new one
fn derive_encrypt_key(
    signed_license: Option<&str>,
) -> Result<EncryptionKey, Box<dyn std::error::Error>> {
    Ok(if let Some(lic_str) = signed_license {
        if let Some(enc_key) =
            extract_encrypt_key_from_license(&bevy_dlc::SignedLicense::from(lic_str.to_string()))
        {
            enc_key
        } else {
            EncryptionKey::new(rand::random())
        }
    } else {
        EncryptionKey::new(rand::random())
    })
}

/// Helper: Handle license verification/generation and output
fn handle_license_output(
    signed_license: Option<&str>,
    pubkey: Option<&str>,
    product: &str,
    dlc_id_str: &str,
    signer_key: Option<&DlcKey>,
    write_files: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(sup_license) = signed_license {
        if let Some(pubkey_str) = pubkey {
            let verifier = DlcKey::public(pubkey_str)
                .map_err(|e| format!("invalid provided pubkey: {:?}", e))?;
            if !verifier.verify_signed_license(&SignedLicense::from(sup_license.to_string())) {
                return Err("supplied signed-license verification failed".into());
            }
            let final_license = SignedLicense::from(sup_license.to_string());
            let verified_product = extract_product_from_license(&final_license).unwrap_or_default();
            if verified_product != product {
                return Err("supplied signed-license product does not match pack product".into());
            }

            // If the dlc_id is not in the license, try to extend it (requires private key).
            // If only a public key is available, print a warning and continue — the pack
            // is still created with the correct encryption key; the user should regenerate
            // the license with the DLC id included if they want it to unlock this pack.
            let mut final_license = SignedLicense::from(sup_license.to_string());
            if !extract_dlc_ids_from_license(&final_license)
                .iter()
                .any(|d| d == &dlc_id_str)
            {
                let extended = signer_key.and_then(|dlc_key| {
                    dlc_key
                        .extend_signed_license(
                            &final_license,
                            &[DlcId::from(dlc_id_str.to_string())],
                            Product::from(product.to_string()),
                        )
                        .ok()
                });
                match extended {
                    Some(ext) => {
                        println!("{}", "note: supplied license did not include requested DLC id, extending it now.".white().bold());
                        final_license = ext;
                    }
                    None => {
                        print_warning(&format!(
                            "license does not include DLC id '{}'; the pack was created but users need a license that covers this DLC id to unlock it. Re-run `generate` with this DLC id to update the license.",
                            dlc_id_str
                        ));
                    }
                }
            }

            final_license.with_secret(|s| {
                println!("{}:\n{}", "SIGNED LICENSE".green().bold(), s);
                println!("{}: {}", "PUB KEY".blue().bold(), pubkey_str);
            });
        } else {
            print_warning("supplied signed-license not verified (no --pubkey supplied)");

            // Check if we can extend with the new dlc_id
            let dlc_ids_in_existing =
                extract_dlc_ids_from_license(&SignedLicense::from(sup_license.to_string()));
            let final_license = if !dlc_ids_in_existing.iter().any(|d| d == dlc_id_str) {
                if let Some(dlc_key) = signer_key {
                    // Extend the supplied license with the new dlc_id
                    let extended = dlc_key.extend_signed_license(
                        &SignedLicense::from(sup_license.to_string()),
                        &[DlcId::from(dlc_id_str.to_string())],
                        Product::from(product.to_string()),
                    )?;
                    println!(
                        "{}",
                        "note: existing license did not include requested DLC id, extended with it"
                            .white()
                            .bold()
                    );
                    extended
                } else {
                    print_warning(&format!(
                        "existing license does not include DLC id '{}' (no private key available to extend)",
                        dlc_id_str
                    ));
                    SignedLicense::from(sup_license.to_string())
                }
            } else {
                SignedLicense::from(sup_license.to_string())
            };

            final_license.with_secret(|s| {
                println!("{}:\n{}", "SIGNED LICENSE:".green().bold(), s);
            });
        }
    } else {
        // Use the provided signer key (the key that signed the pack) when available
        if let Some(dlc_key) = signer_key {
            let signedlicense = dlc_key.create_signed_license(
                &[DlcId::from(dlc_id_str.to_string())],
                Product::from(product.to_string()),
            )?;
            signedlicense.with_secret(|s| {
                if write_files {
                    print_signed_license_and_pubkey(s.as_str(), dlc_key, false, Some(product), None)
                } else {
                    println!("{}:\n{}", "SIGNED LICENSE".green().bold(), s);
                }
            });
        } else {
            let dlc_key = DlcKey::generate_random();
            let signedlicense = dlc_key.create_signed_license(
                &[DlcId::from(dlc_id_str.to_string())],
                Product::from(product.to_string()),
            )?;
            signedlicense.with_secret(|s| {
                if write_files {
                    print_signed_license_and_pubkey(s.as_str(), &dlc_key, true, Some(product), None)
                } else {
                    println!("{}:\n{}", "SIGNED LICENSE".green().bold(), s);
                }
            });
        }
    }
    Ok(())
}

/// Helper: Resolve pubkey/license for Validate, with fallback to embedded product
fn resolve_keys(
    pubkey: Option<String>,
    signed_license: Option<String>,
    product: Option<Product>,
    embedded_product: Option<Product>,
) -> (Option<crate::DlcKey>, Option<crate::SignedLicense>) {
    resolve_keys_with_search_roots(
        pubkey,
        signed_license,
        product,
        embedded_product,
        &[PathBuf::from(".")],
    )
}

pub(crate) fn resolve_keys_with_search_roots(
    pubkey: Option<String>,
    signed_license: Option<String>,
    product: Option<Product>,
    embedded_product: Option<Product>,
    search_roots: &[PathBuf],
) -> (Option<crate::DlcKey>, Option<crate::SignedLicense>) {
    let product_name = product
        .as_ref()
        .or_else(|| embedded_product.as_ref())
        .map(|value| value.as_ref().to_string());

    let (resolved_pubkey_str, resolved_license_str) = match product_name.as_deref() {
        Some(name) => resolve_pubkey_and_license_with_search_roots(
            pubkey,
            signed_license,
            name,
            search_roots,
        ),
        None => (
            pubkey.map(resolve_file_or_value),
            signed_license.map(resolve_file_or_value),
        ),
    };

    let resolved_pubkey = resolved_pubkey_str.and_then(|s| match crate::DlcKey::public(&s) {
        Ok(k) => Some(k),
        Err(_) => None,
    });

    let resolved_license = resolved_license_str.map(crate::SignedLicense::from);

    (resolved_pubkey, resolved_license)
}

fn find_product_file_in_search_roots(
    product: &str,
    ext: &str,
    search_roots: &[PathBuf],
) -> Option<String> {
    let file_name = format!("{}.{}", product, ext);

    for root in search_roots {
        let direct_path = root.join(&file_name);
        if direct_path.is_file() {
            return std::fs::read_to_string(&direct_path)
                .ok()
                .map(|s| s.trim().to_string());
        }

        let mut matches = Vec::new();
        if collect_files_recursive(root, &mut matches, Some(ext), 3).is_ok() {
            for path in matches {
                if let Some(found_name) = path.file_name().and_then(|s| s.to_str()) {
                    if found_name.eq_ignore_ascii_case(&file_name) {
                        return std::fs::read_to_string(&path)
                            .ok()
                            .map(|s| s.trim().to_string());
                    }
                }
            }
        }
    }

    None
}

fn print_error(message: &str) {
    eprintln!("{}: {}", "error".red().bold(), message.white());
}

fn print_warning(message: &str) {
    eprintln!("{}: {}", "warning".yellow().bold(), message.white());
}

fn print_error_and_exit(message: &str) -> ! {
    print_error(message);
    // exit with error status so calling processes can detect failure
    std::process::exit(1);
}

/// Returns true if the file appears to be an executable or script.
/// Checks Unix permissions, binary magic numbers using `infer`, and shebangs.
fn is_executable(path: &std::path::Path) -> bool {
    // Check content for binary executables via infer
    if let Ok(Some(t)) = infer::get_from_path(path) {
        match t.matcher_type() {
            infer::MatcherType::App => return true,
            _ => {}
        }
    }

    false
}

// Helper: attempt to decrypt the first archive entry using the provided symmetric key from a reader.
// Returns Ok(()) on success; Err(...) on any failure (decryption or archive extraction).
fn test_decrypt_archive_with_key_from_reader<R: std::io::Read>(
    dlc_pack_file: &str,
    mut reader: R,
    encrypt_key: &EncryptionKey,
    signature_verified: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    // parse once so we know the version and block metadata; we'll reopen the
    // file later to read the raw ciphertext blocks for v5 packs.
    let (_prod, _did, version, entries, blocks) = parse_encrypted_pack(&mut reader)?;
    if entries.is_empty() {
        println!("container has no entries");
        return Ok(());
    }

    // v5 packs do not store per-entry ciphertext in the manifest. Use the
    // first block metadata entry to locate and decrypt the archive bytes.
    let (archive_nonce, archive_ciphertext) = if version == DLC_PACK_VERSION_LATEST as usize {
        let b = blocks
            .first()
            .ok_or("v5 pack missing block metadata for archive decrypt")?;
        let mut f = std::fs::File::open(dlc_pack_file)?;
        use std::io::Seek;
        f.seek(std::io::SeekFrom::Start(b.file_offset))?;
        let mut buf = vec![0u8; b.encrypted_size as usize];
        f.read_exact(&mut buf)?;
        (b.nonce, buf)
    } else {
        return Err(format!("unsupported pack version: {}", version).into());
    };

    // replicate the current in-place decrypt logic so we don't rely on the
    // pack_format module being public.
    use aes_gcm::aead::AeadInPlace;
    use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
    use secure_gate::RevealSecret;

    let mut buf = archive_ciphertext.clone();
    let _ = encrypt_key.with_secret(|key_bytes| {
        let cipher = Aes256Gcm::new_from_slice(key_bytes).map_err(|e| e.to_string())?;
        let nonce = Nonce::from_slice(&archive_nonce);
        cipher
            .decrypt_in_place(nonce, &[], &mut buf)
            .map_err(|_| "decryption failed (incorrect key or corrupted ciphertext)".to_string())
    })?;
    let plain = buf;

    let dec = flate2::read::GzDecoder::new(std::io::Cursor::new(plain));
    let mut ar = tar::Archive::new(dec);
    ar.entries()
        .map_err(|e| Box::<dyn std::error::Error>::from(format!("(archive extract): {}", e)))?;

    if signature_verified {
        println!("{} -> {}", "GOOD".green().bold(), dlc_pack_file);
    } else {
        println!(
            "{} -> {}\n{}",
            "OKAY:".yellow().bold(),
            dlc_pack_file,
            ".dlcpack archive decrypts with embedded encrypt key (signature NOT verified).\nTry providing the corresponding public key and signed license to verify the signature."
        );
    }

    Ok(())
}

/// Validate a .dlcpack file against an optional signed license and public key, with fallback to embedded product for resolving keys files.
fn validate_dlc_file(
    path: &std::path::Path,
    product_arg: Option<&str>,
    signed_license_arg: Option<&str>,
    pubkey_arg: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    use std::io::Seek;

    // Use streaming reader for efficient processing
    let file = std::fs::File::open(path)?;
    let mut reader = std::io::BufReader::new(file);

    // Parse and get embedded product/dlc id
    let (prod, dlc_id, _v, _ents, _blocks) = parse_encrypted_pack(&mut reader)?;
    let embedded_product = Some(prod.clone());

    // resolve pubkey and signed license with fallback to embedded product (recursively)
    let (supplied_pubkey, supplied_license) = resolve_keys(
        pubkey_arg.map(|s| s.to_string()),
        signed_license_arg.map(|s| s.to_string()),
        product_arg.map(|s| Product::from(s.to_string())),
        embedded_product,
    );

    if supplied_license.is_none() {
        return Err("no signed license supplied or found (use --signed-license or --product <name> to pick <product>.slicense)".into());
    }
    let supplied_license = supplied_license.unwrap();

    // when a pubkey is supplied, verify the signed-license and check DLC coverage
    if let Some(pk) = supplied_pubkey.as_ref() {
        let verifier = pk;
        if !verifier.verify_signed_license(&supplied_license) {
            return Err("signed-license verification failed".into());
        }
        // we can inspect the license directly without cloning
        let verified_product = extract_product_from_license(&supplied_license).unwrap_or_default();
        if Product::from(verified_product) != prod {
            return Err("license product does not match pack".into());
        }
        let verified_dlcs = extract_dlc_ids_from_license(&supplied_license);
        if !verified_dlcs.iter().any(|d| d == &dlc_id.as_ref()) {
            return Err(format!("license does not include DLC id '{}'", dlc_id).into());
        }
    }
    // extract the encrypt key from the license's payload and attempt to decrypt the first archive entry to verify correctness. Note that this does not verify the signature, so we print a warning if no pubkey was supplied.
    // use library helper now that we have a SignedLicense value
    if let Some(enc_key) = extract_encrypt_key_from_license(&supplied_license) {
        reader.seek(std::io::SeekFrom::Start(0))?;
        test_decrypt_archive_with_key_from_reader(
            path.to_str().unwrap(),
            &mut reader,
            &enc_key,
            supplied_pubkey.is_some(),
        )?;
    } else if supplied_pubkey.is_some() {
        print_warning(
            "License verified but does not carry an embedded encrypt key — cannot test decrypt",
        );
    }

    Ok(())
}

/// Helper: search for a .dlcpack file with the specified dlc_id under root_path (recursive, up to depth)
fn find_dlcpack(
    root_path: &Path,
    dlc_id: impl Into<DlcId>,
    depth: Option<usize>,
) -> Result<(PathBuf, usize, DlcPack), Box<dyn std::error::Error>> {
    let dlc_id = dlc_id.into();
    let mut candidates: Vec<PathBuf> = Vec::new();
    collect_files_recursive(
        root_path,
        &mut candidates,
        Some("dlcpack"),
        depth.unwrap_or(5),
    )?;
    let mut best_match: Option<(PathBuf, usize, DlcPack)> = None;
    for p in candidates {
        let file = std::fs::File::open(&p)?;
        let mut reader = std::io::BufReader::new(file);
        let (prod, did, version, ents, _blocks) = parse_encrypted_pack(&mut reader)?;
        let did = DlcId::from(did);
        // if dlc_id is not an exact match, skip
        if did != dlc_id {
            continue;
        }

        let pack = DlcPack::new(
            did.clone(),
            prod,
            version as u8,
            ents.into_iter()
                .map(|(path, encrypted)| DlcPackEntry::new(path, encrypted))
                .collect(),
        );
        best_match = Some((p, version, pack));
        break;
    }
    if let Some(matched) = best_match {
        Ok(matched)
    } else {
        Err(format!("no .dlcpack found with dlc_id '{}'", dlc_id).into())
    }
}

async fn pack_command(
    app: &mut App,
    dlc_id_str: String,
    files: Vec<PathBuf>,
    list: bool,
    out: Option<PathBuf>,
    product: String,
    types: Option<Vec<String>>,
    metadata: Option<Vec<String>>,
    pubkey: Option<String>,
    signed_license: Option<String>,
    dry_run: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let (pubkey, signed_license) = resolve_pubkey_and_license(pubkey, signed_license, &product);

    // A signed license is required so the same encryption key is used consistently.
    // Use `generate` to create one if you don't have one yet.
    if signed_license.is_none() {
        return Err(format!(
            "no signed license found for product '{product}'. \
             Run `bevy-dlc generate {product} <dlc_id>` to create one first, \
             then use `--signed-license <path-or-token>` or place `{product}.slicense` in the current directory."
        ).into());
    }

    // Collect all input files (from files or directories)
    let mut selected_files: Vec<PathBuf> = Vec::new();
    for entry in &files {
        if entry.is_dir() {
            collect_files_recursive(entry, &mut selected_files, None, 10)?;
        } else if entry.is_file() {
            selected_files.push(entry.clone());
        } else {
            return Err(format!("input path not found: {}", entry.display()).into());
        }
    }

    if selected_files.is_empty() {
        return Err("no files selected for dlcpack".into());
    }

    let type_overrides = types
        .as_ref()
        .map(|t| parse_type_overrides(t))
        .unwrap_or_default();
    let type_path_map = bevy::tasks::block_on(async {
        resolve_type_paths_from_bevy(app, &selected_files, &type_overrides).await
    })?;
    let pack_metadata = metadata
        .as_ref()
        .map(|values| parse_metadata_assignments(values))
        .transpose()?
        .unwrap_or_default();

    let mut items: Vec<PackItem> = Vec::new();
    for file in &selected_files {
        if is_executable(file) {
            return Err(format!("refusing to pack executable file: {}", file.display()).into());
        }

        let mut f = File::open(file)?;
        let mut bytes = Vec::new();
        f.read_to_end(&mut bytes)?;

        let mut rel = file
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("file")
            .to_string();
        for base in &files {
            if base.is_dir() && file.starts_with(base) {
                rel = file
                    .strip_prefix(base)
                    .unwrap()
                    .to_string_lossy()
                    .to_string();
                break;
            }
        }
        let ext = file
            .extension()
            .and_then(|s| s.to_str())
            .map(|s| s.to_string());
        let type_path = type_path_map.get(file).cloned();

        let mut item = PackItem::new(rel.clone(), bytes.clone())?;
        if let Some(e) = ext {
            item = item.with_extension(e)?;
        }
        if let Some(tp) = type_path {
            item = item.with_type_path(tp);
        }
        items.push(item);
    }

    let dlc_id = DlcId::from(dlc_id_str.clone());
    // Generate a new signing key for the pack. The private seed is never embedded
    // in the signed license for security reasons - only the symmetric encryption key is.
    let dlc_key = if let Some(pk) = pubkey.as_deref() {
        match DlcKey::public(pk) {
            Ok(k) => k,
            Err(_) => DlcKey::generate_random(),
        }
    } else {
        DlcKey::generate_random()
    };
    let encrypt_key = derive_encrypt_key(signed_license.as_deref())?;

    let container = pack_encrypted_pack_with_metadata(
        &dlc_id,
        &items,
        &Product::from(product.clone()),
        &pack_metadata,
        &encrypt_key,
        bevy_dlc::DEFAULT_BLOCK_SIZE,
    )?;

    handle_license_output(
        signed_license.as_deref(),
        pubkey.as_deref(),
        &product,
        &dlc_id_str,
        Some(&dlc_key),
        !dry_run,
    )?;

    if list {
        let parsed = parse_encrypted_pack_info(&container[..], Some(&encrypt_key))?;
        let did = parsed.dlc_id;
        let version = parsed.version;
        let ents = parsed.entries;
        println!("{} {} entries: {}", "dlc_id".blue(), did, ents.len());
        print_pack_metadata(&parsed.metadata, parsed.metadata_locked);
        print_pack_entries(version, &ents);
    }

    let out_path = if let Some(out_val) = out {
        let path = PathBuf::from(&out_val);
        if path.exists() {
            if path.is_dir() {
                // explicit existing directory
                path.join(format!("{}.dlcpack", dlc_id_str))
            } else {
                // explicit existing file
                path
            }
        } else {
            // If the path has an extension, treat it as a filename (even if it doesn't exist yet).
            // Otherwise treat it as a directory and create it.
            if path.extension().is_some() {
                path
            } else {
                if !path.exists() {
                    std::fs::create_dir_all(&path)?;
                }
                path.join(format!("{}.dlcpack", dlc_id_str))
            }
        }
    } else {
        PathBuf::from(format!("{}.dlcpack", dlc_id_str))
    };
    if dry_run {
        print_warning(format!("dry-run: would create dlcpack: {}", out_path.display()).as_str());
    } else {
        std::fs::write(&out_path, &container)?;
        println!("created dlcpack: {}", out_path.display());
    }
    Ok(())
}

fn build_pack_app() -> App {
    let mut app = App::new();
    app.add_plugins(
        DefaultPlugins
            .set(WindowPlugin {
                primary_window: None,
                ..default()
            })
            .disable::<WinitPlugin>()
            .set(LogPlugin {
                level: bevy::log::Level::ERROR,
                ..Default::default()
            }),
    );

    app.finish();
    app.cleanup();
    app.update();
    app
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Version { dlc } => {
            // package name & version
            println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
            if let Some(path) = dlc {
                let result = (|| -> Result<_, Box<dyn std::error::Error>> {
                    let file = std::fs::File::open(&path)?;
                    let mut reader = std::io::BufReader::new(file);
                    let (_prod, did, version, _ents, _blocks) = parse_encrypted_pack(&mut reader)?;
                    Ok((did, version))
                })();
                match result {
                    Ok((did, version)) => {
                        println!("{} -> {} (pack v{})", path.display(), did.as_str(), version);
                    }
                    Err(e) => {
                        print_error(&format!(
                            "error reading/parsing '{}': {}",
                            path.display(),
                            e
                        ));
                        std::process::exit(1);
                    }
                }
            }
            return Ok(());
        }
        Commands::Pack {
            dlc_id: dlc_id_str,
            files,
            list,
            out,
            product,
            types,
            metadata,
            pubkey,
            signed_license,
        } => {
            let mut app = build_pack_app();
            bevy::tasks::block_on(async {
                pack_command(
                    &mut app,
                    dlc_id_str,
                    files,
                    list,
                    out,
                    product,
                    types,
                    metadata,
                    pubkey,
                    signed_license,
                    cli.dry_run,
                )
                .await
            })?;
        }

        Commands::List { dlc } => {
            if dlc.is_dir() {
                let mut files = Vec::new();
                collect_files_recursive(&dlc, &mut files, Some("dlcpack"), 10)?;
                if files.is_empty() {
                    return Err("no .dlcpack files found in directory".into());
                }
                for file in &files {
                    let f = std::fs::File::open(file)?;
                    let mut reader = std::io::BufReader::new(f);
                    let parsed = parse_encrypted_pack_info(&mut reader, None)?;
                    let did = parsed.dlc_id;
                    let version = parsed.version;
                    let ents = parsed.entries;
                    println!(
                        "{} -> {} {} (v{}) entries: {}",
                        "dlcpack:".color(AnsiColors::Blue),
                        did.as_str().color(AnsiColors::Magenta).bold(),
                        file.display(),
                        version,
                        ents.len()
                    );
                    print_pack_metadata(&parsed.metadata, parsed.metadata_locked);
                    print_pack_entries(version, &ents);
                }
                return Ok(());
            }

            // single-file mode
            let file = std::fs::File::open(&dlc)?;
            let mut reader = std::io::BufReader::new(file);
            let parsed = parse_encrypted_pack_info(&mut reader, None)?;
            let did = parsed.dlc_id;
            let version = parsed.version;
            let ents = parsed.entries;
            println!(
                "{} {} (v{}) entries: {}",
                "dlcpack".color(AnsiColors::Blue),
                did.as_str().color(AnsiColors::Magenta).bold(),
                version,
                ents.len()
            );
            print_pack_metadata(&parsed.metadata, parsed.metadata_locked);
            print_pack_entries(version, &ents);
            return Ok(());
        }

        Commands::Check {
            dlc,
            product,
            signed_license,
            pubkey,
        } => {
            // directory mode: validate every .dlcpack inside recursively
            if dlc.is_dir() {
                let mut files = Vec::new();
                collect_files_recursive(&dlc, &mut files, Some("dlcpack"), 10)?;
                if files.is_empty() {
                    print_error_and_exit("no .dlcpack files found in directory");
                }

                let mut failures = 0usize;
                for file in &files {
                    match validate_dlc_file(
                        file.as_path(),
                        product.as_deref(),
                        signed_license.as_deref(),
                        pubkey.as_deref(),
                    ) {
                        Ok(()) => {}
                        Err(e) => {
                            print_error(&format!("{}: {}", file.display(), e));
                            failures += 1;
                        }
                    }
                }

                if failures > 0 {
                    print_error_and_exit(&format!("{} file(s) failed validation", failures));
                }
                return Ok(());
            }

            // single-file mode
            match validate_dlc_file(
                &dlc,
                product.as_deref(),
                signed_license.as_deref(),
                pubkey.as_deref(),
            ) {
                Ok(()) => return Ok(()),
                Err(e) => print_error_and_exit(&e.to_string()),
            }
        }

        Commands::Generate {
            product,
            dlcs,
            out_dir,
            force,
        } => {
            // create private key + signed license (private key seed becomes embedded encrypt_key)
            let dlc_key = DlcKey::generate_random();
            let signedlicense =
                dlc_key.create_signed_license(&dlcs, Product::from(product.clone()))?;

            // determine output paths (use out_dir when provided)
            let out_dir_path = out_dir
                .clone()
                .unwrap_or_else(|| std::path::PathBuf::from("."));
            if !out_dir_path.exists() {
                std::fs::create_dir_all(&out_dir_path)?;
            }
            let slicense_path = out_dir_path.join(format!("{}.slicense", product));
            let pubkey_path = out_dir_path.join(format!("{}.pubkey", product));

            if !force {
                if slicense_path.exists() || pubkey_path.exists() {
                    // verify the contents of any pre‑existing file so we can warn
                    // about corrupted/forged data instead of silently accepting it.
                    if slicense_path.exists() {
                        let valid = std::fs::read_to_string(&slicense_path)
                            .ok()
                            .and_then(|s| {
                                let sl = bevy_dlc::SignedLicense::from(s.trim().to_string());
                                // at minimum we must be able to extract an encrypt key
                                bevy_dlc::extract_encrypt_key_from_license(&sl).map(|_| ())
                            })
                            .is_some();
                        if !valid {
                            print_error_and_exit(
                                format!(
                                    "existing {} is not a valid signed license; use --force to overwrite",
                                    slicense_path.display()
                                )
                                .as_str(),
                            );
                        }
                    }
                    if pubkey_path.exists() {
                        let valid = std::fs::read_to_string(&pubkey_path)
                            .ok()
                            .map(|pk| DlcKey::public(pk.trim()).is_ok())
                            .unwrap_or(false);
                        if !valid {
                            print_error_and_exit(
                                format!(
                                    "existing {} is not a valid public key; use --force to overwrite",
                                    pubkey_path.display()
                                )
                                .as_str(),
                            );
                        }
                    }
                    // both files are present and structurally valid: refuse to clobber
                    print_error_and_exit(
                        format!(
                            "'{}' or '{}' already exists; use {} to overwrite",
                            slicense_path.display(),
                            pubkey_path.display(),
                            "--force".color(AnsiColors::Magenta).bold()
                        )
                        .as_str(),
                    );
                }
            }

            // print token + pubkey to stdout; write files when not in dry-run mode
            // (out_dir defaults to current directory).
            let write_files = !cli.dry_run;
            signedlicense.with_secret(|s| {
                print_signed_license_and_pubkey(
                    s.as_str(),
                    &dlc_key,
                    write_files,
                    Some(product.as_str()),
                    Some(&out_dir_path),
                )
            });

            if cli.dry_run {
                print_warning(
                    format!(
                        "dry-run: would write {} and {}",
                        slicense_path.display(),
                        pubkey_path.display()
                    )
                    .as_str(),
                );
            } else {
                println!(
                    "Wrote {} and {}.",
                    slicense_path.display(),
                    pubkey_path.display()
                );
                print_warning(
                    "Do NOT SHARE these files or the contents printed above with untrusted parties.",
                );
            }
            return Ok(());
        }
        Commands::Edit {
            dlc,
            signed_license,
            pubkey,
            product,
            command,
        } => {
            // Use streaming reader for efficient processing
            let file = std::fs::File::open(&dlc)?;
            let mut reader = std::io::BufReader::new(file);
            let (emb_prod, _emb_did, _v, _ents, _blocks) = parse_encrypted_pack(&mut reader)?;

            // resolve pubkey and signed license with fallback to embedded product
            let (_, sup_lic) = resolve_keys(
                pubkey,
                signed_license,
                product.map(|p| Product::from(p)),
                Some(emb_prod),
            );

            // extract the encryption key from the license if present
            let encrypt_key = if let Some(lic) = sup_lic.as_ref() {
                extract_encrypt_key_from_license(lic)
                    .map(|ek| ek.with_secret(|kb| EncryptionKey::new(*kb)))
            } else {
                None
            };

            // pass along any trailing arguments as a one-shot command
            let initial = if command.is_empty() {
                None
            } else {
                Some(command.clone())
            };
            repl::run_edit_repl(dlc, encrypt_key, initial, cli.dry_run)?;
        }
        Commands::Find {
            dlc_id,
            dir,
            max_depth,
        } => match find_dlcpack(&dir, dlc_id.clone(), Some(max_depth)) {
            Ok((path, _version, _pack)) => {
                println!("Found .dlcpack at: {}", path.display().bold());
            }
            Err(e) => {
                print_error(&e.to_string());
            }
        },
        Commands::AesKey => {
            if cli.dry_run {
                print_warning("dry-run: would generate and print a random 32-character AES key");
            } else {
                // The macro consumer expects a 32-character printable ASCII key.
                // Encoding 24 random bytes as base64url without padding yields exactly 32 characters.
                let key = URL_SAFE_NO_PAD.encode(rand::random::<[u8; 24]>());
                println!("{} {}", "AES KEY:".color(AnsiColors::Cyan).bold(), key);
            }
        }
        Commands::Watch { dlc_id } => {
            watch::run_watch_command(cli.dry_run, dlc_id.as_deref())?;
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::collect_files_recursive;
    use tempfile::tempdir;

    /// `collect_files_recursive` with no ext_filter must never return files whose
    /// extension appears in FORBIDDEN_EXTENSIONS (.dlcpack, .slicense, .pubkey,
    /// native binaries, etc.).
    #[test]
    fn collect_files_skips_forbidden_extensions() {
        let tmp = tempdir().unwrap();

        // Create asset files that SHOULD be collected.
        let txt = tmp.path().join("sprite.txt");
        let json = tmp.path().join("level.json");
        let png = tmp.path().join("icon.png");
        std::fs::write(&txt, b"hello").unwrap();
        std::fs::write(&json, b"{}").unwrap();
        std::fs::write(&png, b"\x89PNG").unwrap();

        // Create files whose extensions must be silently excluded.
        let forbidden_cases = [
            "bundle.dlcpack",
            "game.slicense",
            "game.pubkey",
            "app.exe",
            "runtime.dll",
            "module.so",
            "lib.dylib",
            "debug.pdb",
            "link.exp",
            "link.lib",
            "object.o",
            "rustlib.rlib",
            "archive.a",
        ];
        for name in &forbidden_cases {
            std::fs::write(tmp.path().join(name), b"data").unwrap();
        }

        let mut collected = Vec::new();
        collect_files_recursive(tmp.path(), &mut collected, None, 5).unwrap();

        // Every collected path must NOT have a forbidden extension.
        const FORBIDDEN: &[&str] = &[
            "dlcpack", "slicense", "pubkey", "exe", "dll", "so", "dylib", "pdb", "ilk", "exp",
            "lib", "a", "o", "rlib",
        ];
        for path in &collected {
            let ext = path
                .extension()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_ascii_lowercase();
            assert!(
                !FORBIDDEN.contains(&ext.as_str()),
                "forbidden extension '.{}' was collected: {}",
                ext,
                path.display()
            );
        }

        // All three asset files must be present.
        let names: Vec<_> = collected
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert!(
            names.contains(&"sprite.txt".to_string()),
            "sprite.txt missing"
        );
        assert!(
            names.contains(&"level.json".to_string()),
            "level.json missing"
        );
        assert!(names.contains(&"icon.png".to_string()), "icon.png missing");

        // Total count: exactly the three asset files (none of the forbidden ones).
        assert_eq!(
            collected.len(),
            3,
            "unexpected files collected: {:?}",
            names
        );
    }

    /// When an ext_filter IS specified, the targeted search works correctly: only
    /// files with the requested extension are returned, and no excluded-extension
    /// filtering is applied (because callers like `list`, `check`, and `find_dlcpack`
    /// need to locate `.dlcpack` files by extension).
    #[test]
    fn collect_files_ext_filter_returns_matching_files() {
        let tmp = tempdir().unwrap();
        std::fs::write(tmp.path().join("bundle.dlcpack"), b"data").unwrap();
        std::fs::write(tmp.path().join("other.dlcpack"), b"data").unwrap();
        std::fs::write(tmp.path().join("good.txt"), b"data").unwrap();

        let mut collected = Vec::new();
        collect_files_recursive(tmp.path(), &mut collected, Some("dlcpack"), 5).unwrap();

        // .dlcpack files must be found when explicitly requested via ext_filter.
        assert_eq!(
            collected.len(),
            2,
            "expected 2 .dlcpack files, got: {:?}",
            collected
        );
        assert!(
            collected
                .iter()
                .any(|p| p.file_name().unwrap() == "bundle.dlcpack")
        );
        assert!(
            collected
                .iter()
                .any(|p| p.file_name().unwrap() == "other.dlcpack")
        );

        // .txt must not appear since it doesn't match the filter.
        assert!(
            !collected
                .iter()
                .any(|p| p.extension().and_then(|e| e.to_str()) == Some("txt"))
        );
    }

    /// Hidden files (names starting with `.`) must never be collected.
    #[test]
    fn collect_files_skips_hidden_files() {
        let tmp = tempdir().unwrap();
        std::fs::write(tmp.path().join(".hidden"), b"secret").unwrap();
        std::fs::write(tmp.path().join("visible.txt"), b"data").unwrap();

        let mut collected = Vec::new();
        collect_files_recursive(tmp.path(), &mut collected, None, 5).unwrap();

        let names: Vec<_> = collected
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert!(
            !names.iter().any(|n| n.starts_with('.')),
            "hidden file collected"
        );
        assert!(names.contains(&"visible.txt".to_string()));
    }

    /// Directories named `target` or `node_modules` (and hidden dirs) must be skipped.
    #[test]
    fn collect_files_skips_build_dirs() {
        let tmp = tempdir().unwrap();
        let target_dir = tmp.path().join("target");
        let nm_dir = tmp.path().join("node_modules");
        let hidden_dir = tmp.path().join(".git");
        std::fs::create_dir_all(&target_dir).unwrap();
        std::fs::create_dir_all(&nm_dir).unwrap();
        std::fs::create_dir_all(&hidden_dir).unwrap();
        std::fs::write(target_dir.join("artifact.txt"), b"build").unwrap();
        std::fs::write(nm_dir.join("dep.txt"), b"dep").unwrap();
        std::fs::write(hidden_dir.join("config"), b"cfg").unwrap();
        std::fs::write(tmp.path().join("asset.txt"), b"asset").unwrap();

        let mut collected = Vec::new();
        collect_files_recursive(tmp.path(), &mut collected, None, 5).unwrap();

        let names: Vec<_> = collected
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert!(
            !names.contains(&"artifact.txt".to_string()),
            "target/ was traversed"
        );
        assert!(
            !names.contains(&"dep.txt".to_string()),
            "node_modules/ was traversed"
        );
        assert!(names.contains(&"asset.txt".to_string()));
    }
}