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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

/*! `Release` file primitives.

`Release` files (or `InRelease` if it contains a PGP cleartext signature) are
the main definition of a Debian repository. They are a control paragraph that
defines repository-level metadata as well as a list of additional *indices* files
that further define the content of the repository.

[ReleaseFile] represents a parsed `Release` or `InRelease` file. It exposes
accessor functions for obtaining well-known metadata fields. It also exposes
various functions for obtaining index file entries.

[ReleaseFileEntry] is the most generic type describing an *indices* file.
Additional types describe more strongly typed indices file variants:

* [ContentsFileEntry] (`Contents` files)
* [PackagesFileEntry] (`Packages` files)
* [SourcesFileEntry] (`Sources` files)

The [ClassifiedReleaseFileEntry] enum wraps all these types and attempts to
classify each entry as the strongest type possible.
*/

use {
    crate::{
        control::{ControlParagraph, ControlParagraphReader},
        error::{DebianError, Result},
        io::ContentDigest,
        repository::Compression,
    },
    chrono::{DateTime, Utc},
    pgp_cleartext::CleartextHasher,
    std::{
        borrow::Cow,
        io::BufRead,
        ops::{Deref, DerefMut},
        str::FromStr,
    },
};

/// Formatter string for dates in release files.
pub const DATE_FORMAT: &str = "%a, %d %b %Y %H:%M:%S %z";

/// Checksum type / digest mechanism used in a release file.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum ChecksumType {
    /// MD5.
    Md5,

    /// SHA-1.
    Sha1,

    /// SHA-256.
    Sha256,
}

impl ChecksumType {
    /// Emit variants in their preferred usage order.
    pub fn preferred_order() -> impl Iterator<Item = ChecksumType> {
        [Self::Sha256, Self::Sha1, Self::Md5].into_iter()
    }

    /// Name of the control field in `Release` files holding this variant type.
    pub fn field_name(&self) -> &'static str {
        match self {
            Self::Md5 => "MD5Sum",
            Self::Sha1 => "SHA1",
            Self::Sha256 => "SHA256",
        }
    }

    /// Obtain a new hasher for this checksum flavor.
    pub fn new_hasher(&self) -> Box<dyn pgp::crypto::Hasher + Send> {
        Box::new(match self {
            Self::Md5 => CleartextHasher::md5(),
            Self::Sha1 => CleartextHasher::sha1(),
            Self::Sha256 => CleartextHasher::sha256(),
        })
    }
}

/// An entry for a file in a parsed `Release` file.
///
/// Instances correspond to a line in a `MD5Sum`, `SHA1`, or `SHA256` field.
///
/// This is the most generic way to represent an indices file in a `Release` file.
///
/// Instances can be fallibly converted into more strongly typed release entries
/// via [TryFrom]/[TryInto]. Other entry types include [ContentsFileEntry],
/// [PackagesFileEntry], and [SourcesFileEntry].
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct ReleaseFileEntry<'a> {
    /// The path to this file within the repository.
    pub path: &'a str,

    /// The content digest of this file.
    pub digest: ContentDigest,

    /// The size of the file in bytes.
    pub size: u64,
}

impl<'a> ReleaseFileEntry<'a> {
    /// Obtain the `by-hash` path variant for this entry.
    pub fn by_hash_path(&self) -> String {
        if let Some((prefix, _)) = self.path.rsplit_once('/') {
            format!(
                "{}/by-hash/{}/{}",
                prefix,
                self.digest.release_field_name(),
                self.digest.digest_hex()
            )
        } else {
            format!(
                "by-hash/{}/{}",
                self.digest.release_field_name(),
                self.digest.digest_hex()
            )
        }
    }
}

/// A type of [ReleaseFileEntry] that describes an AppStream `Components` YAML file.
///
/// Files typically exist in paths named `<component>/dep11/Components-<architecture><compression>`.
#[derive(Clone, Debug, PartialEq)]
pub struct AppStreamComponentsEntry<'a> {
    /// The [ReleaseFileEntry] from which this instance was derived.
    entry: ReleaseFileEntry<'a>,
    /// The repository component name.
    pub component: Cow<'a, str>,
    /// The architecture name.
    pub architecture: Cow<'a, str>,
    /// File-level compression format.
    pub compression: Compression,
}

impl<'a> Deref for AppStreamComponentsEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for AppStreamComponentsEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

impl<'a> From<AppStreamComponentsEntry<'a>> for ReleaseFileEntry<'a> {
    fn from(v: AppStreamComponentsEntry<'a>) -> Self {
        v.entry
    }
}

impl<'a> TryFrom<ReleaseFileEntry<'a>> for AppStreamComponentsEntry<'a> {
    type Error = DebianError;

    fn try_from(entry: ReleaseFileEntry<'a>) -> std::result::Result<Self, Self::Error> {
        let parts = entry.path.split('/').collect::<Vec<_>>();

        let filename = *parts
            .last()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let suffix = filename
            .strip_prefix("Components-")
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let (architecture, remainder) = suffix
            .split_once('.')
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let compression = match remainder {
            "yml" => Compression::None,
            "yml.bz2" => Compression::Bzip2,
            "yml.gz" => Compression::Gzip,
            "yml.lzma" => Compression::Lzma,
            "yml.xz" => Compression::Xz,
            _ => {
                return Err(DebianError::ReleaseIndicesEntryWrongType);
            }
        };

        // The component is the part up until the `/dep11/Components-` pattern.
        let component_end = entry
            .path
            .find("/dep11/Components-")
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;
        let component = &entry.path[0..component_end];

        Ok(Self {
            entry,
            component: component.into(),
            architecture: architecture.into(),
            compression,
        })
    }
}

/// A type of [ReleaseFileEntry] that describes an AppStream `icons` archive.
///
/// Files typically exist in paths named `<component>/dep11/icons-<size><compression>`.
#[derive(Clone, Debug, PartialEq)]
pub struct AppStreamIconsFileEntry<'a> {
    /// The [ReleaseFileEntry] from which this instance was derived.
    entry: ReleaseFileEntry<'a>,
    /// The repository component name.
    pub component: Cow<'a, str>,
    /// The pixel resolution of the icons. e.g. `128x128`.
    pub resolution: Cow<'a, str>,
    /// File-level compression format.s
    pub compression: Compression,
}

