pkgsrc 0.10.0

Rust interface to pkgsrc packages and infrastructure
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
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
/*
 * Copyright (c) 2026 Jonathan Perkin <jonathan@perkin.org.uk>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*!
 * Read and write pkgsrc binary packages.
 *
 * pkgsrc binary packages come in two formats:
 *
 * 1. **Unsigned packages**: Compressed tar archives (`.tgz`, `.tbz`, etc.)
 *    containing package metadata (`+CONTENTS`, `+COMMENT`, `+DESC`, etc.)
 *    and the package files.
 *
 * 2. **Signed packages**: `ar(1)` archives containing:
 *    - `+PKG_HASH`: Hash metadata for verification
 *    - `+PKG_GPG_SIGNATURE`: GPG signature of the hash file
 *    - The original compressed tarball
 *
 * This module provides a two-layer API:
 *
 * ## Low-level (tar-style streaming)
 *
 * - [`Archive`]: Streaming access to archive entries
 * - [`Builder`]: Create new archives by appending entries
 *
 * ## High-level (convenience)
 *
 * - [`BinaryPackage`]: Cached metadata with fast reads and convenience methods
 * - [`SignedArchive`]: Output type for signed packages
 *
 * # Examples
 *
 * ## Fast metadata reading
 *
 * ```no_run
 * use pkgsrc::archive::BinaryPackage;
 *
 * let pkg = BinaryPackage::open("package-1.0.tgz")?;
 * println!("Package: {}", pkg.pkgname().unwrap_or("unknown"));
 * println!("Comment: {}", pkg.metadata().comment());
 *
 * // Convert to summary for repository management
 * let summary = pkg.to_summary()?;
 * # Ok::<(), pkgsrc::archive::ArchiveError>(())
 * ```
 *
 * ## Installing a package (iterating entries)
 *
 * ```no_run
 * use pkgsrc::archive::BinaryPackage;
 *
 * let pkg = BinaryPackage::open("package-1.0.tgz")?;
 *
 * // Check dependencies first (fast, uses cached metadata)
 * for dep in pkg.plist().depends() {
 *     println!("Depends: {}", dep);
 * }
 *
 * // Extract files (re-reads archive)
 * pkg.extract_to("/usr/pkg")?;
 * # Ok::<(), pkgsrc::archive::ArchiveError>(())
 * ```
 *
 * ## Building a new package
 *
 * ```no_run
 * use pkgsrc::archive::Builder;
 *
 * // Auto-detect compression from filename
 * let mut builder = Builder::create("package-1.0.tgz")?;
 * builder.append_metadata_file("+COMMENT", b"A test package")?;
 * builder.append_file("bin/hello", b"#!/bin/sh\necho hello", 0o755)?;
 * builder.finish()?;
 * # Ok::<(), pkgsrc::archive::ArchiveError>(())
 * ```
 *
 * ## Signing an existing package
 *
 * ```no_run
 * use pkgsrc::archive::BinaryPackage;
 *
 * let pkg = BinaryPackage::open("package-1.0.tgz")?;
 * let signature = b"GPG SIGNATURE DATA";
 * pkg.sign(signature)?.write_to("package-1.0-signed.tgz")?;
 * # Ok::<(), pkgsrc::archive::ArchiveError>(())
 * ```
 */

use std::collections::HashMap;
use std::ffi::OsString;
use std::fmt;
use std::fmt::Write as FmtWrite;
use std::fs::{self, File, Permissions};
use std::io::{self, BufReader, Cursor, Read, Seek, SeekFrom, Write};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use tar::{Archive as TarArchive, Builder as TarBuilder, Entries, Header};

use crate::metadata::{Entry, FileRead, Metadata};
use crate::plist::Plist;
use crate::summary::Summary;

/// Parse a mode string (octal) into a u32.
///
/// Supports formats like "0755", "755", "0644", etc.
fn parse_mode(mode_str: &str) -> Option<u32> {
    // Handle both "0755" and "755" formats
    u32::from_str_radix(mode_str, 8).ok()
}

/// Default block size for package hashing (64KB).
pub const DEFAULT_BLOCK_SIZE: usize = 65536;

/// Current pkgsrc signature version.
pub const PKGSRC_SIGNATURE_VERSION: u32 = 1;

/// Magic bytes identifying gzip compressed data.
const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];

/// Magic bytes identifying zstd compressed data.
const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd];

/// Result type for archive operations.
pub type Result<T> = std::result::Result<T, ArchiveError>;

// ============================================================================
// Compression
// ============================================================================

/// Compression format for package archives.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Compression {
    /// No compression (plain .tar)
    None,
    /// Gzip compression (.tgz, .tar.gz)
    #[default]
    Gzip,
    /// Zstandard compression (.tzst, .tar.zst)
    Zstd,
}

impl Compression {
    /// Detect compression format from magic bytes.
    #[must_use]
    pub fn from_magic(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < ZSTD_MAGIC.len() {
            return None;
        }
        if bytes.starts_with(&GZIP_MAGIC) {
            Some(Self::Gzip)
        } else if bytes.starts_with(&ZSTD_MAGIC) {
            Some(Self::Zstd)
        } else {
            None
        }
    }

    /// Detect compression format from file extension.
    #[must_use]
    pub fn from_extension(path: impl AsRef<Path>) -> Option<Self> {
        let name = path.as_ref().file_name()?.to_str()?;
        let lower = name.to_lowercase();

        if lower.ends_with(".tgz") || lower.ends_with(".tar.gz") {
            Some(Self::Gzip)
        } else if lower.ends_with(".tzst") || lower.ends_with(".tar.zst") {
            Some(Self::Zstd)
        } else if lower.ends_with(".tar") {
            Some(Self::None)
        } else {
            None
        }
    }

    /// Return the canonical file extension for this compression type.
    #[must_use]
    pub fn extension(&self) -> &'static str {
        match self {
            Self::None => "tar",
            Self::Gzip => "tgz",
            Self::Zstd => "tzst",
        }
    }
}

impl fmt::Display for Compression {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::None => write!(f, "none"),
            Self::Gzip => write!(f, "gzip"),
            Self::Zstd => write!(f, "zstd"),
        }
    }
}

// ============================================================================
// PkgHashAlgorithm
// ============================================================================

/// Hash algorithm used for package signing.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PkgHashAlgorithm {
    /// SHA-512 (recommended, default)
    #[default]
    Sha512,
    /// SHA-256
    Sha256,
}

impl PkgHashAlgorithm {
    /// Return the string representation as used in +PKG_HASH.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Sha512 => "SHA512",
            Self::Sha256 => "SHA256",
        }
    }

    /// Return the hash output size in bytes.
    #[must_use]
    pub fn hash_size(&self) -> usize {
        match self {
            Self::Sha512 => 64,
            Self::Sha256 => 32,
        }
    }

    /// Compute hash of data.
    #[must_use]
    pub fn hash(&self, data: &[u8]) -> Vec<u8> {
        use sha2::{Digest, Sha256, Sha512};
        match self {
            Self::Sha512 => Sha512::digest(data).to_vec(),
            Self::Sha256 => Sha256::digest(data).to_vec(),
        }
    }

    /// Format hash as lowercase hex string.
    #[must_use]
    pub fn hash_hex(&self, data: &[u8]) -> String {
        let bytes = self.hash(data);
        let mut s = String::with_capacity(bytes.len() * 2);
        for b in &bytes {
            let _ = write!(s, "{b:02x}");
        }
        s
    }
}

