archmeld 1.3.0

Secure, memory-safe, type-safe CLI for multi-format archive extraction, inspection and decompression
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
//! CLI command structure and dispatch.
//!
// CLI layer: as_conversions for ByteSize wrappers and
// arithmetic for counters are safe in this context.
#![allow(clippy::as_conversions)]
#![allow(clippy::arithmetic_side_effects)]
#![allow(clippy::cast_possible_truncation)]

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use bytesize::ByteSize;
use clap::{Parser, Subcommand, ValueEnum};
use comfy_table::{Table, presets::UTF8_FULL};

use crate::archive::{ArchiveEntry, Extractor, is_exarch_format};
use crate::error::Error;
use crate::format::{self, ArchiveFormat};
use crate::{cpt, gzinspect, lz4, sit, size, updater};
use sha2::{Digest, Sha256};
use std::io::IsTerminal;
use std::io::{BufReader, Cursor};

/// archmeld — secure, memory-safe, type-safe archive multi-tool.
///
/// Unified CLI for extracting, inspecting, listing, and verifying archives
/// across ZIP, TAR (gz/bz2/xz/zst/lz4), 7-Zip, Gzip, LZ4, `StuffIt`,
/// and Compact Pro formats.
#[derive(Parser)]
#[command(name = "archmeld", version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
    /// Report whether a newer release exists, then exit.
    ///
    /// Exits 10 when an update is available, 0 when up to date. A network
    /// failure also exits 0 — checking never breaks a script.
    #[arg(long, global = true)]
    check_update: bool,

    /// Download and install the latest release, then exit.
    #[arg(long, global = true)]
    self_update: bool,

    /// Refuse --self-update (env: `ARCHMELD_NO_SELF_UPDATE`).
    ///
    /// Runtime policy opt-out for package-managed and air-gapped installs.
    /// Exits 3 when it refuses. The CLI flag always wins over the env var.
    #[arg(long, global = true)]
    no_self_update: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Extract files from an archive
    Extract {
        /// Path to the archive file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output directory (default: current directory)
        #[arg(short, long, default_value = ".")]
        output: PathBuf,

        /// Override auto-detected format
        #[arg(short, long)]
        format: Option<FormatArg>,

        /// Maximum single file size (K/M/G/T suffixes)
        #[arg(long, default_value = "100M")]
        max_file_size: String,

        /// Maximum total extraction size (K/M/G/T suffixes)
        #[arg(long, default_value = "1G")]
        max_total_size: String,

        /// Maximum number of files to extract
        #[arg(long, default_value_t = 10_000)]
        max_files: usize,

        /// Maximum compression ratio (zip bomb protection)
        #[arg(long, default_value_t = 100)]
        max_compression_ratio: u64,

        /// Allow symlinks (within extraction directory)
        #[arg(long)]
        allow_symlinks: bool,

        /// Allow hardlinks (within extraction directory)
        #[arg(long)]
        allow_hardlinks: bool,

        /// Preserve file permissions from archive
        #[arg(long)]
        preserve_permissions: bool,

        /// Overwrite existing files
        #[arg(long)]
        force: bool,

        /// Allow solid 7z archives (higher memory use)
        #[arg(long)]
        allow_solid_archives: bool,

        /// Allow world-writable file permissions (0o002)
        #[arg(long)]
        allow_world_writable: bool,
    },

    /// List contents of an archive
    List {
        /// Path to the archive file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Override auto-detected format
        #[arg(short, long)]
        format: Option<FormatArg>,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Detect and display format information
    Info {
        /// Path to the file to identify
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Inspect gzip file headers and metadata
    #[command(name = "gz-inspect")]
    GzInspect {
        /// Path to the gzip file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Verify CRC-32 integrity
        #[arg(long)]
        verify: bool,

        /// Show individual gzip member/chunk boundaries
        #[arg(long)]
        chunks: bool,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// LZ4 compression and decompression
    Lz4 {
        #[command(subcommand)]
        action: Lz4Action,
    },

    /// Inspect `StuffIt` (.sit) archive
    #[command(name = "sit-inspect")]
    SitInspect {
        /// Path to the `StuffIt` archive
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Inspect Compact Pro (.cpt) archive
    #[command(name = "cpt-inspect")]
    CptInspect {
        /// Path to the Compact Pro archive
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Verify header CRC-32
        #[arg(long)]
        verify: bool,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Verify archive integrity
    Verify {
        /// Path to the archive file
        #[arg(value_name = "FILE")]
        input: PathBuf,
    },
}

#[derive(Subcommand)]
enum Lz4Action {
    /// Decompress an LZ4 file
    Decompress {
        /// Input LZ4 file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output file (default: strip .lz4 extension)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    /// Compress a file with LZ4
    Compress {
        /// Input file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output file (default: append .lz4 extension)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    /// Inspect LZ4 frame header
    Inspect {
        /// Input LZ4 file
        #[arg(value_name = "FILE")]
        input: PathBuf,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Clone, ValueEnum)]
enum FormatArg {
    Zip,
    Tar,
    TarGz,
    TarBz2,
    TarXz,
    TarZst,
    TarLz4,
    #[value(name = "7z")]
    SevenZip,
    Gz,
    Bz2,
    Xz,
    Lz4,
    Zstd,
    Lzma,
    Lha,
    Rar,
    Arc,
    Zoo,
    Xar,
}

impl From<FormatArg> for ArchiveFormat {
    fn from(arg: FormatArg) -> Self {
        match arg {
            FormatArg::Zip => Self::Zip,
            FormatArg::Tar => Self::Tar,
            FormatArg::TarGz => Self::TarGz,
            FormatArg::TarBz2 => Self::TarBz2,
            FormatArg::TarXz => Self::TarXz,
            FormatArg::TarZst => Self::TarZst,
            FormatArg::TarLz4 => Self::TarLz4,
            FormatArg::SevenZip => Self::SevenZip,
            FormatArg::Gz => Self::Gz,
            FormatArg::Bz2 => Self::Bz2,
            FormatArg::Xz => Self::Xz,
            FormatArg::Lz4 => Self::Lz4,
            FormatArg::Zstd => Self::Zstd,
            FormatArg::Lzma => Self::Lzma,
            FormatArg::Lha => Self::Lha,
            FormatArg::Rar => Self::Rar,
            FormatArg::Arc => Self::Arc,
            FormatArg::Zoo => Self::Zoo,
            FormatArg::Xar => Self::Xar,
        }
    }
}

/// Run the CLI.
///
/// # Errors
///
/// Returns error on any command failure.
#[allow(clippy::fn_params_excessive_bools)]
pub fn run() -> anyhow::Result<u8> {
    let cli = Cli::parse();

    // Update actions are one-shot: they act and exit, never falling through
    // into the main program. Order is fixed by skills/rust-self-update --
    // --check-update is evaluated before --self-update.
    if cli.check_update {
        let outcome = updater::check_update();
        println!("{}", outcome.message());
        return Ok(outcome.exit_code());
    }
    if cli.self_update {
        let disabled = updater::is_disabled(cli.no_self_update);
        // A user-initiated update may prompt, but only with a terminal
        // attached; otherwise it would stall a CI job or a cron entry forever.
        let interactive = std::io::stdin().is_terminal();
        let outcome = updater::self_update(disabled, interactive)?;
        println!("{}", outcome.message());
        return Ok(outcome.exit_code());
    }

    let Some(command) = cli.command else {
        // No subcommand and no update action: clap's own help is the right
        // answer, and it exits 2 like any other usage error.
        let mut cmd = <Cli as clap::CommandFactory>::command();
        cmd.print_help()?;
        println!();
        return Ok(2);
    };

    run_command(command).map(|()| 0)
}

/// Dispatch a subcommand.
///
/// # Errors
///
/// Returns error on any command failure.
#[allow(clippy::fn_params_excessive_bools)]
fn run_command(command: Commands) -> anyhow::Result<()> {
    match command {
        Commands::Extract {
            input,
            output,
            format,
            max_file_size,
            max_total_size,
            max_files,
            max_compression_ratio,
            allow_symlinks,
            allow_hardlinks,
            preserve_permissions,
            force,
            allow_solid_archives,
            allow_world_writable,
        } => cmd_extract(
            &input,
            &output,
            format,
            &max_file_size,
            &max_total_size,
            max_files,
            max_compression_ratio,
            allow_symlinks,
            allow_hardlinks,
            preserve_permissions,
            force,
            allow_solid_archives,
            allow_world_writable,
        ),
        Commands::List {
            input,
            format,
            json,
        } => cmd_list(&input, format, json),
        Commands::Info { input, json } => cmd_info(&input, json),
        Commands::GzInspect {
            input,
            verify,
            chunks,
            json,
        } => cmd_gz_inspect(&input, verify, chunks, json),
        Commands::Lz4 { action } => cmd_lz4(action),
        Commands::SitInspect { input, json } => cmd_sit_inspect(&input, json),
        Commands::CptInspect {
            input,
            verify,
            json,
        } => cmd_cpt_inspect(&input, verify, json),
        Commands::Verify { input } => cmd_verify(&input),
    }
}

fn read_file(path: &Path) -> anyhow::Result<Vec<u8>> {
    if !path.exists() {
        return Err(Error::FileNotFound(path.to_path_buf()).into());
    }
    Ok(fs::read(path)?)
}

fn resolve_format(path: &Path, data: &[u8], format_arg: Option<FormatArg>) -> ArchiveFormat {
    format_arg.map_or_else(
        || format::detect_format_from_path(path, data),
        std::convert::Into::into,
    )
}

/// Build an `exarch_core::SecurityConfig` from CLI args.
#[allow(clippy::fn_params_excessive_bools)]
#[allow(clippy::too_many_arguments)]
fn build_security_config(
    max_file_size: u64,
    max_total_size: u64,
    max_files: usize,
    max_compression_ratio: u64,
    allow_symlinks: bool,
    allow_hardlinks: bool,
    preserve_permissions: bool,
    allow_solid_archives: bool,
    allow_world_writable: bool,
) -> exarch_core::SecurityConfig {
    #[allow(clippy::cast_precision_loss)]
    let ratio = max_compression_ratio as f64;
    exarch_core::SecurityConfig {
        max_file_size,
        max_total_size,
        max_compression_ratio: ratio,
        max_file_count: max_files,
        allow_solid_archives,
        allowed: exarch_core::config::AllowedFeatures {
            symlinks: allow_symlinks,
            hardlinks: allow_hardlinks,
            world_writable: allow_world_writable,
            ..Default::default()
        },
        preserve_permissions,
        ..exarch_core::SecurityConfig::default()
    }
}

#[allow(clippy::fn_params_excessive_bools)]
#[allow(clippy::too_many_arguments)]
fn cmd_extract(
    input: &Path,
    output: &Path,
    format_arg: Option<FormatArg>,
    max_file_size_str: &str,
    max_total_size_str: &str,
    max_files: usize,
    max_compression_ratio: u64,
    allow_symlinks: bool,
    allow_hardlinks: bool,
    preserve_permissions: bool,
    force: bool,
    allow_solid_archives: bool,
    allow_world_writable: bool,
) -> anyhow::Result<()> {
    let max_file_size = size::parse_size(max_file_size_str)?;
    let max_total_size = size::parse_size(max_total_size_str)?;

    let data = read_file(input)?;
    let fmt = resolve_format(input, &data, format_arg);

    if fmt == ArchiveFormat::Unknown {
        anyhow::bail!(
            "Could not determine archive format for: {}",
            input.display()
        );
    }

    eprintln!("Extracting {} archive: {}", fmt, input.display());

    if fmt == ArchiveFormat::Xar {
        return extract_xar(input, output, force);
    }

    if fmt == ArchiveFormat::Dds {
        anyhow::bail!(
            "DDS is a texture format, not an \
             extractable archive. Use 'info' to \
             inspect it."
        );
    }

    if is_exarch_format(fmt) {
        extract_via_exarch(
            input,
            output,
            max_file_size,
            max_total_size,
            max_files,
            max_compression_ratio,
            allow_symlinks,
            allow_hardlinks,
            preserve_permissions,
            allow_solid_archives,
            allow_world_writable,
        )
    } else {
        extract_native(
            input,
            &data,
            fmt,
            output,
            &NativeExtractPolicy {
                max_file_size,
                max_total_size,
                max_files,
                max_compression_ratio,
                force,
            },
        )
    }
}

/// Extract using exarch-core (ZIP, TAR, 7z).
#[allow(clippy::fn_params_excessive_bools)]
#[allow(clippy::too_many_arguments)]
fn extract_via_exarch(
    input: &Path,
    output: &Path,
    max_file_size: u64,
    max_total_size: u64,
    max_files: usize,
    max_compression_ratio: u64,
    allow_symlinks: bool,
    allow_hardlinks: bool,
    preserve_permissions: bool,
    allow_solid_archives: bool,
    allow_world_writable: bool,
) -> anyhow::Result<()> {
    // WHY: disallowed-methods wants "explicit error handling + permissions".
    // Error handling is explicit via `?`. The path here is the OPERATOR's own
    // -o argument, not archive-derived, so inheriting the process umask is the
    // correct behaviour -- forcing a mode would override the operator's choice.
    #[allow(clippy::disallowed_methods)]
    fs::create_dir_all(output)?;

    let config = build_security_config(
        max_file_size,
        max_total_size,
        max_files,
        max_compression_ratio,
        allow_symlinks,
        allow_hardlinks,
        preserve_permissions,
        allow_solid_archives,
        allow_world_writable,
    );

    let report = exarch_core::extract_archive(input, output, &config)
        .map_err(|e| Error::ExarchExtraction(e.to_string()))?;

    for warning in &report.warnings {
        eprintln!("Warning: {warning}");
    }

    eprintln!(
        "Extracted {} files, {} dirs ({}) to {}",
        report.files_extracted,
        report.directories_created,
        ByteSize(report.bytes_written),
        output.display()
    );

    if report.files_skipped > 0 {
        eprintln!("Skipped {} files (security checks)", report.files_skipped);
    }

    if report.files_extracted == 0 && report.files_skipped > 0 {
        anyhow::bail!(
            "No files extracted: all {} files were \
             skipped by security checks. Consider \
             --allow-solid-archives, \
             --allow-world-writable, or adjusting \
             --max-file-size / --max-total-size.",
            report.files_skipped
        );
    }

    Ok(())
}

/// Extract using archmeld-native code (LHA, LZ4, etc.).
#[allow(clippy::too_many_arguments)]
/// Apply a deterministic, safe mode to something archmeld just extracted.
///
/// The native extraction path previously relied on the process umask, which is
/// ambient configuration: on a host with a permissive umask (`0002`, say) an
/// extracted file would come out group-writable. archmeld handles hostile input
/// on triage machines, so the mode it produces must not depend on how the shell
/// happened to be configured.
///
/// Files become `0o644`, directories `0o755`. Neither is world-writable, and
/// neither carries setuid, setgid or the sticky bit — an archive cannot talk
/// archmeld into creating a privileged file.
///
/// `--preserve-permissions` is deliberately NOT honoured here: the native
/// formats reach this code as [`ExtractedFile`], which carries no mode field,
/// so there is no archive mode to preserve. That flag affects the exarch-core
/// path only. Saying so is better than pretending otherwise.
///
/// # Errors
///
/// Returns the underlying I/O error if the mode cannot be applied.
#[cfg(unix)]
fn set_safe_mode(path: &Path, is_dir: bool) -> std::io::Result<()> {
    use std::os::unix::fs::PermissionsExt as _;
    let mode = if is_dir { 0o755 } else { 0o644 };
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
}

/// Windows has no POSIX mode bits, so there is nothing to tighten.
///
/// # Errors
///
/// Never returns an error; the signature matches the Unix version.
#[cfg(not(unix))]
fn set_safe_mode(_path: &Path, _is_dir: bool) -> std::io::Result<()> {
    Ok(())
}

/// Everything the native extraction path is allowed to do, in one value.
///
/// These five knobs travelled together as five positional parameters, which is
/// how `max_file_size` and `max_total_size` — same type, adjacent, and easy to
/// transpose at a call site — could be swapped without the compiler noticing.
/// Named fields make that transposition impossible to write.
struct NativeExtractPolicy {
    /// Per-entry ceiling in bytes.
    max_file_size: u64,
    /// Whole-archive ceiling in bytes.
    max_total_size: u64,
    /// Maximum number of entries to extract.
    max_files: usize,
    /// Maximum decompressed-to-compressed expansion factor.
    max_compression_ratio: u64,
    /// Overwrite files that already exist in the output directory.
    force: bool,
}

fn extract_native(
    input: &Path,
    data: &[u8],
    fmt: ArchiveFormat,
    output: &Path,
    policy: &NativeExtractPolicy,
) -> anyhow::Result<()> {
    let force = policy.force;
    let extractor = Extractor::new()
        .with_max_file_size(policy.max_file_size)
        .with_max_total_size(policy.max_total_size)
        .with_max_files(policy.max_files)
        .with_max_compression_ratio(policy.max_compression_ratio);

    let files = extractor.extract(data, fmt)?;

    // WHY: disallowed-methods wants "explicit error handling + permissions".
    // Error handling is explicit via `?`. The path here is the OPERATOR's own
    // -o argument, not archive-derived, so inheriting the process umask is the
    // correct behaviour -- forcing a mode would override the operator's choice.
    #[allow(clippy::disallowed_methods)]
    fs::create_dir_all(output)?;

    let mut count = 0u32;
    let mut total_bytes: u64 = 0;

    for file in &files {
        // For standalone decompressed files, derive
        // the output name from the input filename
        // (strip the compression extension) instead
        // of using the generic "decompressed".
        let path = if file.path == "decompressed" {
            derive_decompressed_name(input)
        } else {
            file.path.clone()
        };
        let dest = output.join(&path);

        if file.is_directory {
            // WHY: disallowed-methods wants "explicit error handling + permissions".
            // Error handling is explicit via `?`, and the path is confined by
            // archive::sanitize_path before reaching here. PERMISSIONS ARE NOT SET:
            // there is no set_permissions anywhere in src/, so extracted entries take
            // the process umask. Tracked as a gap -- see CHANGELOG "Known issues".
            #[allow(clippy::disallowed_methods)]
            fs::create_dir_all(&dest)?;
            continue;
        }

        if let Some(parent) = dest.parent() {
            // WHY: disallowed-methods wants "explicit error handling + permissions".
            // Both are now satisfied: `?` for errors, set_safe_mode for the mode.
            // The path is confined by archive::sanitize_path before reaching here.
            #[allow(clippy::disallowed_methods)]
            fs::create_dir_all(parent)?;
            set_safe_mode(parent, true)?;
        }

        if dest.exists() && !force {
            eprintln!("Skipping (exists): {}", dest.display());
            continue;
        }

        // WHY: disallowed-methods wants "explicit error handling + permissions".
        // Both are now satisfied: `?` for errors, set_safe_mode for the mode.
        // The path is confined by archive::sanitize_path before reaching here.
        #[allow(clippy::disallowed_methods)]
        fs::write(&dest, &file.data)?;
        set_safe_mode(&dest, false)?;
        count += 1;
        total_bytes += file.size;
    }

    eprintln!(
        "Extracted {count} files ({}) to {}",
        ByteSize(total_bytes),
        output.display()
    );

    Ok(())
}

/// Derive a meaningful output filename for standalone
/// decompression by stripping the compression extension.
///
/// For example: `data.csv.gz` → `data.csv`,
/// `archive.lz4` → `archive`.
/// Falls back to `decompressed` if no stem is found.
fn derive_decompressed_name(input: &Path) -> String {
    let stem = input.file_stem().and_then(|s| s.to_str());
    match stem {
        Some(s) if !s.is_empty() => s.to_owned(),
        _ => "decompressed".to_owned(),
    }
}

fn cmd_list(input: &Path, format_arg: Option<FormatArg>, json: bool) -> anyhow::Result<()> {
    let data = read_file(input)?;
    let fmt = resolve_format(input, &data, format_arg);

    if fmt == ArchiveFormat::Unknown {
        anyhow::bail!(
            "Could not determine archive format for: {}",
            input.display()
        );
    }

    if fmt == ArchiveFormat::Xar {
        return list_xar(input, json);
    }

    if is_exarch_format(fmt) {
        return list_via_exarch(input, json);
    }

    let extractor = Extractor::new();

    // For native formats that support listing, use
    // list; otherwise fall back to extract
    let entries: Vec<ArchiveEntry> = if let Ok(e) = extractor.list(&data, fmt) {
        e
    } else {
        // Fall back: extract and convert
        let files = extractor.extract(&data, fmt)?;
        files
            .into_iter()
            .map(|f| ArchiveEntry {
                path: f.path,
                compressed_size: f.size,
                uncompressed_size: f.size,
                is_directory: f.is_directory,
                compression_method: "unknown".into(),
            })
            .collect()
    };

    print_list_output(&entries, input, json)
}

/// List archive contents via exarch-core.
fn list_via_exarch(input: &Path, json: bool) -> anyhow::Result<()> {
    let config = exarch_core::SecurityConfig::default();
    let manifest = exarch_core::list_archive(input, &config)
        .map_err(|e| Error::ExarchExtraction(e.to_string()))?;

    let entries: Vec<ArchiveEntry> = manifest
        .entries
        .iter()
        .map(|e| {
            let is_dir = e.entry_type == exarch_core::ManifestEntryType::Directory;
            ArchiveEntry {
                path: e.path.to_string_lossy().into_owned(),
                compressed_size: e.compressed_size.unwrap_or(e.size),
                uncompressed_size: e.size,
                is_directory: is_dir,
                compression_method: format!("{}", e.entry_type),
            }
        })
        .collect();

    print_list_output(&entries, input, json)
}

/// Print archive listing (shared between native and
/// exarch-core paths).
fn print_list_output(entries: &[ArchiveEntry], input: &Path, json: bool) -> anyhow::Result<()> {
    if json {
        let out = serde_json::to_string_pretty(entries)?;
        println!("{out}");
    } else {
        let mut table = Table::new();
        table.load_preset(UTF8_FULL);
        table.set_header(vec!["Path", "Compressed", "Uncompressed", "Method", "Type"]);

        for entry in entries {
            table.add_row(vec![
                entry.path.clone(),
                ByteSize(entry.compressed_size).to_string(),
                ByteSize(entry.uncompressed_size).to_string(),
                entry.compression_method.clone(),
                if entry.is_directory { "dir" } else { "file" }.into(),
            ]);
        }

        println!("{table}");
        eprintln!("{} entries in {}", entries.len(), input.display());
    }

    Ok(())
}

fn cmd_info(input: &Path, json: bool) -> anyhow::Result<()> {
    let data = read_file(input)?;
    let fmt = format::detect_format_from_path(input, &data);
    let info = format::format_info(fmt);

    if json {
        let out = serde_json::to_string_pretty(&info)?;
        println!("{out}");
    } else {
        println!("File:        {}", input.display());
        println!("Format:      {}", info.format);
        println!("Description: {}", info.description);
        println!("MIME type:   {}", info.mime_type);
        println!("Is archive:  {}", info.is_archive);
        println!("Compressed:  {}", info.is_compressed);
        println!("File size:   {}", ByteSize(data.len() as u64));

        // Show extended DDS texture metadata
        if fmt == ArchiveFormat::Dds {
            print_dds_info(&data)?;
        }
    }

    Ok(())
}

#[allow(clippy::too_many_lines)]
fn cmd_gz_inspect(input: &Path, verify: bool, chunks: bool, json: bool) -> anyhow::Result<()> {
    let data = read_file(input)?;
    let analysis = gzinspect::inspect(&data)?;

    if verify {
        let valid = gzinspect::verify_crc(&data)?;
        if valid {
            eprintln!("CRC-32 verification: PASSED");
        } else {
            eprintln!("CRC-32 verification: FAILED");
            anyhow::bail!("CRC-32 verification failed");
        }
    }

    if json {
        let out = serde_json::to_string_pretty(&analysis)?;
        println!("{out}");
    } else {
        let h = &analysis.header;
        println!("=== Gzip Header ===");
        println!("Compression:   {}", h.compression_method_name);
        println!("Flags:         0x{:02X}", h.flags);
        println!("  FTEXT:       {}", h.is_text);
        println!("  FHCRC:       {}", h.has_header_crc);
        println!("  FEXTRA:      {}", h.has_extra);
        println!("  FNAME:       {}", h.has_name);
        println!("  FCOMMENT:    {}", h.has_comment);
        println!("Mod time:      {}", h.mtime_formatted);
        println!(
            "Extra flags:   {} ({})",
            h.extra_flags, h.extra_flags_description
        );
        println!("OS:            {} ({})", h.os_code, h.os_name);

        if let Some(ref name) = h.original_name {
            println!("Orig name:     {name}");
        }
        if let Some(ref comment) = h.comment {
            println!("Comment:       {comment}");
        }
        if let Some(ref extra) = h.extra_data {
            println!("Extra data:    {} bytes", extra.len());
        }
        if let Some(crc) = h.header_crc16 {
            println!("Header CRC16:  0x{crc:04X}");
        }

        println!("\n=== File Statistics ===");
        println!("Header size:      {} bytes", h.header_size);
        println!("Compressed size:  {}", ByteSize(analysis.compressed_size));
        println!("File size:        {}", ByteSize(analysis.file_size));
        println!("SHA-256:          {}", analysis.sha256);
        println!("Members:          {}", analysis.member_count);
        println!("Multi-member:     {}", analysis.is_multi_member);

        if let Some(ref t) = analysis.trailer {
            println!("\n=== Gzip Trailer ===");
            println!("CRC-32:        0x{:08X}", t.crc32);
            println!(
                "Original size: {} (mod 2^32)",
                ByteSize(u64::from(t.original_size))
            );
        }
    }

    if chunks {
        print_gz_chunks(input)?;
    }

    Ok(())
}

fn cmd_lz4(action: Lz4Action) -> anyhow::Result<()> {
    match action {
        Lz4Action::Decompress { input, output } => {
            let data = read_file(&input)?;
            let decompressed = lz4::decompress_frame(&data)?;

            let out_path = output.unwrap_or_else(|| {
                let name = input.to_string_lossy();
                if let Some(stripped) = name.strip_suffix(".lz4") {
                    PathBuf::from(stripped)
                } else {
                    PathBuf::from(format!("{name}.decompressed"))
                }
            });

            // WHY: disallowed-methods wants "explicit error handling + permissions".
            // Error handling is explicit via `?`. The path here is the OPERATOR's own
            // -o argument, not archive-derived, so inheriting the process umask is the
            // correct behaviour -- forcing a mode would override the operator's choice.
            #[allow(clippy::disallowed_methods)]
            fs::write(&out_path, &decompressed)?;
            eprintln!(
                "Decompressed {} -> {} ({})",
                input.display(),
                out_path.display(),
                ByteSize(decompressed.len() as u64)
            );

            Ok(())
        },
        Lz4Action::Compress { input, output } => {
            let data = read_file(&input)?;
            let compressed = lz4::compress_frame(&data)?;

            let out_path =
                output.unwrap_or_else(|| PathBuf::from(format!("{}.lz4", input.display())));

            // WHY: disallowed-methods wants "explicit error handling + permissions".
            // Error handling is explicit via `?`. The path here is the OPERATOR's own
            // -o argument, not archive-derived, so inheriting the process umask is the
            // correct behaviour -- forcing a mode would override the operator's choice.
            #[allow(clippy::disallowed_methods)]
            fs::write(&out_path, &compressed)?;
            eprintln!(
                "Compressed {} -> {} ({} -> {})",
                input.display(),
                out_path.display(),
                ByteSize(data.len() as u64),
                ByteSize(compressed.len() as u64)
            );

            Ok(())
        },
        Lz4Action::Inspect { input, json } => {
            let data = read_file(&input)?;
            let info = lz4::parse_frame_header(&data)?;

            if json {
                let out = serde_json::to_string_pretty(&info)?;
                println!("{out}");
            } else {
                println!("=== LZ4 Frame Header ===");
                println!("Block independent:  {}", info.block_independent);
                println!("Block checksum:     {}", info.block_checksum);
                println!(
                    "Content size:       {}",
                    info.content_size
                        .map_or_else(|| "not present".into(), |s| ByteSize(s).to_string(),)
                );
                println!("Content checksum:   {}", info.content_checksum);
                println!(
                    "Block max size:     {}",
                    ByteSize(u64::from(info.block_max_size))
                );
            }

            Ok(())
        },
    }
}

fn cmd_sit_inspect(input: &Path, json: bool) -> anyhow::Result<()> {
    let data = read_file(input)?;
    let analysis = sit::analyze(&data)?;

    if json {
        let out = serde_json::to_string_pretty(&analysis)?;
        println!("{out}");
    } else {
        let h = &analysis.header;
        println!("=== StuffIt Archive ===");
        println!("Signature:  {}", h.signature);
        println!("Version:    {}", h.version);
        println!(
            "Format:     {}",
            if h.is_stuffit5 {
                "StuffIt 5.x"
            } else {
                "Classic StuffIt"
            }
        );
        println!("Entries:    {}", h.num_entries);
        println!("Size:       {}", ByteSize(u64::from(h.archive_size)));

        if !analysis.entries.is_empty() {
            println!("\n=== Entries ===");
            let mut table = Table::new();
            table.load_preset(UTF8_FULL);
            table.set_header(vec![
                "Name",
                "Type",
                "Compressed",
                "Uncompressed",
                "Method",
                "Encrypted",
            ]);

            for entry in &analysis.entries {
                table.add_row(vec![
                    entry.name.clone(),
                    if entry.is_directory { "dir" } else { "file" }.into(),
                    ByteSize(u64::from(entry.data_compressed_size)).to_string(),
                    ByteSize(u64::from(entry.data_uncompressed_size)).to_string(),
                    entry.compression_method_name.clone(),
                    if entry.is_encrypted { "YES" } else { "no" }.into(),
                ]);
            }

            println!("{table}");
        }
    }

    Ok(())
}

fn cmd_cpt_inspect(input: &Path, verify: bool, json: bool) -> anyhow::Result<()> {
    let data = read_file(input)?;
    let analysis = cpt::analyze(&data)?;

    if verify {
        let valid = cpt::verify(&data)?;
        if valid {
            eprintln!("Header CRC-32 verification: PASSED");
        } else {
            eprintln!("Header CRC-32 verification: FAILED");
        }
    }

    if json {
        let out = serde_json::to_string_pretty(&analysis)?;
        println!("{out}");
    } else {
        let h = &analysis.header;
        println!("=== Compact Pro Archive ===");
        println!("Volume:       {}", h.volume_number);
        println!("Header CRC:   0x{:08X}", h.header_crc32);
        println!("Entries:      {}", h.total_entries);
        if let Some(ref c) = h.comment {
            println!("Comment:      {c}");
        }

        if !analysis.entries.is_empty() {
            println!("\n=== Entries ===");
            let mut table = Table::new();
            table.load_preset(UTF8_FULL);
            table.set_header(vec![
                "Name",
                "Type",
                "Data Size",
                "Rsrc Size",
                "LZH",
                "Encrypted",
            ]);

            for entry in &analysis.entries {
                match entry {
                    cpt::CptEntry::Directory(d) => {
                        table.add_row(vec![
                            d.name.clone(),
                            "dir".into(),
                            "-".into(),
                            "-".into(),
                            "-".into(),
                            "-".into(),
                        ]);
                    },
                    cpt::CptEntry::File(f) => {
                        table.add_row(vec![
                            f.name.clone(),
                            "file".into(),
                            ByteSize(u64::from(f.data_uncompressed_size)).to_string(),
                            ByteSize(u64::from(f.rsrc_uncompressed_size)).to_string(),
                            format!("d:{} r:{}", f.data_lzh, f.rsrc_lzh),
                            if f.is_encrypted { "YES" } else { "no" }.into(),
                        ]);
                    },
                }
            }

            println!("{table}");
        }
    }

    Ok(())
}

fn cmd_verify(input: &Path) -> anyhow::Result<()> {
    let data = read_file(input)?;
    let fmt = format::detect_format_from_path(input, &data);

    eprintln!("Verifying {} (format: {})", input.display(), fmt);

    if fmt == ArchiveFormat::Xar {
        verify_xar(input)?;
    } else if is_exarch_format(fmt) {
        verify_via_exarch(input)?;
    } else {
        match fmt {
            ArchiveFormat::Gz | ArchiveFormat::TarGz => {
                let valid = gzinspect::verify_crc(&data)?;
                if valid {
                    println!(
                        "PASS: Gzip CRC-32 \
                         verification succeeded"
                    );
                } else {
                    anyhow::bail!(
                        "FAIL: Gzip CRC-32 \
                         verification failed"
                    );
                }
            },
            ArchiveFormat::CompactPro => {
                let valid = cpt::verify(&data)?;
                if valid {
                    println!(
                        "PASS: Compact Pro header \
                         CRC-32 verified"
                    );
                } else {
                    anyhow::bail!(
                        "FAIL: Compact Pro header \
                         CRC-32 mismatch"
                    );
                }
            },
            ArchiveFormat::StuffIt => {
                let analysis = sit::analyze(&data)?;
                println!(
                    "PASS: StuffIt archive header \
                     parsed ({} entries)",
                    analysis.entries.len()
                );
            },
            ArchiveFormat::Lz4 => {
                let _info = lz4::parse_frame_header(&data)?;
                let decompressed = lz4::decompress_frame(&data)?;
                println!(
                    "PASS: LZ4 frame decompressed \
                     successfully ({} bytes)",
                    decompressed.len()
                );
            },
            ArchiveFormat::Zip
            | ArchiveFormat::Tar
            | ArchiveFormat::TarBz2
            | ArchiveFormat::TarXz
            | ArchiveFormat::TarZst
            | ArchiveFormat::TarLz4
            | ArchiveFormat::SevenZip
            | ArchiveFormat::Bz2
            | ArchiveFormat::Xz
            | ArchiveFormat::Zstd
            | ArchiveFormat::Lzma
            | ArchiveFormat::Lha
            | ArchiveFormat::Rar
            | ArchiveFormat::Arc
            | ArchiveFormat::Zoo
            | ArchiveFormat::Xar
            | ArchiveFormat::Dds
            | ArchiveFormat::Unknown => {
                // Generic: try native extract
                let extractor = Extractor::new();
                let files = extractor.extract(&data, fmt)?;
                println!(
                    "PASS: Archive verified \
                     ({} entries)",
                    files.len()
                );
            },
        }
    }

    // Print SHA-256
    let mut hasher = Sha256::new();
    hasher.update(&data);
    let hash = hex::encode(hasher.finalize());
    println!("SHA-256: {hash}");

    std::io::stdout().flush()?;

    Ok(())
}

/// Verify an archive via exarch-core's security checks.
fn verify_via_exarch(input: &Path) -> anyhow::Result<()> {
    let config = exarch_core::SecurityConfig::default();
    let report = exarch_core::verify_archive(input, &config)
        .map_err(|e| Error::ExarchExtraction(e.to_string()))?;

    println!(
        "Verification: {} ({} entries, {})",
        report.status,
        report.total_entries,
        ByteSize(report.total_size)
    );
    println!("  Integrity: {}", report.integrity_status);
    println!("  Security:  {}", report.security_status);

    if !report.issues.is_empty() {
        println!("\nIssues:");
        for issue in &report.issues {
            println!(
                "  [{}/{}] {}",
                issue.severity, issue.category, issue.message
            );
            if let Some(ref path) = issue.entry_path {
                println!("    Entry: {}", path.display());
            }
        }
    }

    if report.is_safe() {
        println!("PASS: Archive verified");
    } else {
        anyhow::bail!(
            "FAIL: Security issues found \
             ({} suspicious entries)",
            report.suspicious_entries
        );
    }

    Ok(())
}

// ── XAR support ────────────────────────────────────

/// Extract a XAR archive using the xara crate.
///
/// Note: xara always overwrites existing files
/// (uses `create(true).truncate(true)` internally),
/// so `force` is accepted for API consistency but
/// has no additional effect.
fn extract_xar(input: &Path, output: &Path, _force: bool) -> anyhow::Result<()> {
    let file = fs::File::open(input)?;
    let mut archive = xara::XarArchive::open(file).map_err(|e| Error::Xar(e.to_string()))?;

    // WHY: disallowed-methods wants "explicit error handling + permissions".
    // Error handling is explicit via `?`. The path here is the OPERATOR's own
    // -o argument, not archive-derived, so inheriting the process umask is the
    // correct behaviour -- forcing a mode would override the operator's choice.
    #[allow(clippy::disallowed_methods)]
    fs::create_dir_all(output)?;

    let stats = archive
        .extract_all(output)
        .map_err(|e| Error::Xar(e.to_string()))?;

    eprintln!(
        "Extracted {} files, {} dirs ({}) to {}",
        stats.files,
        stats.dirs,
        ByteSize(stats.bytes),
        output.display()
    );

    if stats.symlinks_skipped > 0 {
        eprintln!("Skipped {} symlinks (security)", stats.symlinks_skipped);
    }

    Ok(())
}

/// List contents of a XAR archive.
fn list_xar(input: &Path, json: bool) -> anyhow::Result<()> {
    let file = fs::File::open(input)?;
    let archive = xara::XarArchive::open(file).map_err(|e| Error::Xar(e.to_string()))?;

    let entries: Vec<ArchiveEntry> = archive
        .files()
        .iter()
        .map(|f| {
            let is_dir = f.file_type == xara::XarFileType::Directory;
            let (compressed, uncompressed) = if let Some(ref data) = f.data {
                (data.length, data.size)
            } else {
                (0, 0)
            };
            ArchiveEntry {
                path: f.path.clone(),
                compressed_size: compressed,
                uncompressed_size: uncompressed,
                is_directory: is_dir,
                compression_method: f
                    .data
                    .as_ref()
                    .map_or_else(|| "none".into(), |d| d.encoding.clone()),
            }
        })
        .collect();

    print_list_output(&entries, input, json)
}

/// Verify a XAR archive by parsing it fully.
fn verify_xar(input: &Path) -> anyhow::Result<()> {
    let file = fs::File::open(input)?;
    let archive = xara::XarArchive::open(file).map_err(|e| Error::Xar(e.to_string()))?;

    let header = archive.header();
    let file_count = archive.files().len();

    println!(
        "PASS: XAR archive verified \
         (version {}, checksum {:?}, \
         {} entries)",
        header.version, header.checksum_algo, file_count
    );

    Ok(())
}

// ── Chunked gzip analysis (gzinspector) ────────────

/// Print individual gzip member boundaries using
/// the gzinspector crate.
fn print_gz_chunks(input: &Path) -> anyhow::Result<()> {
    let file = fs::File::open(input)?;
    let mut reader = BufReader::new(file);

    let mut offset: u64 = 0;
    let mut chunk_number: usize = 0;
    let mut total_compressed: u64 = 0;
    let mut total_uncompressed: u64 = 0;

    println!("\n=== Gzip Members (chunks) ===");

    let mut table = Table::new();
    table.load_preset(UTF8_FULL);
    table.set_header(vec![
        "#",
        "Offset",
        "Compressed",
        "Uncompressed",
        "Ratio",
        "Header",
    ]);

    loop {
        match gzinspector::read_chunk(&mut reader, offset, chunk_number) {
            Ok(info) => {
                table.add_row(vec![
                    format!("{}", info.chunk_number),
                    format!("0x{:X}", info.offset),
                    ByteSize(info.compressed_size).to_string(),
                    ByteSize(info.uncompressed_size).to_string(),
                    format!("{:.1}x", info.compression_ratio),
                    info.header_info.clone(),
                ]);

                total_compressed += info.compressed_size;
                total_uncompressed += info.uncompressed_size;
                offset += info.compressed_size;
                chunk_number += 1;
            },
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                break;
            },
            Err(e) => {
                // Non-fatal: some trailing bytes may
                // not form a valid member
                if chunk_number > 0 {
                    break;
                }
                return Err(e.into());
            },
        }
    }

    println!("{table}");
    eprintln!(
        "Total: {chunk_number} members, \
         {} compressed, {} uncompressed",
        ByteSize(total_compressed),
        ByteSize(total_uncompressed)
    );

    Ok(())
}

// ── DDS texture inspection ─────────────────────────

/// Show DDS texture metadata via `image_dds`.
fn print_dds_info(data: &[u8]) -> anyhow::Result<()> {
    let dds = image_dds::ddsfile::Dds::read(&mut Cursor::new(data))
        .map_err(|e| Error::InvalidArchive(format!("DDS parse error: {e}")))?;

    let width = dds.get_width();
    let height = dds.get_height();
    let depth = dds.get_depth();
    let mip_levels = dds.get_num_mipmap_levels();
    let array_layers = dds.get_num_array_layers();

    let format_str = match image_dds::dds_image_format(&dds) {
        Ok(fmt) => format!("{fmt:?}"),
        Err(info) => format!("Unknown (DXGI: {:?}, D3D: {:?})", info.dxgi, info.d3d),
    };

    println!("\n=== DDS Texture Details ===");
    println!("Dimensions:    {width} x {height}");
    if depth > 1 {
        println!("Depth:         {depth}");
    }
    println!("Mip levels:    {mip_levels}");
    if array_layers > 1 {
        println!("Array layers:  {array_layers}");
    }
    println!("Pixel format:  {format_str}");
    println!(
        "Data size:     {}",
        ByteSize(u64::from(dds.get_main_texture_size().unwrap_or(0)))
    );

    Ok(())
}

#[cfg(all(test, unix))]
// WHY(disallowed_methods): the ban on bare `std::fs::write` exists because it
// leaves permissions to the ambient umask — the exact defect `set_safe_mode`
// fixes. These tests must create a file with deliberately WRONG permissions to
// prove the fix tightens them, so the ban is inverted here: routing the
// fixtures through the safe helper would make every assertion below vacuous.
// WHY(tests_outside_test_module): the module IS `cfg(test)`; the lint only
// recognises a bare `#[cfg(test)]` and does not see through `all(test, unix)`.
// The extra `unix` is required — `PermissionsExt` does not exist elsewhere.
#[allow(clippy::disallowed_methods, clippy::tests_outside_test_module)]
mod tests {
    use super::set_safe_mode;
    use std::os::unix::fs::PermissionsExt as _;

    /// A permissive file must come out 0o644.
    ///
    /// The point of `set_safe_mode` is that the result does NOT depend on the
    /// ambient umask. Asserting "the mode is 0o644" would pass without the fix
    /// under the common umask 022, so the file is deliberately created
    /// world-writable first: only an explicit tightening can produce 0o644.
    #[test]
    fn set_safe_mode_tightens_a_permissive_file_to_0644() {
        let dir = tempfile::tempdir().expect("tempdir");
        let file = dir.path().join("loose.bin");
        std::fs::write(&file, b"x").expect("write");
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o666)).expect("loosen");

        set_safe_mode(&file, false).expect("set_safe_mode");

        let mode = std::fs::metadata(&file).expect("stat").permissions().mode() & 0o7777;
        assert_eq!(
            mode, 0o644,
            "an extracted file must end up 0o644 regardless of how it was created"
        );
    }

    /// Directories get 0o755, and the same umask-independence applies.
    #[test]
    fn set_safe_mode_tightens_a_permissive_dir_to_0755() {
        let dir = tempfile::tempdir().expect("tempdir");
        let sub = dir.path().join("loose");
        std::fs::create_dir_all(&sub).expect("mkdir");
        std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o777)).expect("loosen");

        set_safe_mode(&sub, true).expect("set_safe_mode");

        let mode = std::fs::metadata(&sub).expect("stat").permissions().mode() & 0o7777;
        assert_eq!(mode, 0o755, "an extracted directory must end up 0o755");
    }

    /// An archive must never talk archmeld into creating a privileged file.
    #[test]
    fn set_safe_mode_strips_setuid_setgid_and_sticky() {
        let dir = tempfile::tempdir().expect("tempdir");
        let file = dir.path().join("suid.bin");
        std::fs::write(&file, b"x").expect("write");
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o7777)).expect("loosen");

        set_safe_mode(&file, false).expect("set_safe_mode");

        let mode = std::fs::metadata(&file).expect("stat").permissions().mode() & 0o7777;
        assert_eq!(
            mode & 0o4000,
            0,
            "setuid must be stripped, mode was {mode:o}"
        );
        assert_eq!(
            mode & 0o2000,
            0,
            "setgid must be stripped, mode was {mode:o}"
        );
        assert_eq!(
            mode & 0o1000,
            0,
            "sticky must be stripped, mode was {mode:o}"
        );
        assert_eq!(
            mode & 0o002,
            0,
            "world-write must be off, mode was {mode:o}"
        );
    }
}