impl<'a> Deref for AppStreamIconsFileEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for AppStreamIconsFileEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

impl<'a> From<AppStreamIconsFileEntry<'a>> for ReleaseFileEntry<'a> {
    fn from(v: AppStreamIconsFileEntry<'a>) -> Self {
        v.entry
    }
}

impl<'a> TryFrom<ReleaseFileEntry<'a>> for AppStreamIconsFileEntry<'a> {
    type Error = DebianError;

    fn try_from(entry: ReleaseFileEntry<'a>) -> std::result::Result<Self, Self::Error> {
        let parts = entry.path.split('/').collect::<Vec<_>>();

        let filename = *parts
            .last()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let suffix = filename
            .strip_prefix("icons-")
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let (resolution, remainder) = suffix
            .split_once('.')
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let compression = match remainder {
            "tar" => Compression::None,
            "tar.bz2" => Compression::Bzip2,
            "tar.gz" => Compression::Gzip,
            "tar.lzma" => Compression::Lzma,
            "tar.xz" => Compression::Xz,
            _ => {
                return Err(DebianError::ReleaseIndicesEntryWrongType);
            }
        };

        // The component is the part up until the `/dep11/icons-` pattern.
        let component_end = entry
            .path
            .find("/dep11/icons-")
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;
        let component = &entry.path[0..component_end];

        Ok(Self {
            entry,
            component: component.into(),
            resolution: resolution.into(),
            compression,
        })
    }
}

/// A type of [ReleaseFileEntry] that describes a `Contents` file.
///
/// This represents a pre-parsed wrapper around a [ReleaseFileEntry].
#[derive(Clone, Debug, PartialEq)]
pub struct ContentsFileEntry<'a> {
    /// The [ReleaseFileEntry] from which this instance was derived.
    entry: ReleaseFileEntry<'a>,

    /// The parsed component name (from the entry's path).
    pub component: Cow<'a, str>,

    /// The parsed architecture name (from the entry's path).
    pub architecture: Cow<'a, str>,

    /// File-level compression format being used.
    pub compression: Compression,

    /// Whether this refers to udeb packages used by installers.
    pub is_installer: bool,
}

impl<'a> Deref for ContentsFileEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for ContentsFileEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

impl<'a> From<ContentsFileEntry<'a>> for ReleaseFileEntry<'a> {
    fn from(v: ContentsFileEntry<'a>) -> Self {
        v.entry
    }
}

impl<'a> TryFrom<ReleaseFileEntry<'a>> for ContentsFileEntry<'a> {
    type Error = DebianError;

    fn try_from(entry: ReleaseFileEntry<'a>) -> std::result::Result<Self, Self::Error> {
        let parts = entry.path.split('/').collect::<Vec<_>>();

        let filename = *parts
            .last()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let suffix = filename
            .strip_prefix("Contents-")
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let (architecture, compression) = if let Some(v) = suffix.strip_suffix(".gz") {
            (v, Compression::Gzip)
        } else {
            (suffix, Compression::None)
        };

        let (architecture, is_installer) = if let Some(v) = architecture.strip_prefix("udeb-") {
            (v, true)
        } else {
            (architecture, false)
        };

        // The component is the part up until the `/Contents*` final path component.
        let component = &entry.path[..entry.path.len() - filename.len() - 1];

        Ok(Self {
            entry,
            component: component.into(),
            architecture: architecture.into(),
            compression,
            is_installer,
        })
    }
}

/// A special type of [ReleaseFileEntry] that describes a `Packages` file.
#[derive(Clone, Debug, PartialEq)]
pub struct PackagesFileEntry<'a> {
    /// The [ReleaseFileEntry] from which this instance was derived.
    entry: ReleaseFileEntry<'a>,

    /// The parsed component name (from the entry's path).
    pub component: Cow<'a, str>,

    /// The parsed architecture name (from the entry's path).
    pub architecture: Cow<'a, str>,

    /// File-level compression format being used.
    pub compression: Compression,

    /// Whether this refers to udeb packages used by installers.
    pub is_installer: bool,
}

impl<'a> Deref for PackagesFileEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for PackagesFileEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

impl<'a> From<PackagesFileEntry<'a>> for ReleaseFileEntry<'a> {
    fn from(v: PackagesFileEntry<'a>) -> Self {
        v.entry
    }
}

impl<'a> TryFrom<ReleaseFileEntry<'a>> for PackagesFileEntry<'a> {
    type Error = DebianError;

    fn try_from(entry: ReleaseFileEntry<'a>) -> std::result::Result<Self, Self::Error> {
        let parts = entry.path.split('/').collect::<Vec<_>>();

        let compression = match *parts
            .last()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?
        {
            "Packages" => Compression::None,
            "Packages.xz" => Compression::Xz,
            "Packages.gz" => Compression::Gzip,
            "Packages.bz2" => Compression::Bzip2,
            "Packages.lzma" => Compression::Lzma,
            _ => {
                return Err(DebianError::ReleaseIndicesEntryWrongType);
            }
        };

        // The component and architecture are the directory components before the
        // filename. The architecture is limited to a single directory component but
        // the component can have multiple directories.

        let architecture_component = *parts
            .iter()
            .rev()
            .nth(1)
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let search = &entry.path[..entry.path.len()
            - parts
                .last()
                .ok_or(DebianError::ReleaseIndicesEntryWrongType)?
                .len()
            - 1];
        let component = &search[0..search
            .rfind('/')
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?];

        // The architecture part is prefixed with `binary-`.
        let architecture = architecture_component
            .strip_prefix("binary-")
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        // udeps have a `debian-installer` path component following the component.
        let (component, is_udeb) =
            if let Some(component) = component.strip_suffix("/debian-installer") {
                (component, true)
            } else {
                (component, false)
            };

        Ok(Self {
            entry,
            component: component.into(),
            architecture: architecture.into(),
            compression,
            is_installer: is_udeb,
        })
    }
}