impl fmt::Display for PkgHashAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl std::str::FromStr for PkgHashAlgorithm {
    type Err = ArchiveError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_uppercase().as_str() {
            "SHA512" => Ok(Self::Sha512),
            "SHA256" => Ok(Self::Sha256),
            _ => Err(ArchiveError::UnsupportedAlgorithm(s.to_string())),
        }
    }
}

// ============================================================================
// Error
// ============================================================================

/// Error type for archive operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ArchiveError {
    /// I/O error.
    #[error("I/O error: {0}")]
    Io(#[from] io::Error),

    /// Invalid archive format.
    #[error("invalid archive format: {0}")]
    InvalidFormat(String),

    /// Invalid +PKG_HASH format.
    #[error("invalid +PKG_HASH format: {0}")]
    InvalidPkgHash(String),

    /// Missing required metadata.
    #[error("missing required metadata: {0}")]
    MissingMetadata(String),

    /// Invalid metadata content.
    #[error("invalid metadata: {0}")]
    InvalidMetadata(String),

    /// Plist parsing error.
    #[error("plist error: {0}")]
    Plist(#[from] crate::plist::PlistError),

    /// Hash verification failed.
    #[error("hash verification failed: {0}")]
    HashMismatch(String),

    /// Unsupported algorithm.
    #[error("unsupported hash algorithm: {0}")]
    UnsupportedAlgorithm(String),

    /// Unsupported compression.
    #[error("unsupported compression: {0}")]
    UnsupportedCompression(String),

    /// Summary generation error.
    #[error("summary error: {0}")]
    Summary(String),

    /// No path available for operation.
    #[error("no path available: {0}")]
    NoPath(String),
}

// ============================================================================
// ExtractOptions
// ============================================================================

/// Options for extracting package files.
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub struct ExtractOptions {
    /// Apply file modes from plist `@mode` directives.
    pub apply_mode: bool,
    /// Apply file ownership from plist `@owner`/`@group` directives.
    /// Note: Requires root privileges to change ownership.
    pub apply_ownership: bool,
    /// Preserve original timestamps from the archive.
    pub preserve_mtime: bool,
}

impl ExtractOptions {
    /// Create new extract options with all options disabled.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable applying file modes from plist.
    #[must_use]
    pub fn with_mode(mut self) -> Self {
        self.apply_mode = true;
        self
    }

    /// Enable applying file ownership from plist.
    #[must_use]
    pub fn with_ownership(mut self) -> Self {
        self.apply_ownership = true;
        self
    }

    /// Enable preserving original timestamps.
    #[must_use]
    pub fn with_mtime(mut self) -> Self {
        self.preserve_mtime = true;
        self
    }
}

/// Result of extracting a single file.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ExtractedFile {
    /// Path where the file was extracted.
    pub path: PathBuf,
    /// Whether this is a metadata file (starts with +).
    pub is_metadata: bool,
    /// MD5 checksum from plist, if present.
    pub expected_checksum: Option<String>,
    /// Mode applied to the file.
    pub mode: Option<u32>,
}

// ============================================================================
// PkgHash
// ============================================================================

/// The `+PKG_HASH` file contents for signed packages.
///
/// This structure represents the hash metadata file used in signed pkgsrc
/// packages. It contains information needed to verify the package integrity.
///
/// # Format
///
/// The `+PKG_HASH` file has the following format:
///
/// ```text
/// pkgsrc signature
/// version: 1
/// pkgname: package-1.0
/// algorithm: SHA512
/// block size: 65536
/// file size: 123456
/// <hash1>
/// <hash2>
/// ...
/// ```
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PkgHash {
    version: u32,
    pkgname: String,
    algorithm: PkgHashAlgorithm,
    block_size: usize,
    file_size: u64,
    hashes: Vec<String>,
}

impl PkgHash {
    /// Create a new `PkgHash` with default settings.
    #[must_use]
    pub fn new(pkgname: impl Into<String>) -> Self {
        Self {
            version: PKGSRC_SIGNATURE_VERSION,
            pkgname: pkgname.into(),
            algorithm: PkgHashAlgorithm::default(),
            block_size: DEFAULT_BLOCK_SIZE,
            file_size: 0,
            hashes: Vec::new(),
        }
    }

    /// Generate `PkgHash` from a tarball.
    pub fn from_tarball<R: Read>(
        pkgname: impl Into<String>,
        mut reader: R,
        algorithm: PkgHashAlgorithm,
        block_size: usize,
    ) -> Result<Self> {
        let mut pkg_hash = PkgHash::new(pkgname);
        pkg_hash.algorithm = algorithm;
        pkg_hash.block_size = block_size;

        let mut buffer = vec![0u8; block_size];
        let mut total_size: u64 = 0;

        loop {
            let bytes_read = reader.read(&mut buffer)?;
            if bytes_read == 0 {
                break;
            }

            total_size += bytes_read as u64;
            let hash = algorithm.hash_hex(&buffer[..bytes_read]);
            pkg_hash.hashes.push(hash);
        }

        pkg_hash.file_size = total_size;
        Ok(pkg_hash)
    }

    /// Return the pkgsrc signature version.
    #[must_use]
    pub fn version(&self) -> u32 {
        self.version
    }

    /// Return the package name.
    #[must_use]
    pub fn pkgname(&self) -> &str {
        &self.pkgname
    }

    /// Return the hash algorithm.
    #[must_use]
    pub fn algorithm(&self) -> PkgHashAlgorithm {
        self.algorithm
    }

    /// Return the block size.
    #[must_use]
    pub fn block_size(&self) -> usize {
        self.block_size
    }

    /// Return the original file size.
    #[must_use]
    pub fn file_size(&self) -> u64 {
        self.file_size
    }

    /// Return the block hashes.
    #[must_use]
    pub fn hashes(&self) -> &[String] {
        &self.hashes
    }

    /// Verify a tarball against this hash.
    pub fn verify<R: Read>(&self, mut reader: R) -> Result<bool> {
        let mut buffer = vec![0u8; self.block_size];
        let mut hash_idx = 0;
        let mut total_size: u64 = 0;

        loop {
            let bytes_read = reader.read(&mut buffer)?;
            if bytes_read == 0 {
                break;
            }

            total_size += bytes_read as u64;

            if hash_idx >= self.hashes.len() {
                return Err(ArchiveError::HashMismatch(
                    "more data than expected".into(),
                ));
            }

            let computed = self.algorithm.hash_hex(&buffer[..bytes_read]);
            if computed != self.hashes[hash_idx] {
                return Err(ArchiveError::HashMismatch(format!(
                    "block {} hash mismatch",
                    hash_idx
                )));
            }

            hash_idx += 1;
        }

        if total_size != self.file_size {
            return Err(ArchiveError::HashMismatch(format!(
                "file size mismatch: expected {}, got {}",
                self.file_size, total_size
            )));
        }

        if hash_idx != self.hashes.len() {
            return Err(ArchiveError::HashMismatch(
                "fewer blocks than expected".into(),
            ));
        }

        Ok(true)
    }
}

impl fmt::Display for PkgHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "pkgsrc signature")?;
        writeln!(f, "version: {}", self.version)?;
        writeln!(f, "pkgname: {}", self.pkgname)?;
        writeln!(f, "algorithm: {}", self.algorithm)?;
        writeln!(f, "block size: {}", self.block_size)?;
        writeln!(f, "file size: {}", self.file_size)?;
        for hash in &self.hashes {
            writeln!(f, "{}", hash)?;
        }
        Ok(())
    }
}

impl std::str::FromStr for PkgHash {
    type Err = ArchiveError;

    /**
     * Parse a `PkgHash` from `+PKG_HASH` file contents.
     */
    fn from_str(s: &str) -> Result<Self> {
        let lines: Vec<&str> = s.lines().collect();

        if lines.is_empty() || lines[0] != "pkgsrc signature" {
            return Err(ArchiveError::InvalidPkgHash(
                "missing 'pkgsrc signature' header".into(),
            ));
        }

        let mut pkg_hash = PkgHash::default();
        let mut header_complete = false;
        let mut line_idx = 1;

        while line_idx < lines.len() && !header_complete {
            let line = lines[line_idx];

            if let Some((key, value)) = line.split_once(": ") {
                match key {
                    "version" => {
                        pkg_hash.version = value.parse().map_err(|_| {
                            ArchiveError::InvalidPkgHash(format!(
                                "invalid version: {}",
                                value
                            ))
                        })?;
                    }
                    "pkgname" => {
                        pkg_hash.pkgname = value.to_string();
                    }
                    "algorithm" => {
                        pkg_hash.algorithm = value.parse()?;
                    }
                    "block size" => {
                        pkg_hash.block_size = value.parse().map_err(|_| {
                            ArchiveError::InvalidPkgHash(format!(
                                "invalid block size: {}",
                                value
                            ))
                        })?;
                    }
                    "file size" => {
                        pkg_hash.file_size = value.parse().map_err(|_| {
                            ArchiveError::InvalidPkgHash(format!(
                                "invalid file size: {}",
                                value
                            ))
                        })?;
                        header_complete = true;
                    }
                    _ => {
                        return Err(ArchiveError::InvalidPkgHash(format!(
                            "unknown header field: {}",
                            key
                        )));
                    }
                }
            } else if !line.is_empty() {
                header_complete = true;
                line_idx -= 1;
            }
            line_idx += 1;
        }

        while line_idx < lines.len() {
            let line = lines[line_idx].trim();
            if !line.is_empty() {
                pkg_hash.hashes.push(line.to_string());
            }
            line_idx += 1;
        }

        if pkg_hash.pkgname.is_empty() {
            return Err(ArchiveError::InvalidPkgHash("missing pkgname".into()));
        }

        Ok(pkg_hash)
    }
}

// ============================================================================
// ArchiveType
// ============================================================================

/// Type of binary package archive.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ArchiveType {
    /// Unsigned package (plain compressed tarball)
    Unsigned,
    /// Signed package (ar archive containing tarball + signatures)
    Signed,
}

// ============================================================================
// Archive (low-level, tar-style)
// ============================================================================

/// Wrapper for different decompression decoders.
///
/// This is an implementation detail exposed due to the generic nature of
/// [`Archive`]. Users should not need to interact with this type directly.
#[doc(hidden)]
#[allow(clippy::large_enum_variant)]
pub enum Decoder<R: Read> {
    None(R),
    Gzip(GzDecoder<R>),
    Zstd(zstd::stream::Decoder<'static, BufReader<R>>),
}

impl<R: Read> Read for Decoder<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Decoder::None(r) => r.read(buf),
            Decoder::Gzip(d) => d.read(buf),
            Decoder::Zstd(d) => d.read(buf),
        }
    }
}

/// Low-level streaming access to package archives.
///
/// This provides tar-style streaming access to archive entries. For most use
/// cases, prefer [`BinaryPackage`] which provides cached metadata and convenience
/// methods.
///
/// # Example
///
/// ```no_run
/// use pkgsrc::archive::{Archive, Compression};
/// use std::io::Read;
///
/// let mut archive = Archive::open("package-1.0.tgz")?;
/// for entry in archive.entries()? {
///     let entry = entry?;
///     println!("{}", entry.path()?.display());
/// }
/// # Ok::<(), pkgsrc::archive::ArchiveError>(())
/// ```
pub struct Archive<R: Read> {
    inner: TarArchive<Decoder<R>>,
    compression: Compression,
}

impl Archive<BufReader<File>> {
    /// Open an archive from a file path.
    ///
    /// Automatically detects compression format from magic bytes.
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let file = File::open(path)?;
        let mut reader = BufReader::new(file);

        // Read magic bytes for compression detection
        let mut magic = [0u8; 8];
        reader.read_exact(&mut magic)?;
        reader.seek(SeekFrom::Start(0))?;

        let compression = Compression::from_magic(&magic)
            .or_else(|| Compression::from_extension(path))
            .unwrap_or(Compression::Gzip);

        Archive::with_compression(reader, compression)
    }
}

impl<R: Read> Archive<R> {
    /// Create a new archive from a reader.
    ///
    /// Defaults to gzip compression. Use [`Archive::with_compression`] to
    /// specify a different format, or [`Archive::open`] to auto-detect from
    /// a file path.
    #[must_use = "creating an archive has no effect if not used"]
    pub fn new(reader: R) -> Result<Self> {
        Self::with_compression(reader, Compression::Gzip)
    }

    /// Create a new archive from a reader with explicit compression.
    #[must_use = "creating an archive has no effect if not used"]
    pub fn with_compression(
        reader: R,
        compression: Compression,
    ) -> Result<Self> {
        let decoder = match compression {
            Compression::None => Decoder::None(reader),
            Compression::Gzip => Decoder::Gzip(GzDecoder::new(reader)),
            Compression::Zstd => {
                Decoder::Zstd(zstd::stream::Decoder::new(reader)?)
            }
        };

        Ok(Archive {
            inner: TarArchive::new(decoder),
            compression,
        })
    }

    /// Return the compression format.
    #[must_use]
    pub fn compression(&self) -> Compression {
        self.compression
    }

    /// Return an iterator over the entries in this archive.
    #[must_use = "entries iterator must be used to iterate"]
    pub fn entries(&mut self) -> Result<Entries<'_, Decoder<R>>> {
        Ok(self.inner.entries()?)
    }
}

// ============================================================================
// Package (high-level, cached metadata)
// ============================================================================

/// Options for converting a [`BinaryPackage`] to a [`Summary`].
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub struct SummaryOptions {
    /// Compute the SHA256 checksum of the package file.
    ///
    /// This requires re-reading the entire package file, which can be slow
    /// for large packages. Default is `false`.
    pub compute_file_cksum: bool,
}

/// A pkgsrc binary package with cached metadata.
///
/// This provides fast access to package metadata without re-reading the
/// archive. The metadata is read once during [`BinaryPackage::open`], and subsequent
/// operations like [`BinaryPackage::archive`] or [`BinaryPackage::extract_to`] re-open
/// the archive as needed.
///
/// # Example
///
/// ```no_run
/// use pkgsrc::archive::BinaryPackage;
///
/// // Fast metadata access
/// let pkg = BinaryPackage::open("package-1.0.tgz")?;
/// println!("Name: {}", pkg.pkgname().unwrap_or("unknown"));
/// println!("Comment: {}", pkg.metadata().comment());
///
/// // Generate summary for repository
/// let summary = pkg.to_summary()?;
///
/// // Extract files (re-reads archive)
/// pkg.extract_to("/usr/pkg")?;
/// # Ok::<(), pkgsrc::archive::ArchiveError>(())
/// ```
#[derive(Debug)]
pub struct BinaryPackage {
    /// Path to the package file.
    path: PathBuf,

    /// Detected compression format.
    compression: Compression,

    /// Type of package (signed or unsigned).
    archive_type: ArchiveType,

    /// Parsed metadata from the package.
    metadata: Metadata,

    /// Parsed packing list.
    plist: Plist,

    /// Build info key-value pairs.
    build_info: HashMap<String, Vec<String>>,

    /// Package hash (for signed packages).
    pkg_hash: Option<PkgHash>,