/// A type of [ReleaseFileEntry] that describes a nested `Release` file.
///
/// These often appear next to `Packages` or `Sources` files and contain a control paragraph
/// to describe the defined component.
#[derive(Clone, Debug, PartialEq)]
pub struct ReleaseReleaseFileEntry<'a> {
    entry: ReleaseFileEntry<'a>,
}

impl<'a> Deref for ReleaseReleaseFileEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for ReleaseReleaseFileEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

impl<'a> From<ReleaseReleaseFileEntry<'a>> for ReleaseFileEntry<'a> {
    fn from(v: ReleaseReleaseFileEntry<'a>) -> Self {
        v.entry
    }
}

impl<'a> TryFrom<ReleaseFileEntry<'a>> for ReleaseReleaseFileEntry<'a> {
    type Error = DebianError;

    fn try_from(entry: ReleaseFileEntry<'a>) -> std::result::Result<Self, Self::Error> {
        let parts = entry.path.split('/').collect::<Vec<_>>();

        if *parts
            .last()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?
            != "Release"
        {
            return Err(DebianError::ReleaseIndicesEntryWrongType);
        }

        Ok(Self { entry })
    }
}

/// A type of [ReleaseFileEntry] that describes a `Sources` file.
#[derive(Clone, Debug, PartialEq)]
pub struct SourcesFileEntry<'a> {
    entry: ReleaseFileEntry<'a>,
    /// The component the sources belong to.
    pub component: Cow<'a, str>,
    /// The compression format of the sources index.
    pub compression: Compression,
}

impl<'a> Deref for SourcesFileEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for SourcesFileEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

impl<'a> From<SourcesFileEntry<'a>> for ReleaseFileEntry<'a> {
    fn from(v: SourcesFileEntry<'a>) -> Self {
        v.entry
    }
}

impl<'a> TryFrom<ReleaseFileEntry<'a>> for SourcesFileEntry<'a> {
    type Error = DebianError;

    fn try_from(entry: ReleaseFileEntry<'a>) -> std::result::Result<Self, Self::Error> {
        let parts = entry.path.split('/').collect::<Vec<_>>();

        let compression = match *parts
            .last()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?
        {
            "Sources" => Compression::None,
            "Sources.gz" => Compression::Gzip,
            "Sources.xz" => Compression::Xz,
            "Sources.bz2" => Compression::Bzip2,
            "Sources.lzma" => Compression::Lzma,
            _ => {
                return Err(DebianError::ReleaseIndicesEntryWrongType);
            }
        };

        let component = *parts
            .first()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        Ok(Self {
            entry,
            component: component.into(),
            compression,
        })
    }
}

/// A special type of [ReleaseFileEntry] that describes a `Translations` file.
///
/// These typically exist under paths named `<component>/i18n/Translation-<locale><compression>`.
#[derive(Clone, Debug, PartialEq)]
pub struct TranslationFileEntry<'a> {
    /// The [ReleaseFileEntry] from which this instance was derived.
    entry: ReleaseFileEntry<'a>,

    /// The parsed component name (from the entry's path).
    pub component: Cow<'a, str>,

    /// The locale the translation is for.
    pub locale: Cow<'a, str>,

    /// File-level compression format being used.
    pub compression: Compression,
}

impl<'a> Deref for TranslationFileEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for TranslationFileEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

impl<'a> From<TranslationFileEntry<'a>> for ReleaseFileEntry<'a> {
    fn from(v: TranslationFileEntry<'a>) -> Self {
        v.entry
    }
}

impl<'a> TryFrom<ReleaseFileEntry<'a>> for TranslationFileEntry<'a> {
    type Error = DebianError;

    fn try_from(entry: ReleaseFileEntry<'a>) -> std::result::Result<Self, Self::Error> {
        // The component is the part up to `/i18n/Translation-`.
        let component_end = entry
            .path
            .find("/i18n/Translation-")
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;
        let component = &entry.path[0..component_end];

        let parts = entry.path.split('/').collect::<Vec<_>>();

        let filename = parts
            .last()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let remainder = filename
            .strip_prefix("Translation-")
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let (locale, compression) = if let Some((locale, extension)) = remainder.split_once('.') {
            let compression = match extension {
                "gz" => Compression::Gzip,
                "bz2" => Compression::Bzip2,
                "lzma" => Compression::Lzma,
                "xz" => Compression::Xz,
                _ => {
                    return Err(DebianError::ReleaseIndicesEntryWrongType);
                }
            };

            (locale, compression)
        } else {
            (remainder, Compression::None)
        };

        Ok(Self {
            entry,
            component: component.into(),
            locale: locale.into(),
            compression,
        })
    }
}

/// A type of [ReleaseFileEntry] that describes a manifest of files with content digests.
///
/// This represents `MD5SUMS` and `SHA256SUMS` files which hold an additional list of files
/// and their content manifests.
#[derive(Clone, Debug, PartialEq)]
pub struct FileManifestEntry<'a> {
    /// The [ReleaseFileEntry] from which this instance was derived.
    entry: ReleaseFileEntry<'a>,

    /// The digest format stored in this file.
    pub checksum: ChecksumType,

    /// The root path for files in this manifest.
    pub root_path: Cow<'a, str>,
}

impl<'a> Deref for FileManifestEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for FileManifestEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

impl<'a> From<FileManifestEntry<'a>> for ReleaseFileEntry<'a> {
    fn from(v: FileManifestEntry<'a>) -> Self {
        v.entry
    }
}

impl<'a> TryFrom<ReleaseFileEntry<'a>> for FileManifestEntry<'a> {
    type Error = DebianError;

    fn try_from(entry: ReleaseFileEntry<'a>) -> std::result::Result<Self, Self::Error> {
        let parts = entry.path.split('/').collect::<Vec<_>>();

        let filename = *parts
            .last()
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?;

        let checksum = match filename {
            "MD5SUMS" => ChecksumType::Md5,
            "SHA256SUMS" => ChecksumType::Sha256,
            _ => {
                return Err(DebianError::ReleaseIndicesEntryWrongType);
            }
        };

        let root_path = entry
            .path
            .rsplit_once('/')
            .ok_or(DebianError::ReleaseIndicesEntryWrongType)?
            .0;

        Ok(Self {
            entry,
            checksum,
            root_path: root_path.into(),
        })
    }
}

/// A `[In]Release` file entry cast to its stronger type, if possible.
#[derive(Debug)]
pub enum ClassifiedReleaseFileEntry<'a> {
    /// A `Contents` file.
    Contents(ContentsFileEntry<'a>),
    /// A `Packages` file.
    Packages(PackagesFileEntry<'a>),
    /// A `Sources` file.
    Sources(SourcesFileEntry<'a>),
    /// A nested `Release` file.
    Release(ReleaseReleaseFileEntry<'a>),
    /// An AppStream `Components` YAML file.
    AppStreamComponents(AppStreamComponentsEntry<'a>),
    /// An AppStream `Icons` file.
    AppStreamIcons(AppStreamIconsFileEntry<'a>),
    /// A `Translation` file.
    Translation(TranslationFileEntry<'a>),
    /// A `*SUMS` file containing content digests of additional files.
    FileManifest(FileManifestEntry<'a>),
    /// Some other file type.
    Other(ReleaseFileEntry<'a>),
}

impl<'a> Deref for ClassifiedReleaseFileEntry<'a> {
    type Target = ReleaseFileEntry<'a>;

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Contents(v) => &v.entry,
            Self::Packages(v) => &v.entry,
            Self::Sources(v) => &v.entry,
            Self::Release(v) => &v.entry,
            Self::AppStreamComponents(v) => &v.entry,
            Self::AppStreamIcons(v) => &v.entry,
            Self::Translation(v) => &v.entry,
            Self::FileManifest(v) => &v.entry,
            Self::Other(v) => v,
        }
    }
}

impl<'a> DerefMut for ClassifiedReleaseFileEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self {
            Self::Contents(v) => &mut v.entry,
            Self::Packages(v) => &mut v.entry,
            Self::Sources(v) => &mut v.entry,
            Self::Release(v) => &mut v.entry,
            Self::AppStreamComponents(v) => &mut v.entry,
            Self::AppStreamIcons(v) => &mut v.entry,
            Self::Translation(v) => &mut v.entry,
            Self::FileManifest(v) => &mut v.entry,
            Self::Other(v) => v,
        }
    }
}

/// A Debian repository `Release` file.
///
/// Release files contain metadata and list the index files for a *repository*.
/// They are effectively the entrypoint for defining a Debian repository and its
/// content.
///
/// Instances are wrappers around a [ControlParagraph]. [Deref] and [DerefMut] are
/// implemented to allow obtaining the inner [ControlParagraph]. [From] and [Into]
/// are implemented to allow cheap type coercions. Note that converting from
/// [ReleaseFile] to [ControlParagraph] may discard PGP cleartext signature data.
pub struct ReleaseFile<'a> {
    paragraph: ControlParagraph<'a>,

    /// Parsed PGP signatures for this file.
    signatures: Option<pgp_cleartext::CleartextSignatures>,
}

impl<'a> From<ControlParagraph<'a>> for ReleaseFile<'a> {
    fn from(paragraph: ControlParagraph<'a>) -> Self {
        Self {
            paragraph,
            signatures: None,
        }
    }
}

impl<'a> From<ReleaseFile<'a>> for ControlParagraph<'a> {
    fn from(release: ReleaseFile<'a>) -> Self {
        release.paragraph
    }
}

impl<'a> Deref for ReleaseFile<'a> {
    type Target = ControlParagraph<'a>;

    fn deref(&self) -> &Self::Target {
        &self.paragraph
    }
}

impl<'a> DerefMut for ReleaseFile<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.paragraph
    }
}

impl<'a> ReleaseFile<'a> {
    /// Construct an instance by reading data from a reader.
    ///
    /// The source must be a Debian control file with exactly 1 paragraph.
    ///
    /// The source must not be PGP armored. i.e. do not feed it raw `InRelease`
    /// files that begin with `-----BEGIN PGP SIGNED MESSAGE-----`.
    pub fn from_reader<R: BufRead>(reader: R) -> Result<Self> {
        let paragraphs = ControlParagraphReader::new(reader).collect::<Result<Vec<_>>>()?;

        // A Release control file should have a single paragraph.
        if paragraphs.len() != 1 {
            return Err(DebianError::ReleaseControlParagraphMismatch(
                paragraphs.len(),
            ));
        }

        let paragraph = paragraphs
            .into_iter()
            .next()
            .expect("validated paragraph count above");

        Ok(Self {
            paragraph,
            signatures: None,
        })
    }

    /// Construct an instance by reading data from a reader containing a PGP cleartext signature.
    ///
    /// This can be used to parse content from an `InRelease` file, which begins
    /// with `-----BEGIN PGP SIGNED MESSAGE-----`.
    ///
    /// An error occurs if the PGP cleartext file is not well-formed or if a PGP parsing
    /// error occurs.
    ///
    /// The PGP signature is NOT validated. The file will be parsed despite lack of
    /// signature verification. This is conceptually insecure. But since Rust has memory
    /// safety, some risk is prevented.
    pub fn from_armored_reader<R: BufRead>(reader: R) -> Result<Self> {
        let reader = pgp_cleartext::CleartextSignatureReader::new(reader);
        let mut reader = std::io::BufReader::new(reader);

        let mut slf = Self::from_reader(&mut reader)?;
        slf.signatures = Some(reader.into_inner().finalize());

        Ok(slf)
    }

    /// Obtain PGP signatures from this `InRelease` file.
    pub fn signatures(&self) -> Option<&pgp_cleartext::CleartextSignatures> {
        self.signatures.as_ref()
    }

    /// Description of this repository.
    pub fn description(&self) -> Option<&str> {
        self.field_str("Description")
    }

    /// Origin of the repository.
    pub fn origin(&self) -> Option<&str> {
        self.field_str("Origin")
    }

    /// Label for the repository.
    pub fn label(&self) -> Option<&str> {
        self.field_str("Label")
    }

    /// Version of this repository.
    ///
    /// Typically a sequence of `.` delimited integers.
    pub fn version(&self) -> Option<&str> {
        self.field_str("Version")
    }