    /// GPG signature (for signed packages).
    gpg_signature: Option<Vec<u8>>,

    /// File size of the package.
    file_size: u64,
}

impl BinaryPackage {
    /// Open a package from a file path.
    ///
    /// This reads only the metadata entries at the start of the archive,
    /// providing fast access to package information without decompressing
    /// the entire file.
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let file = File::open(path)?;
        let file_size = file.metadata()?.len();
        let mut reader = BufReader::new(file);

        // Read magic bytes
        let mut magic = [0u8; 8];
        reader.read_exact(&mut magic)?;
        reader.seek(SeekFrom::Start(0))?;

        // Check for ar archive (signed package)
        if &magic[..7] == b"!<arch>" {
            Self::read_signed(path, reader, file_size)
        } else {
            Self::read_unsigned(path, reader, &magic, file_size)
        }
    }

    /// Read an unsigned package (compressed tarball).
    fn read_unsigned<R: Read + Seek>(
        path: &Path,
        reader: R,
        magic: &[u8],
        file_size: u64,
    ) -> Result<Self> {
        let compression = Compression::from_magic(magic)
            .or_else(|| Compression::from_extension(path))
            .unwrap_or(Compression::Gzip);

        let decompressed: Box<dyn Read> = match compression {
            Compression::None => Box::new(reader),
            Compression::Gzip => Box::new(GzDecoder::new(reader)),
            Compression::Zstd => Box::new(zstd::stream::Decoder::new(reader)?),
        };

        let mut archive = TarArchive::new(decompressed);
        let mut metadata = Metadata::new();
        let mut plist = Plist::new();
        let mut build_info: HashMap<String, Vec<String>> = HashMap::new();

        for entry_result in archive.entries()? {
            let mut entry = entry_result?;
            let entry_path = entry.path()?.into_owned();

            // Stop at first non-metadata file (fast path)
            let Some(entry_type) =
                entry_path.to_str().and_then(Entry::from_filename)
            else {
                break;
            };

            // Pre-allocate based on entry size to avoid reallocation during read
            let entry_size = entry.header().size().unwrap_or(0) as usize;
            let mut content = String::with_capacity(entry_size);
            entry.read_to_string(&mut content)?;
            metadata.read_metadata(entry_type, &content).map_err(|e| {
                ArchiveError::InvalidMetadata(format!(
                    "{}: {}",
                    entry_path.display(),
                    e
                ))
            })?;

            if entry_path.as_os_str() == "+CONTENTS" {
                plist = Plist::from_bytes(content.as_bytes())?;
            } else if entry_path.as_os_str() == "+BUILD_INFO" {
                for line in content.lines() {
                    if let Some((key, value)) = line.split_once('=') {
                        build_info
                            .entry(key.to_string())
                            .or_default()
                            .push(value.to_string());
                    }
                }
            }
        }

        metadata.validate().map_err(|e| {
            ArchiveError::MissingMetadata(format!("incomplete package: {}", e))
        })?;

        Ok(Self {
            path: path.to_path_buf(),
            compression,
            archive_type: ArchiveType::Unsigned,
            metadata,
            plist,
            build_info,
            pkg_hash: None,
            gpg_signature: None,
            file_size,
        })
    }

    /// Read a signed package (ar archive).
    fn read_signed<R: Read>(
        path: &Path,
        reader: R,
        file_size: u64,
    ) -> Result<Self> {
        let mut ar = ar::Archive::new(reader);

        let mut pkg_hash_content: Option<String> = None;
        let mut gpg_signature: Option<Vec<u8>> = None;
        let mut metadata = Metadata::new();
        let mut plist = Plist::new();
        let mut build_info: HashMap<String, Vec<String>> = HashMap::new();
        let mut compression = Compression::Gzip;

        loop {
            let mut entry = match ar.next_entry() {
                Some(Ok(entry)) => entry,
                Some(Err(e)) if e.kind() == io::ErrorKind::UnexpectedEof => {
                    break;
                }
                Some(Err(e)) => return Err(e.into()),
                None => break,
            };
            let name = String::from_utf8_lossy(entry.header().identifier())
                .to_string();

            match name.as_str() {
                "+PKG_HASH" => {
                    let mut content = String::new();
                    entry.read_to_string(&mut content)?;
                    pkg_hash_content = Some(content);
                }
                "+PKG_GPG_SIGNATURE" => {
                    let mut data = Vec::new();
                    entry.read_to_end(&mut data)?;
                    gpg_signature = Some(data);
                }
                _ if name.ends_with(".tgz")
                    || name.ends_with(".tzst")
                    || name.ends_with(".tar") =>
                {
                    // Detect compression from inner tarball name
                    compression = Compression::from_extension(&name)
                        .unwrap_or(Compression::Gzip);

                    let decompressed: Box<dyn Read> = match compression {
                        Compression::None => Box::new(entry),
                        Compression::Gzip => Box::new(GzDecoder::new(entry)),
                        Compression::Zstd => {
                            Box::new(zstd::stream::Decoder::new(entry)?)
                        }
                    };

                    let mut archive = TarArchive::new(decompressed);

                    for tar_entry_result in archive.entries()? {
                        let mut tar_entry = tar_entry_result?;
                        let entry_path = tar_entry.path()?.into_owned();

                        let Some(entry_type) =
                            entry_path.to_str().and_then(Entry::from_filename)
                        else {
                            break;
                        };

                        // Pre-allocate based on entry size to avoid reallocation
                        let entry_size =
                            tar_entry.header().size().unwrap_or(0) as usize;
                        let mut content = String::with_capacity(entry_size);
                        tar_entry.read_to_string(&mut content)?;
                        metadata.read_metadata(entry_type, &content).map_err(
                            |e| {
                                ArchiveError::InvalidMetadata(format!(
                                    "{}: {}",
                                    entry_path.display(),
                                    e
                                ))
                            },
                        )?;

                        if entry_path.as_os_str() == "+CONTENTS" {
                            plist = Plist::from_bytes(content.as_bytes())?;
                        } else if entry_path.as_os_str() == "+BUILD_INFO" {
                            for line in content.lines() {
                                if let Some((key, value)) = line.split_once('=')
                                {
                                    build_info
                                        .entry(key.to_string())
                                        .or_default()
                                        .push(value.to_string());
                                }
                            }
                        }
                    }
                    break;
                }
                _ => {}
            }
        }

        let pkg_hash: Option<PkgHash> =
            pkg_hash_content.as_deref().map(str::parse).transpose()?;

        metadata.validate().map_err(|e| {
            ArchiveError::MissingMetadata(format!("incomplete package: {}", e))
        })?;

        Ok(Self {
            path: path.to_path_buf(),
            compression,
            archive_type: ArchiveType::Signed,
            metadata,
            plist,
            build_info,
            pkg_hash,
            gpg_signature,
            file_size,
        })
    }

    /// Return the path to the package file.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Return the compression format.
    #[must_use]
    pub fn compression(&self) -> Compression {
        self.compression
    }

    /// Return the archive type (signed or unsigned).
    #[must_use]
    pub fn archive_type(&self) -> ArchiveType {
        self.archive_type
    }

    /// Return whether this package is signed.
    #[must_use]
    pub fn is_signed(&self) -> bool {
        self.archive_type == ArchiveType::Signed
    }

    /// Return the package metadata.
    #[must_use]
    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    /// Return the packing list.
    #[must_use]
    pub fn plist(&self) -> &Plist {
        &self.plist
    }

    /// Return the package name from the plist.
    #[must_use]
    pub fn pkgname(&self) -> Option<&str> {
        self.plist.pkgname()
    }

    /// Return the build info key-value pairs.
    #[must_use]
    pub fn build_info(&self) -> &HashMap<String, Vec<String>> {
        &self.build_info
    }

    /// Get a specific build info value (first value if multiple exist).
    #[must_use]
    pub fn build_info_value(&self, key: &str) -> Option<&str> {
        self.build_info
            .get(key)
            .and_then(|v| v.first())
            .map(|s| s.as_str())
    }

    /// Get all values for a build info key.
    #[must_use]
    pub fn build_info_values(&self, key: &str) -> Option<&[String]> {
        self.build_info.get(key).map(|v| v.as_slice())
    }

    /// Return the package hash (for signed packages).
    #[must_use]
    pub fn pkg_hash(&self) -> Option<&PkgHash> {
        self.pkg_hash.as_ref()
    }

    /// Return the GPG signature (for signed packages).
    #[must_use]
    pub fn gpg_signature(&self) -> Option<&[u8]> {
        self.gpg_signature.as_deref()
    }

    /// Return the file size of the package.
    #[must_use]
    pub fn file_size(&self) -> u64 {
        self.file_size
    }

    /// Open the archive for iteration (re-reads the file).
    pub fn archive(&self) -> Result<Archive<BufReader<File>>> {
        Archive::open(&self.path)
    }

    /// Extract all files to a destination directory.
    ///
    /// This re-reads the archive and extracts all entries.
    pub fn extract_to(&self, dest: impl AsRef<Path>) -> Result<()> {
        let mut archive = self.archive()?;
        for entry in archive.entries()? {
            let mut entry = entry?;
            entry.unpack_in(dest.as_ref())?;
        }
        Ok(())
    }

    /// Extract files to a destination directory with plist-based permissions.
    ///
    /// This method extracts files and applies permissions specified in the
    /// packing list (`@mode`, `@owner`, `@group` directives).
    ///
    /// # Arguments
    ///
    /// * `dest` - Destination directory for extraction
    /// * `options` - Extraction options controlling mode/ownership application
    ///
    /// # Returns
    ///
    /// A vector of [`ExtractedFile`] describing each extracted file.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use pkgsrc::archive::{BinaryPackage, ExtractOptions};
    ///
    /// let pkg = BinaryPackage::open("package-1.0.tgz")?;
    /// let options = ExtractOptions::new().with_mode();
    /// let extracted = pkg.extract_with_plist("/usr/pkg", options)?;
    /// for file in &extracted {
    ///     println!("Extracted: {}", file.path.display());
    /// }
    /// # Ok::<(), pkgsrc::archive::ArchiveError>(())
    /// ```
    #[cfg(unix)]
    pub fn extract_with_plist(
        &self,
        dest: impl AsRef<Path>,
        options: ExtractOptions,
    ) -> Result<Vec<ExtractedFile>> {
        use crate::plist::FileInfo;
        use std::os::unix::ffi::OsStrExt;

        let dest = dest.as_ref();
        let mut extracted = Vec::new();

        // Build a map of file paths to their plist metadata
        let file_infos: HashMap<OsString, FileInfo> = self
            .plist
            .files_with_info()
            .into_iter()
            .map(|info| (info.path.clone(), info))
            .collect();

        let mut archive = self.archive()?;
        for entry_result in archive.entries()? {
            let mut entry = entry_result?;
            let entry_path = entry.path()?.into_owned();

            // Determine if this is a metadata file
            let is_metadata =
                entry_path.as_os_str().as_bytes().starts_with(b"+");

            // Extract the file
            entry.unpack_in(dest)?;

            let full_path = dest.join(&entry_path);

            // Look up plist metadata for this file
            let file_info = file_infos.get(entry_path.as_os_str());

            let mut applied_mode = None;

            // Apply mode from plist if requested
            if options.apply_mode && !is_metadata {
                if let Some(info) = file_info {
                    if let Some(mode_str) = &info.mode {
                        if let Some(mode) = parse_mode(mode_str) {
                            if full_path.exists() && !full_path.is_symlink() {
                                fs::set_permissions(
                                    &full_path,
                                    Permissions::from_mode(mode),
                                )?;
                                applied_mode = Some(mode);
                            }
                        }
                    }
                }
            }

            // Apply ownership from plist if requested
            // Note: This requires root privileges
            #[cfg(unix)]
            if options.apply_ownership && !is_metadata {
                if let Some(info) = file_info {
                    if info.owner.is_some() || info.group.is_some() {
                        // Ownership changes require the nix crate or libc
                        // For now, we just note it in the result but don't apply
                        // To implement: use nix::unistd::{chown, Uid, Gid}
                    }
                }
            }

            extracted.push(ExtractedFile {
                path: full_path,
                is_metadata,
                expected_checksum: file_info.and_then(|i| i.checksum.clone()),
                mode: applied_mode,
            });
        }

        Ok(extracted)
    }

    /// Verify checksums of extracted files against plist MD5 values.
    ///
    /// This method checks that files in the destination directory match
    /// the MD5 checksums recorded in the packing list.
    ///
    /// # Arguments
    ///
    /// * `dest` - Directory where files were extracted
    ///
    /// # Returns
    ///
    /// A vector of tuples containing (file_path, expected_hash, actual_hash)
    /// for files that failed verification. Empty vector means all passed.
    pub fn verify_checksums(
        &self,
        dest: impl AsRef<Path>,
    ) -> Result<Vec<(PathBuf, String, String)>> {
        use md5::{Digest, Md5};

        let dest = dest.as_ref();
        let mut failures = Vec::new();

        for info in self.plist.files_with_info() {
            // Skip files without checksums
            let Some(expected) = &info.checksum else {
                continue;
            };

            // Skip symlinks (they have Symlink: comments instead of MD5:)
            if info.symlink_target.is_some() {
                continue;
            }

            let file_path = dest.join(&info.path);

            if !file_path.exists() {
                failures.push((
                    file_path,
                    expected.clone(),
                    "FILE_NOT_FOUND".to_string(),
                ));
                continue;
            }

            // Compute MD5 of the file
            let mut file = File::open(&file_path)?;
            let mut hasher = Md5::new();
            io::copy(&mut file, &mut hasher)?;
            let result = hasher.finalize();
            let actual = format!("{:032x}", result);

            if actual != *expected {
                failures.push((file_path, expected.clone(), actual));
            }
        }

        Ok(failures)
    }

    /// Sign this package.
    ///
    /// Re-reads the package file to compute hashes and create a signed archive.
    pub fn sign(&self, signature: &[u8]) -> Result<SignedArchive> {
        let pkgname = self
            .pkgname()
            .ok_or_else(|| ArchiveError::MissingMetadata("pkgname".into()))?
            .to_string();

        // Read the tarball data
        let tarball = std::fs::read(&self.path)?;

        // Generate hash
        let pkg_hash = PkgHash::from_tarball(
            &pkgname,
            Cursor::new(&tarball),
            PkgHashAlgorithm::Sha512,
            DEFAULT_BLOCK_SIZE,
        )?;

        Ok(SignedArchive {
            pkgname,
            compression: self.compression,
            pkg_hash,
            signature: signature.to_vec(),
            tarball,
        })
    }

    /// Convert this package to a [`Summary`] entry.
    ///
    /// This uses default options (no file checksum computation).
    /// Use [`to_summary_with_opts`](Self::to_summary_with_opts) for more control.
    pub fn to_summary(&self) -> Result<Summary> {
        self.to_summary_with_opts(&SummaryOptions::default())
    }

    /// Convert this package to a [`Summary`] entry with options.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use pkgsrc::archive::{BinaryPackage, SummaryOptions};
    ///
    /// let pkg = BinaryPackage::open("package-1.0.tgz")?;
    /// let opts = SummaryOptions { compute_file_cksum: true };
    /// let summary = pkg.to_summary_with_opts(&opts)?;
    /// # Ok::<(), pkgsrc::archive::ArchiveError>(())
    /// ```
    pub fn to_summary_with_opts(
        &self,
        opts: &SummaryOptions,
    ) -> Result<Summary> {
        use sha2::{Digest, Sha256};

        let pkgname = self
            .plist
            .pkgname()
            .map(crate::PkgName::new)
            .ok_or_else(|| ArchiveError::MissingMetadata("PKGNAME".into()))?;

        // Helper to filter empty/whitespace-only strings
        let non_empty = |s: &&str| !s.trim().is_empty();

        // Helper to convert &str to String, avoiding redundant into() calls
        let to_string = |s: &str| String::from(s);

        // Compute SHA256 checksum of the package file if requested
        let file_cksum = if opts.compute_file_cksum && self.file_size > 0 {
            let mut file = File::open(&self.path)?;
            let mut hasher = Sha256::new();
            io::copy(&mut file, &mut hasher)?;
            let hash = hasher.finalize();
            const PREFIX: &str = "sha256 ";
            let mut s = String::with_capacity(PREFIX.len() + hash.len() * 2);
            s.push_str(PREFIX);
            for b in &hash {
                let _ = write!(s, "{b:02x}");
            }
            Some(s)
        } else {
            None
        };

        Ok(Summary::new(
            pkgname,
            self.metadata.comment().to_string(),
            self.metadata.size_pkg().unwrap_or(0),
            to_string(self.build_info_value("BUILD_DATE").unwrap_or("")),
            self.build_info_value("CATEGORIES")
                .unwrap_or("")
                .split_whitespace()
                .map(String::from)
                .collect(),
            to_string(self.build_info_value("MACHINE_ARCH").unwrap_or("")),
            to_string(self.build_info_value("OPSYS").unwrap_or("")),
            to_string(self.build_info_value("OS_VERSION").unwrap_or("")),
            to_string(self.build_info_value("PKGPATH").unwrap_or("")),
            to_string(self.build_info_value("PKGTOOLS_VERSION").unwrap_or("")),
            self.metadata.desc().lines().map(String::from).collect(),
            // Optional fields - avoid Vec<String> allocation when empty
            Some(self.plist.conflicts().map(String::from).collect::<Vec<_>>())
                .filter(|v| !v.is_empty()),
            Some(self.plist.depends().map(String::from).collect::<Vec<_>>())
                .filter(|v| !v.is_empty()),
            self.build_info_value("HOMEPAGE")
                .filter(non_empty)
                .map(to_string),
            self.build_info_value("LICENSE").map(to_string),
            self.build_info_value("PKG_OPTIONS").map(to_string),
            self.build_info_value("PREV_PKGPATH")
                .filter(non_empty)
                .map(to_string),
            self.build_info_values("PROVIDES").map(|v| v.to_vec()),
            self.build_info_values("REQUIRES").map(|v| v.to_vec()),
            self.build_info_values("SUPERSEDES").map(|v| v.to_vec()),
            self.path
                .file_name()
                .map(|f| f.to_string_lossy().into_owned()),
            if self.file_size > 0 {
                Some(self.file_size)
            } else {
                None
            },
            file_cksum,
        ))
    }
}