    /// Suite of this repository.
    ///
    /// e.g. `stable`, `unstable`, `experimental`.
    pub fn suite(&self) -> Option<&str> {
        self.field_str("Suite")
    }

    /// Codename of this repository.
    pub fn codename(&self) -> Option<&str> {
        self.field_str("Codename")
    }

    /// Names of components within this repository.
    ///
    /// These are areas within the repository. Values may contain path characters.
    /// e.g. `main`, `updates/main`.
    pub fn components(&self) -> Option<Box<(dyn Iterator<Item = &str> + '_)>> {
        self.iter_field_words("Components")
    }

    /// Debian machine architectures supported by this repository.
    ///
    /// e.g. `all`, `amd64`, `arm64`.
    pub fn architectures(&self) -> Option<Box<(dyn Iterator<Item = &str> + '_)>> {
        self.iter_field_words("Architectures")
    }

    /// Time the release file was created, as its raw string value.
    pub fn date_str(&self) -> Option<&str> {
        self.field_str("Date")
    }

    /// Time the release file was created, as a [DateTime].
    ///
    /// The timezone from the original file is always normalized to UTC.
    pub fn date(&self) -> Option<Result<DateTime<Utc>>> {
        self.field_datetime_rfc5322("Date")
    }

    /// Time the release file should be considered expired by the client, as its raw string value.
    pub fn valid_until_str(&self) -> Option<&str> {
        self.field_str("Valid-Until")
    }

    /// Time the release file should be considered expired by the client.
    pub fn valid_until(&self) -> Option<Result<DateTime<Utc>>> {
        self.field_datetime_rfc5322("Valid-Until")
    }

    /// Evaluated value for `NotAutomatic` field.
    ///
    /// `true` is returned iff the value is `yes`. `no` and other values result in `false`.
    pub fn not_automatic(&self) -> Option<bool> {
        self.field_bool("NotAutomatic")
    }

    /// Evaluated value for `ButAutomaticUpgrades` field.
    ///
    /// `true` is returned iff the value is `yes`. `no` and other values result in `false`.
    pub fn but_automatic_upgrades(&self) -> Option<bool> {
        self.field_bool("ButAutomaticUpgrades")
    }

    /// Whether to acquire files by hash.
    pub fn acquire_by_hash(&self) -> Option<bool> {
        self.field_bool("Acquire-By-Hash")
    }

    /// Obtain indexed files in this repository.
    ///
    /// Files are grouped by their checksum variant.
    ///
    /// If the specified checksum variant is present, [Some] is returned.
    ///
    /// The returned iterator emits [ReleaseFileEntry] instances. Entries are lazily
    /// parsed as they are consumed from the iterator. Parse errors result in an [Err].
    pub fn iter_index_files(
        &self,
        checksum: ChecksumType,
    ) -> Option<Box<(dyn Iterator<Item = Result<ReleaseFileEntry<'_>>> + '_)>> {
        if let Some(iter) = self.iter_field_lines(checksum.field_name()) {
            Some(Box::new(iter.map(move |v| {
                // Values are of form: <digest> <size> <path>

                let mut parts = v.split_ascii_whitespace();

                let digest = parts.next().ok_or(DebianError::ReleaseMissingDigest)?;
                let size = parts.next().ok_or(DebianError::ReleaseMissingSize)?;
                let path = parts.next().ok_or(DebianError::ReleaseMissingPath)?;

                // Are paths with spaces allowed?
                if parts.next().is_some() {
                    return Err(DebianError::ReleasePathWithSpaces(v.to_string()));
                }

                let digest = ContentDigest::from_hex_digest(checksum, digest)?;
                let size = u64::from_str(size)?;

                Ok(ReleaseFileEntry { path, digest, size })
            })))
        } else {
            None
        }
    }

    /// Obtain indexed files in this repository classified to their type.
    ///
    /// This is like [Self::iter_index_files()] except it attempts classify each [ReleaseFileEntry]
    /// into a well-defined file type, returning a [ClassifiedReleaseFileEntry].
    ///
    /// If an entry doesn't map to a more well-defined type, [ClassifiedReleaseFileEntry::Other]
    /// will be emitted. If an error occurs when coercing an entry to its stronger type,
    /// [Err] will be emitted instead of [ClassifiedReleaseFileEntry::Other].
    pub fn iter_classified_index_files(
        &self,
        checksum: ChecksumType,
    ) -> Option<Box<(dyn Iterator<Item = Result<ClassifiedReleaseFileEntry<'_>>> + '_)>> {
        if let Some(iter) = self.iter_index_files(checksum) {
            Some(Box::new(iter.map(|entry| match entry {
                Ok(entry) => {
                    // This isn't the most efficient implementation or even the most semantically
                    // correct way to do it. But it should get the job done.

                    match ContentsFileEntry::try_from(entry.clone()) {
                        Ok(contents) => {
                            return Ok(ClassifiedReleaseFileEntry::Contents(contents));
                        }
                        Err(DebianError::ReleaseIndicesEntryWrongType) => {}
                        Err(e) => {
                            return Err(e);
                        }
                    }

                    match FileManifestEntry::try_from(entry.clone()) {
                        Ok(entry) => {
                            return Ok(ClassifiedReleaseFileEntry::FileManifest(entry));
                        }
                        Err(DebianError::ReleaseIndicesEntryWrongType) => {}
                        Err(e) => {
                            return Err(e);
                        }
                    }

                    match PackagesFileEntry::try_from(entry.clone()) {
                        Ok(packages) => {
                            return Ok(ClassifiedReleaseFileEntry::Packages(packages));
                        }
                        Err(DebianError::ReleaseIndicesEntryWrongType) => {}
                        Err(e) => {
                            return Err(e);
                        }
                    }

                    match ReleaseReleaseFileEntry::try_from(entry.clone()) {
                        Ok(release) => {
                            return Ok(ClassifiedReleaseFileEntry::Release(release));
                        }
                        Err(DebianError::ReleaseIndicesEntryWrongType) => {}
                        Err(e) => {
                            return Err(e);
                        }
                    }

                    match AppStreamComponentsEntry::try_from(entry.clone()) {
                        Ok(components) => {
                            return Ok(ClassifiedReleaseFileEntry::AppStreamComponents(components));
                        }
                        Err(DebianError::ReleaseIndicesEntryWrongType) => {}
                        Err(e) => {
                            return Err(e);
                        }
                    }

                    match AppStreamIconsFileEntry::try_from(entry.clone()) {
                        Ok(icons) => {
                            return Ok(ClassifiedReleaseFileEntry::AppStreamIcons(icons));
                        }
                        Err(DebianError::ReleaseIndicesEntryWrongType) => {}
                        Err(e) => {
                            return Err(e);
                        }
                    }

                    match TranslationFileEntry::try_from(entry.clone()) {
                        Ok(entry) => {
                            return Ok(ClassifiedReleaseFileEntry::Translation(entry));
                        }
                        Err(DebianError::ReleaseIndicesEntryWrongType) => {}
                        Err(e) => {
                            return Err(e);
                        }
                    }

                    match SourcesFileEntry::try_from(entry.clone()) {
                        Ok(sources) => {
                            return Ok(ClassifiedReleaseFileEntry::Sources(sources));
                        }
                        Err(DebianError::ReleaseIndicesEntryWrongType) => {}
                        Err(e) => {
                            return Err(e);
                        }
                    }

                    Ok(ClassifiedReleaseFileEntry::Other(entry))
                }
                Err(e) => Err(e),
            })))
        } else {
            None
        }
    }