impl FileRead for BinaryPackage {
    fn pkgname(&self) -> &str {
        self.plist.pkgname().unwrap_or("")
    }

    fn comment(&self) -> std::io::Result<String> {
        Ok(self.metadata.comment().to_string())
    }

    fn contents(&self) -> std::io::Result<String> {
        Ok(self.metadata.contents().to_string())
    }

    fn desc(&self) -> std::io::Result<String> {
        Ok(self.metadata.desc().to_string())
    }

    fn build_info(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.build_info().map(|v| v.join("\n")))
    }

    fn build_version(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.build_version().map(|v| v.join("\n")))
    }

    fn deinstall(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.deinstall().map(|s| s.to_string()))
    }

    fn display(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.display().map(|s| s.to_string()))
    }

    fn install(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.install().map(|s| s.to_string()))
    }

    fn installed_info(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.installed_info().map(|v| v.join("\n")))
    }

    fn mtree_dirs(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.mtree_dirs().map(|v| v.join("\n")))
    }

    fn preserve(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.preserve().map(|v| v.join("\n")))
    }

    fn required_by(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.required_by().map(|v| v.join("\n")))
    }

    fn size_all(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.size_all().map(|n| n.to_string()))
    }

    fn size_pkg(&self) -> std::io::Result<Option<String>> {
        Ok(self.metadata.size_pkg().map(|n| n.to_string()))
    }
}

impl TryFrom<&BinaryPackage> for Summary {
    type Error = ArchiveError;

    fn try_from(pkg: &BinaryPackage) -> Result<Self> {
        pkg.to_summary()
    }
}

// ============================================================================
// Builder (low-level, tar-style)
// ============================================================================

/// Wrapper for different compression encoders.
enum Encoder<W: Write> {
    Gzip(GzEncoder<W>),
    Zstd(zstd::stream::Encoder<'static, W>),
}

impl<W: Write> Write for Encoder<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            Encoder::Gzip(e) => e.write(buf),
            Encoder::Zstd(e) => e.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self {
            Encoder::Gzip(e) => e.flush(),
            Encoder::Zstd(e) => e.flush(),
        }
    }
}

impl<W: Write> Encoder<W> {
    fn finish(self) -> io::Result<W> {
        match self {
            Encoder::Gzip(e) => e.finish(),
            Encoder::Zstd(e) => e.finish(),
        }
    }
}

/// Build a new compressed package archive.
///
/// This provides tar-style streaming construction of package archives.
/// Supports gzip and zstd compression.
///
/// # Example
///
/// ```no_run
/// use pkgsrc::archive::Builder;
///
/// // Create a package with auto-detected compression from filename
/// let mut builder = Builder::create("package-1.0.tgz")?;
///
/// // Add metadata files first
/// builder.append_metadata_file("+CONTENTS", b"@name package-1.0\n")?;
/// builder.append_metadata_file("+COMMENT", b"A test package")?;
/// builder.append_metadata_file("+DESC", b"Description here")?;
///
/// // Add package files
/// builder.append_file("bin/hello", b"#!/bin/sh\necho hello", 0o755)?;
///
/// builder.finish()?;
/// # Ok::<(), pkgsrc::archive::ArchiveError>(())
/// ```
pub struct Builder<W: Write> {
    inner: TarBuilder<Encoder<W>>,
    compression: Compression,
}

impl Builder<File> {
    /// Create a new archive file with compression auto-detected from extension.
    ///
    /// Supported extensions:
    /// - `.tgz`, `.tar.gz` → gzip
    /// - `.tzst`, `.tar.zst` → zstd
    ///
    /// Falls back to gzip for unrecognized extensions.
    pub fn create(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let compression =
            Compression::from_extension(path).unwrap_or(Compression::Gzip);
        let file = File::create(path)?;
        Self::with_compression(file, compression)
    }
}

impl<W: Write> Builder<W> {
    /// Create a new archive builder with gzip compression (default).
    ///
    /// Use [`Builder::with_compression`] for other formats, or
    /// [`Builder::create`] to auto-detect from a file path.
    pub fn new(writer: W) -> Result<Self> {
        Self::with_compression(writer, Compression::Gzip)
    }