    /// Obtain `Contents` indices entries given a checksum flavor.
    ///
    /// This essentially looks for `Contents*` files in the file lists.
    ///
    /// The emitted entries have component and architecture values derived by the
    /// file paths. These values are not checked against the list of components
    /// and architectures defined by this file.
    pub fn iter_contents_indices(
        &self,
        checksum: ChecksumType,
    ) -> Option<Box<(dyn Iterator<Item = Result<ContentsFileEntry<'_>>> + '_)>> {
        if let Some(iter) = self.iter_index_files(checksum) {
            Some(Box::new(iter.filter_map(|entry| match entry {
                Ok(entry) => match ContentsFileEntry::try_from(entry) {
                    Ok(v) => Some(Ok(v)),
                    Err(DebianError::ReleaseIndicesEntryWrongType) => None,
                    Err(e) => Some(Err(e)),
                },
                Err(e) => Some(Err(e)),
            })))
        } else {
            None
        }
    }

    /// Obtain `Packages` indices entries given a checksum flavor.
    ///
    /// This essentially looks for `Packages*` files in the file lists.
    ///
    /// The emitted entries have component and architecture values derived by the
    /// file paths. These values are not checked against the list of components
    /// and architectures defined by this file.
    pub fn iter_packages_indices(
        &self,
        checksum: ChecksumType,
    ) -> Option<Box<(dyn Iterator<Item = Result<PackagesFileEntry<'_>>> + '_)>> {
        if let Some(iter) = self.iter_index_files(checksum) {
            Some(Box::new(iter.filter_map(|entry| match entry {
                Ok(entry) => match PackagesFileEntry::try_from(entry) {
                    Ok(v) => Some(Ok(v)),
                    Err(DebianError::ReleaseIndicesEntryWrongType) => None,
                    Err(e) => Some(Err(e)),
                },
                Err(e) => Some(Err(e)),
            })))
        } else {
            None
        }
    }