    /// Create a new archive builder with explicit compression.
    pub fn with_compression(
        writer: W,
        compression: Compression,
    ) -> Result<Self> {
        let encoder = match compression {
            Compression::Gzip => Encoder::Gzip(GzEncoder::new(
                writer,
                flate2::Compression::default(),
            )),
            Compression::Zstd => Encoder::Zstd(zstd::stream::Encoder::new(
                writer,
                zstd::DEFAULT_COMPRESSION_LEVEL,
            )?),
            Compression::None => {
                return Err(ArchiveError::UnsupportedCompression(
                    "uncompressed archives not supported for building".into(),
                ));
            }
        };

        Ok(Self {
            inner: TarBuilder::new(encoder),
            compression,
        })
    }

    /// Return the compression format.
    #[must_use]
    pub fn compression(&self) -> Compression {
        self.compression
    }

    /// Append a metadata file (e.g., +CONTENTS, +COMMENT).
    pub fn append_metadata_file(
        &mut self,
        name: &str,
        content: &[u8],
    ) -> Result<()> {
        let mut header = Header::new_gnu();
        header.set_size(content.len() as u64);
        header.set_mode(0o644);
        header.set_mtime(0);
        header.set_cksum();

        self.inner.append_data(&mut header, name, content)?;
        Ok(())
    }

    /// Append a file with the given path, content, and mode.
    pub fn append_file(
        &mut self,
        path: impl AsRef<Path>,
        content: &[u8],
        mode: u32,
    ) -> Result<()> {
        let mut header = Header::new_gnu();
        header.set_size(content.len() as u64);
        header.set_mode(mode);
        header.set_mtime(0);
        header.set_cksum();

        self.inner.append_data(&mut header, path, content)?;
        Ok(())
    }

    /// Append a file from disk.
    pub fn append_path(&mut self, path: impl AsRef<Path>) -> Result<()> {
        self.inner.append_path(path)?;
        Ok(())
    }

    /// Finish building the archive and return the underlying writer.
    pub fn finish(self) -> Result<W> {
        let encoder = self.inner.into_inner()?;
        let writer = encoder.finish()?;
        Ok(writer)
    }
}

// ============================================================================
// SignedArchive
// ============================================================================

/// A signed binary package ready to be written.
///
/// This is created by [`BinaryPackage::sign`] or [`SignedArchive::from_unsigned`].
#[derive(Debug)]
pub struct SignedArchive {
    pkgname: String,
    compression: Compression,
    pkg_hash: PkgHash,
    signature: Vec<u8>,
    tarball: Vec<u8>,
}

impl SignedArchive {
    /// Create a signed archive from unsigned tarball bytes.
    ///
    /// This is useful for signing a freshly-built package without writing
    /// it to disk first.
    pub fn from_unsigned(
        data: Vec<u8>,
        pkgname: impl Into<String>,
        signature: &[u8],
        compression: Compression,
    ) -> Result<Self> {
        let pkgname = pkgname.into();
        let pkg_hash = PkgHash::from_tarball(
            &pkgname,
            Cursor::new(&data),
            PkgHashAlgorithm::Sha512,
            DEFAULT_BLOCK_SIZE,
        )?;

        Ok(Self {
            pkgname,
            compression,
            pkg_hash,
            signature: signature.to_vec(),
            tarball: data,
        })
    }

    /// Return the package name.
    #[must_use]
    pub fn pkgname(&self) -> &str {
        &self.pkgname
    }

    /// Return the compression format of the inner tarball.
    #[must_use]
    pub fn compression(&self) -> Compression {
        self.compression
    }

    /// Return the package hash.
    #[must_use]
    pub fn pkg_hash(&self) -> &PkgHash {
        &self.pkg_hash
    }

    /// Write the signed package to a file.
    pub fn write_to(&self, path: impl AsRef<Path>) -> Result<()> {
        let file = File::create(path)?;
        self.write(file)
    }