    /// Find a [PackagesFileEntry] given search constraints.
    pub fn find_packages_indices(
        &self,
        checksum: ChecksumType,
        compression: Compression,
        component: &str,
        arch: &str,
        is_installer: bool,
    ) -> Option<PackagesFileEntry<'_>> {
        if let Some(mut iter) = self.iter_packages_indices(checksum) {
            iter.find_map(|entry| {
                if let Ok(entry) = entry {
                    if entry.component == component
                        && entry.architecture == arch
                        && entry.is_installer == is_installer
                        && entry.compression == compression
                    {
                        Some(entry)
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
        } else {
            None
        }
    }

    /// Obtain `Sources` indices entries given a checksum flavor.
    ///
    /// This essentially looks for `Sources*` files in the file lists.
    pub fn iter_sources_indices(
        &self,
        checksum: ChecksumType,
    ) -> Option<Box<(dyn Iterator<Item = Result<SourcesFileEntry<'_>>> + '_)>> {
        if let Some(iter) = self.iter_index_files(checksum) {
            Some(Box::new(iter.filter_map(|entry| match entry {
                Ok(entry) => match SourcesFileEntry::try_from(entry) {
                    Ok(v) => Some(Ok(v)),
                    Err(DebianError::ReleaseIndicesEntryWrongType) => None,
                    Err(e) => Some(Err(e)),
                },
                Err(e) => Some(Err(e)),
            })))
        } else {
            None
        }
    }

    /// Find a [SourcesFileEntry] given search constraints.
    pub fn find_sources_indices(
        &self,
        checksum: ChecksumType,
        compression: Compression,
        component: &str,
    ) -> Option<SourcesFileEntry<'_>> {
        if let Some(mut iter) = self.iter_sources_indices(checksum) {
            iter.find_map(|entry| {
                if let Ok(entry) = entry {
                    if entry.component == component && entry.compression == compression {
                        Some(entry)
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
        } else {
            None
        }
    }
}

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

    #[test]
    fn parse_bullseye_release() -> Result<()> {
        let mut reader =
            std::io::Cursor::new(include_bytes!("../testdata/release-debian-bullseye"));

        let release = ReleaseFile::from_reader(&mut reader)?;

        assert_eq!(
            release.description(),
            Some("Debian 11.1 Released 09 October 2021")
        );
        assert_eq!(release.origin(), Some("Debian"));
        assert_eq!(release.label(), Some("Debian"));
        assert_eq!(release.version(), Some("11.1"));
        assert_eq!(release.suite(), Some("stable"));
        assert_eq!(release.codename(), Some("bullseye"));
        assert_eq!(
            release.components().unwrap().collect::<Vec<_>>(),
            vec!["main", "contrib", "non-free"]
        );
        assert_eq!(
            release.architectures().unwrap().collect::<Vec<_>>(),
            vec![
                "all", "amd64", "arm64", "armel", "armhf", "i386", "mips64el", "mipsel", "ppc64el",
                "s390x"
            ]
        );
        assert_eq!(release.date_str(), Some("Sat, 09 Oct 2021 09:34:56 UTC"));
        assert_eq!(
            release.date().unwrap()?,
            DateTime::<Utc>::from_utc(
                chrono::NaiveDateTime::new(
                    chrono::NaiveDate::from_ymd(2021, 10, 9),
                    chrono::NaiveTime::from_hms(9, 34, 56)
                ),
                Utc
            )
        );

        assert!(release.valid_until_str().is_none());

        let entries = release
            .iter_index_files(ChecksumType::Md5)
            .unwrap()
            .collect::<Result<Vec<_>>>()?;
        assert_eq!(entries.len(), 600);
        assert_eq!(
            entries[0],
            ReleaseFileEntry {
                path: "contrib/Contents-all",
                digest: ContentDigest::md5_hex("7fdf4db15250af5368cc52a91e8edbce").unwrap(),
                size: 738242,
            }
        );
        assert_eq!(
            entries[0].by_hash_path(),
            "contrib/by-hash/MD5Sum/7fdf4db15250af5368cc52a91e8edbce"
        );
        assert_eq!(
            entries[1],
            ReleaseFileEntry {
                path: "contrib/Contents-all.gz",
                digest: ContentDigest::md5_hex("cbd7bc4d3eb517ac2b22f929dfc07b47").unwrap(),
                size: 57319,
            }
        );
        assert_eq!(
            entries[1].by_hash_path(),
            "contrib/by-hash/MD5Sum/cbd7bc4d3eb517ac2b22f929dfc07b47"
        );
        assert_eq!(
            entries[599],
            ReleaseFileEntry {
                path: "non-free/source/Sources.xz",
                digest: ContentDigest::md5_hex("e3830f6fc5a946b5a5b46e8277e1d86f").unwrap(),
                size: 80488,
            }
        );
        assert_eq!(
            entries[599].by_hash_path(),
            "non-free/source/by-hash/MD5Sum/e3830f6fc5a946b5a5b46e8277e1d86f"
        );

        assert!(release.iter_index_files(ChecksumType::Sha1).is_none());

        let entries = release
            .iter_index_files(ChecksumType::Sha256)
            .unwrap()
            .collect::<Result<Vec<_>>>()?;
        assert_eq!(entries.len(), 600);
        assert_eq!(
            entries[0],
            ReleaseFileEntry {
                path: "contrib/Contents-all",
                digest: ContentDigest::sha256_hex(
                    "3957f28db16e3f28c7b34ae84f1c929c567de6970f3f1b95dac9b498dd80fe63"
                )
                .unwrap(),
                size: 738242,
            }
        );
        assert_eq!(entries[0].by_hash_path(), "contrib/by-hash/SHA256/3957f28db16e3f28c7b34ae84f1c929c567de6970f3f1b95dac9b498dd80fe63");
        assert_eq!(
            entries[1],
            ReleaseFileEntry {
                path: "contrib/Contents-all.gz",
                digest: ContentDigest::sha256_hex(
                    "3e9a121d599b56c08bc8f144e4830807c77c29d7114316d6984ba54695d3db7b"
                )
                .unwrap(),
                size: 57319,
            }
        );
        assert_eq!(entries[1].by_hash_path(), "contrib/by-hash/SHA256/3e9a121d599b56c08bc8f144e4830807c77c29d7114316d6984ba54695d3db7b");
        assert_eq!(
            entries[599],
            ReleaseFileEntry {
                digest: ContentDigest::sha256_hex(
                    "30f3f996941badb983141e3b29b2ed5941d28cf81f9b5f600bb48f782d386fc7"
                )
                .unwrap(),
                size: 80488,
                path: "non-free/source/Sources.xz",
            }
        );
        assert_eq!(entries[599].by_hash_path(), "non-free/source/by-hash/SHA256/30f3f996941badb983141e3b29b2ed5941d28cf81f9b5f600bb48f782d386fc7");

        const EXPECTED_CONTENTS: usize = 126;
        const EXPECTED_PACKAGES: usize = 180;
        const EXPECTED_SOURCES: usize = 9;
        const EXPECTED_RELEASE: usize = 63;
        const EXPECTED_APPSTREAM_COMPONENTS: usize = 72;
        const EXPECTED_APPSTREAM_ICONS: usize = 18;
        const EXPECTED_TRANSLATION: usize = 78;
        const EXPECTED_FILEMANIFEST: usize = 54;
        const EXPECTED_OTHER: usize = 600
            - EXPECTED_CONTENTS
            - EXPECTED_PACKAGES
            - EXPECTED_SOURCES
            - EXPECTED_RELEASE
            - EXPECTED_APPSTREAM_COMPONENTS
            - EXPECTED_APPSTREAM_ICONS
            - EXPECTED_TRANSLATION
            - EXPECTED_FILEMANIFEST;

        assert_eq!(EXPECTED_OTHER, 0);

        let entries = release
            .iter_classified_index_files(ChecksumType::Sha256)
            .unwrap()
            .collect::<Result<Vec<_>>>()?;
        assert_eq!(entries.len(), 600);
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::Contents(_)))
                .count(),
            EXPECTED_CONTENTS
        );
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::Packages(_)))
                .count(),
            EXPECTED_PACKAGES
        );
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::Sources(_)))
                .count(),
            EXPECTED_SOURCES
        );
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::Release(_)))
                .count(),
            EXPECTED_RELEASE
        );
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::AppStreamComponents(_)))
                .count(),
            EXPECTED_APPSTREAM_COMPONENTS
        );
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::AppStreamIcons(_)))
                .count(),
            EXPECTED_APPSTREAM_ICONS
        );
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::Translation(_)))
                .count(),
            EXPECTED_TRANSLATION
        );
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::FileManifest(_)))
                .count(),
            EXPECTED_FILEMANIFEST
        );
        assert_eq!(
            entries
                .iter()
                .filter(|entry| matches!(entry, ClassifiedReleaseFileEntry::Other(_)))
                .count(),
            EXPECTED_OTHER
        );

        let contents = release
            .iter_contents_indices(ChecksumType::Sha256)
            .unwrap()
            .collect::<Result<Vec<_>>>()?;
        assert_eq!(contents.len(), EXPECTED_CONTENTS);

        assert_eq!(
            contents[0],
            ContentsFileEntry {
                entry: ReleaseFileEntry {
                    path: "contrib/Contents-all",
                    digest: ContentDigest::sha256_hex(
                        "3957f28db16e3f28c7b34ae84f1c929c567de6970f3f1b95dac9b498dd80fe63"
                    )
                    .unwrap(),
                    size: 738242,
                },
                component: "contrib".into(),
                architecture: "all".into(),
                compression: Compression::None,
                is_installer: false
            }
        );
        assert_eq!(
            contents[1],
            ContentsFileEntry {
                entry: ReleaseFileEntry {
                    path: "contrib/Contents-all.gz",
                    digest: ContentDigest::sha256_hex(
                        "3e9a121d599b56c08bc8f144e4830807c77c29d7114316d6984ba54695d3db7b"
                    )
                    .unwrap(),
                    size: 57319,
                },
                component: "contrib".into(),
                architecture: "all".into(),
                compression: Compression::Gzip,
                is_installer: false
            }
        );
        assert_eq!(
            contents[24],
            ContentsFileEntry {
                entry: ReleaseFileEntry {
                    path: "contrib/Contents-udeb-amd64",
                    digest: ContentDigest::sha256_hex(
                        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
                    )
                    .unwrap(),
                    size: 0,
                },
                component: "contrib".into(),
                architecture: "amd64".into(),
                compression: Compression::None,
                is_installer: true
            }
        );

        let packages = release
            .iter_packages_indices(ChecksumType::Sha256)
            .unwrap()
            .collect::<Result<Vec<_>>>()?;
        assert_eq!(packages.len(), EXPECTED_PACKAGES);

        assert_eq!(
            packages[0],
            PackagesFileEntry {
                entry: ReleaseFileEntry {
                    path: "contrib/binary-all/Packages",
                    digest: ContentDigest::sha256_hex(
                        "48cfe101cd84f16baf720b99e8f2ff89fd7e063553966d8536b472677acb82f0"
                    )
                    .unwrap(),
                    size: 103223,
                },
                component: "contrib".into(),
                architecture: "all".into(),
                compression: Compression::None,
                is_installer: false
            }
        );
        assert_eq!(
            packages[1],
            PackagesFileEntry {
                entry: ReleaseFileEntry {
                    path: "contrib/binary-all/Packages.gz",
                    digest: ContentDigest::sha256_hex(
                        "86057fcd3eff667ec8e3fbabb2a75e229f5e99f39ace67ff0db4a8509d0707e4"
                    )
                    .unwrap(),
                    size: 27334,
                },
                component: "contrib".into(),
                architecture: "all".into(),
                compression: Compression::Gzip,
                is_installer: false
            }
        );
        assert_eq!(
            packages[2],
            PackagesFileEntry {
                entry: ReleaseFileEntry {
                    path: "contrib/binary-all/Packages.xz",
                    digest: ContentDigest::sha256_hex(
                        "706c840235798e098d4d6013d1dabbc967f894d0ffa02c92ac959dcea85ddf54"
                    )
                    .unwrap(),
                    size: 23912,
                },
                component: "contrib".into(),
                architecture: "all".into(),
                compression: Compression::Xz,
                is_installer: false
            }
        );

        let udeps = packages
            .into_iter()
            .filter(|x| x.is_installer)
            .collect::<Vec<_>>();

        assert_eq!(udeps.len(), 90);
        assert_eq!(
            udeps[0],
            PackagesFileEntry {
                entry: ReleaseFileEntry {
                    path: "contrib/debian-installer/binary-all/Packages",
                    digest: ContentDigest::sha256_hex(
                        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
                    )
                    .unwrap(),
                    size: 0,
                },
                component: "contrib".into(),
                architecture: "all".into(),
                compression: Compression::None,
                is_installer: true
            }
        );

        let sources = release
            .iter_sources_indices(ChecksumType::Sha256)
            .unwrap()
            .collect::<Result<Vec<_>>>()?;
        assert_eq!(sources.len(), EXPECTED_SOURCES);

        let entry = release
            .find_sources_indices(ChecksumType::Sha256, Compression::Xz, "main")
            .unwrap();
        assert_eq!(
            entry,
            SourcesFileEntry {
                entry: ReleaseFileEntry {
                    path: "main/source/Sources.xz",
                    digest: ContentDigest::sha256_hex(
                        "1801d18c1135168d5dd86a8cb85fb5cd5bd81e16174acc25d900dee11389e9cd"
                    )
                    .unwrap(),
                    size: 8616784,
                },
                component: "main".into(),
                compression: Compression::Xz
            }
        );

        Ok(())
    }

    fn bullseye_signing_key() -> pgp::SignedPublicKey {
        crate::signing_key::DistroSigningKey::Debian11Release.public_key()
    }

    #[test]
    fn parse_bullseye_inrelease() -> Result<()> {
        let reader = std::io::Cursor::new(include_bytes!("../testdata/inrelease-debian-bullseye"));

        let release = ReleaseFile::from_armored_reader(reader)?;

        let signing_key = bullseye_signing_key();

        assert_eq!(release.signatures.unwrap().verify(&signing_key).unwrap(), 1);

        Ok(())
    }

    #[test]
    fn bad_signature_rejection() -> Result<()> {
        let reader = std::io::Cursor::new(
            include_str!("../testdata/inrelease-debian-bullseye").replace(
                "d41d8cd98f00b204e9800998ecf8427e",
                "d41d8cd98f00b204e9800998ecf80000",
            ),
        );
        let release = ReleaseFile::from_armored_reader(reader)?;

        let signing_key = bullseye_signing_key();

        assert!(release.signatures.unwrap().verify(&signing_key).is_err());

        Ok(())
    }
}