    /// Write the signed package to a writer.
    pub fn write<W: Write>(&self, writer: W) -> Result<()> {
        let mut ar = ar::Builder::new(writer);

        // Write +PKG_HASH
        let hash_content = self.pkg_hash.to_string();
        let hash_bytes = hash_content.as_bytes();
        let mut header =
            ar::Header::new(b"+PKG_HASH".to_vec(), hash_bytes.len() as u64);
        header.set_mode(0o644);
        ar.append(&header, hash_bytes)?;

        // Write +PKG_GPG_SIGNATURE
        let mut header = ar::Header::new(
            b"+PKG_GPG_SIGNATURE".to_vec(),
            self.signature.len() as u64,
        );
        header.set_mode(0o644);
        ar.append(&header, self.signature.as_slice())?;

        // Write tarball with appropriate extension
        let tarball_name =
            format!("{}.{}", self.pkgname, self.compression.extension());
        let mut header = ar::Header::new(
            tarball_name.into_bytes(),
            self.tarball.len() as u64,
        );
        header.set_mode(0o644);
        ar.append(&header, self.tarball.as_slice())?;

        Ok(())
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_compression_from_magic() {
        assert_eq!(
            Compression::from_magic(&[0x1f, 0x8b, 0, 0, 0, 0]),
            Some(Compression::Gzip)
        );
        assert_eq!(
            Compression::from_magic(&[0x28, 0xb5, 0x2f, 0xfd, 0, 0]),
            Some(Compression::Zstd)
        );
        assert_eq!(Compression::from_magic(&[0, 0, 0, 0, 0, 0]), None);
    }

    #[test]
    fn test_compression_from_extension() {
        assert_eq!(
            Compression::from_extension("foo.tgz"),
            Some(Compression::Gzip)
        );
        assert_eq!(
            Compression::from_extension("foo.tar.gz"),
            Some(Compression::Gzip)
        );
        assert_eq!(
            Compression::from_extension("foo.tzst"),
            Some(Compression::Zstd)
        );
        assert_eq!(
            Compression::from_extension("foo.tar.zst"),
            Some(Compression::Zstd)
        );
        assert_eq!(
            Compression::from_extension("foo.tar"),
            Some(Compression::None)
        );
    }

    #[test]
    fn test_hash_algorithm() {
        assert_eq!(
            "SHA512".parse::<PkgHashAlgorithm>().ok(),
            Some(PkgHashAlgorithm::Sha512)
        );
        assert_eq!(
            "sha256".parse::<PkgHashAlgorithm>().ok(),
            Some(PkgHashAlgorithm::Sha256)
        );
        assert!("MD5".parse::<PkgHashAlgorithm>().is_err());

        assert_eq!(PkgHashAlgorithm::Sha512.as_str(), "SHA512");
        assert_eq!(PkgHashAlgorithm::Sha256.as_str(), "SHA256");

        assert_eq!(PkgHashAlgorithm::Sha512.hash_size(), 64);
        assert_eq!(PkgHashAlgorithm::Sha256.hash_size(), 32);
    }

    #[test]
    fn test_pkg_hash_parse() -> Result<()> {
        let content = "\
pkgsrc signature
version: 1
pkgname: test-1.0
algorithm: SHA512
block size: 65536
file size: 12345
abc123
def456
";
        let pkg_hash: PkgHash = content.parse()?;

        assert_eq!(pkg_hash.version(), 1);
        assert_eq!(pkg_hash.pkgname(), "test-1.0");
        assert_eq!(pkg_hash.algorithm(), PkgHashAlgorithm::Sha512);
        assert_eq!(pkg_hash.block_size(), 65536);
        assert_eq!(pkg_hash.file_size(), 12345);
        assert_eq!(pkg_hash.hashes(), &["abc123", "def456"]);
        Ok(())
    }

    #[test]
    fn test_pkg_hash_generate() -> Result<()> {
        let data = b"Hello, World!";
        let pkg_hash = PkgHash::from_tarball(
            "test-1.0",
            Cursor::new(data),
            PkgHashAlgorithm::Sha512,
            1024,
        )?;

        assert_eq!(pkg_hash.pkgname(), "test-1.0");
        assert_eq!(pkg_hash.algorithm(), PkgHashAlgorithm::Sha512);
        assert_eq!(pkg_hash.block_size(), 1024);
        assert_eq!(pkg_hash.file_size(), 13);
        assert_eq!(pkg_hash.hashes().len(), 1);
        Ok(())
    }

    #[test]
    fn test_pkg_hash_verify() -> Result<()> {
        let data = b"Hello, World!";
        let pkg_hash = PkgHash::from_tarball(
            "test-1.0",
            Cursor::new(data),
            PkgHashAlgorithm::Sha512,
            1024,
        )?;

        assert!(pkg_hash.verify(Cursor::new(data))?);

        let bad_data = b"Goodbye, World!";
        assert!(pkg_hash.verify(Cursor::new(bad_data)).is_err());
        Ok(())
    }

    #[test]
    fn test_pkg_hash_roundtrip() -> Result<()> {
        let data = vec![0u8; 200_000];
        let pkg_hash = PkgHash::from_tarball(
            "test-1.0",
            Cursor::new(&data),
            PkgHashAlgorithm::Sha512,
            65536,
        )?;

        let serialized = pkg_hash.to_string();
        let parsed: PkgHash = serialized.parse()?;

        assert_eq!(pkg_hash.version(), parsed.version());
        assert_eq!(pkg_hash.pkgname(), parsed.pkgname());
        assert_eq!(pkg_hash.algorithm(), parsed.algorithm());
        assert_eq!(pkg_hash.block_size(), parsed.block_size());
        assert_eq!(pkg_hash.file_size(), parsed.file_size());
        assert_eq!(pkg_hash.hashes(), parsed.hashes());

        assert!(parsed.verify(Cursor::new(&data))?);
        Ok(())
    }

    #[test]
    fn test_build_package_gzip() -> Result<()> {
        // Use new() which defaults to gzip
        let mut builder = Builder::new(Vec::new())?;

        let plist = "@name testpkg-1.0\n@cwd /opt/test\nbin/test\n";
        builder.append_metadata_file("+CONTENTS", plist.as_bytes())?;
        builder.append_metadata_file("+COMMENT", b"A test package")?;
        builder.append_metadata_file(
            "+DESC",
            b"This is a test.\nMultiple lines.",
        )?;
        builder.append_metadata_file(
            "+BUILD_INFO",
            b"OPSYS=NetBSD\nMACHINE_ARCH=x86_64\n",
        )?;
        builder.append_file("bin/test", b"#!/bin/sh\necho test", 0o755)?;
        let output = builder.finish()?;

        assert!(!output.is_empty());

        // Verify we can read it back using low-level Archive (default gzip)
        let mut archive = Archive::new(Cursor::new(&output))?;
        let mut found_contents = false;
        for entry in archive.entries()? {
            let entry = entry?;
            if entry.path()?.to_str() == Some("+CONTENTS") {
                found_contents = true;
                break;
            }
        }
        assert!(found_contents);
        Ok(())
    }

    #[test]
    fn test_build_package_zstd() -> Result<()> {
        // Use with_compression for explicit zstd
        let mut builder =
            Builder::with_compression(Vec::new(), Compression::Zstd)?;

        let plist = "@name testpkg-1.0\n@cwd /opt/test\nbin/test\n";
        builder.append_metadata_file("+CONTENTS", plist.as_bytes())?;
        builder.append_metadata_file("+COMMENT", b"A test package")?;
        builder.append_metadata_file(
            "+DESC",
            b"This is a test.\nMultiple lines.",
        )?;
        builder.append_file("bin/test", b"#!/bin/sh\necho test", 0o755)?;
        let output = builder.finish()?;

        assert!(!output.is_empty());

        // Verify we can read it back using low-level Archive
        let mut archive =
            Archive::with_compression(Cursor::new(&output), Compression::Zstd)?;
        let mut found_contents = false;
        for entry in archive.entries()? {
            let entry = entry?;
            if entry.path()?.to_str() == Some("+CONTENTS") {
                found_contents = true;
                break;
            }
        }
        assert!(found_contents);
        Ok(())
    }

    #[test]
    fn test_signed_archive_from_unsigned() -> Result<()> {
        // Build an unsigned package (default gzip)
        let mut builder = Builder::new(Vec::new())?;
        builder.append_metadata_file("+CONTENTS", b"@name testpkg-1.0\n")?;
        builder.append_metadata_file("+COMMENT", b"A test package")?;
        builder.append_metadata_file("+DESC", b"Test description")?;
        let output = builder.finish()?;

        let fake_signature = b"FAKE GPG SIGNATURE";
        let signed = SignedArchive::from_unsigned(
            output,
            "testpkg-1.0",
            fake_signature,
            Compression::Gzip,
        )?;

        assert_eq!(signed.pkgname(), "testpkg-1.0");
        assert_eq!(signed.pkg_hash().algorithm(), PkgHashAlgorithm::Sha512);
        assert_eq!(signed.compression(), Compression::Gzip);

        // Write to buffer and verify it's an ar archive
        let mut signed_output = Vec::new();
        signed.write(&mut signed_output)?;
        assert!(&signed_output[..7] == b"!<arch>");
        Ok(())
    }

    #[test]
    fn test_signed_archive_zstd() -> Result<()> {
        // Build an unsigned zstd package
        let mut builder =
            Builder::with_compression(Vec::new(), Compression::Zstd)?;
        builder.append_metadata_file("+CONTENTS", b"@name testpkg-1.0\n")?;
        builder.append_metadata_file("+COMMENT", b"A test package")?;
        builder.append_metadata_file("+DESC", b"Test description")?;
        let output = builder.finish()?;

        let fake_signature = b"FAKE GPG SIGNATURE";
        let signed = SignedArchive::from_unsigned(
            output,
            "testpkg-1.0",
            fake_signature,
            Compression::Zstd,
        )?;

        assert_eq!(signed.pkgname(), "testpkg-1.0");
        assert_eq!(signed.compression(), Compression::Zstd);

        // Write to buffer and verify it's an ar archive
        let mut signed_output = Vec::new();
        signed.write(&mut signed_output)?;
        assert!(&signed_output[..7] == b"!<arch>");
        Ok(())
    }

    #[test]
    fn test_parse_mode() {
        // Standard octal formats
        assert_eq!(super::parse_mode("0755"), Some(0o755));
        assert_eq!(super::parse_mode("755"), Some(0o755));
        assert_eq!(super::parse_mode("0644"), Some(0o644));
        assert_eq!(super::parse_mode("644"), Some(0o644));
        assert_eq!(super::parse_mode("0777"), Some(0o777));
        assert_eq!(super::parse_mode("0400"), Some(0o400));

        // Invalid formats
        assert_eq!(super::parse_mode(""), None);
        assert_eq!(super::parse_mode("abc"), None);
        assert_eq!(super::parse_mode("999"), None); // 9 is not valid octal
    }

    #[test]
    fn test_extract_options() {
        let opts = ExtractOptions::new();
        assert!(!opts.apply_mode);
        assert!(!opts.apply_ownership);
        assert!(!opts.preserve_mtime);

        let opts = ExtractOptions::new().with_mode().with_ownership();
        assert!(opts.apply_mode);
        assert!(opts.apply_ownership);
        assert!(!opts.preserve_mtime);
    }
}