fstool 0.3.0

Build disk images and filesystems (ext2/3/4, MBR, GPT) from a directory tree and TOML spec, in the spirit of genext2fs.
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
//! Repack — copy file trees from one source into a freshly-formatted
//! destination filesystem.
//!
//! Three kinds of sources, exposed as [`Source`]:
//!
//! * A **host directory** (`Source::HostDir`) — the original
//!   `ext-build` / `fat-build` flow, walks a directory tree.
//! * A **tar archive** on disk (`Source::TarArchive`), with optional
//!   compression codec. Compressed archives go through a two-pass
//!   stream-index → replay flow; plain `.tar` falls through to the
//!   `Image` path (the regular tar reader sits on top of a
//!   [`BlockDevice`](crate::block::BlockDevice)).
//! * An **existing image** (`Source::Image`) — a raw or qcow2 file,
//!   optionally with a `:N` partition selector. Walks the source FS
//!   through [`AnyFs`](crate::inspect::AnyFs) and copies entries
//!   straight through without host-filesystem intermediation.
//!
//! The two main entry points — [`populate_ext_from_source`] and
//! [`populate_fat32_from_source`] — take an already-formatted
//! destination filesystem and stream the chosen source's contents
//! into it. Auto-sizing helpers ([`ext_build_plan_for_source`],
//! [`fat32_min_bytes_for_source`]) let callers right-size the
//! destination geometry up-front.
//!
//! Used by both the `fstool repack` CLI command and by the
//! [`spec`](crate::spec) layer when a TOML `source = "..."` value
//! points at a tar / image instead of a directory.

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

use crate::Result;
use crate::compression::Algo;
use crate::fs::ext::{Ext, FsKind};

/// Where to draw a filesystem's contents from when building or
/// populating it. See module docs.
#[derive(Debug, Clone)]
pub enum Source {
    /// A directory on the host filesystem, walked recursively.
    HostDir(PathBuf),
    /// A tar archive on disk, plain or compressed.
    TarArchive { path: PathBuf, codec: Option<Algo> },
    /// An existing image, optionally with a `:N` partition selector.
    Image(crate::inspect::Target),
    /// Multiple sources stacked bottom→top. Upper layers override
    /// files of the same path; tombstones (`.wh.*` files, character
    /// device 0/0) delete paths from lower layers. See
    /// [`crate::merge`] for the fold semantics.
    Layered(Vec<Source>),
}

impl Source {
    /// Auto-detect what kind of source `spec` points at.
    ///
    /// * `a+b+c` (`+`-separated specs) → `Layered`, applied bottom→top.
    /// * An existing directory path → `HostDir`.
    /// * A recognised tar extension (`.tar`, `.tar.gz`, `.tgz`,
    ///   `.tar.xz`, `.txz`, `.tar.zst`, `.tar.lz4`, `.tar.lzma`,
    ///   `.tar.lzo`) → `TarArchive`.
    /// * Anything else, including a `path:N` partition selector
    ///   → `Image`. Parsed by [`crate::inspect::Target::parse`].
    pub fn detect(spec: &str) -> Result<Self> {
        // Layered: `a+b+c` (bottom=a, top=c). The single `+` separator
        // never collides with real paths in practice — `+` is rare in
        // filenames and `path:partition` syntax uses `:` not `+`.
        if spec.contains('+') {
            let parts: Vec<_> = spec
                .split('+')
                .filter(|p| !p.is_empty())
                .map(Self::detect)
                .collect::<Result<_>>()?;
            if parts.len() > 1 {
                return Ok(Self::Layered(parts));
            }
            if let Some(single) = parts.into_iter().next() {
                return Ok(single);
            }
        }
        // Strip the partition suffix (`:N`) only when `N` is purely
        // numeric — otherwise a Windows drive letter (`C:\foo.tar`)
        // gets mistaken for a `path:partition` spec and the rest of
        // the detection logic loses the file extension.
        let bare = match spec.rsplit_once(':') {
            Some((head, tail)) if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) => {
                head
            }
            _ => spec,
        };
        let bare_path = Path::new(bare);
        if bare == spec
            && let Ok(meta) = std::fs::metadata(bare_path)
            && meta.is_dir()
        {
            return Ok(Self::HostDir(bare_path.to_path_buf()));
        }
        if let Some(codec) = tar_input_codec(spec) {
            return Ok(Self::TarArchive {
                path: bare_path.to_path_buf(),
                codec: Some(codec),
            });
        }
        if has_plain_tar_extension(bare_path) {
            return Ok(Self::TarArchive {
                path: bare_path.to_path_buf(),
                codec: None,
            });
        }
        Ok(Self::Image(crate::inspect::Target::parse(spec)))
    }
}

fn has_plain_tar_extension(path: &Path) -> bool {
    path.extension()
        .and_then(|s| s.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case("tar"))
}

/// Open `target` as a block device, treat its contents as an
/// arbitrary readable FS, and copy every entry into `dst` (a
/// freshly-formatted ext{2,3,4}).
fn copy_image_into_ext(
    target: &crate::inspect::Target,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut Ext,
) -> Result<()> {
    crate::inspect::with_target_device(target, |src_dev| {
        let src_fs = crate::inspect::AnyFs::open(src_dev)?;
        copy_into_ext(src_dev, &src_fs, dst_dev, dst)
    })
}

/// FAT32 sibling of [`copy_image_into_ext`].
fn copy_image_into_fat32(
    target: &crate::inspect::Target,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::fat::Fat32,
) -> Result<()> {
    crate::inspect::with_target_device(target, |src_dev| {
        let src_fs = crate::inspect::AnyFs::open(src_dev)?;
        copy_into_fat32(src_dev, &src_fs, dst_dev, dst)
    })
}

/// Populate `dst` (a freshly formatted ext{2,3,4}) with the contents
/// of `source`. The destination is assumed to already exist.
pub fn populate_ext_from_source(
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut Ext,
    source: &Source,
) -> Result<()> {
    match source {
        Source::HostDir(p) => dst.populate_from_host_dir(dst_dev, 2, p),
        Source::TarArchive {
            path,
            codec: Some(algo),
        } => {
            let spec = path.to_string_lossy().into_owned();
            let index = build_tar_stream_index(&spec, *algo)?;
            replay_tar_index_into_ext(&spec, *algo, &index, dst_dev, dst)
        }
        Source::TarArchive { path, codec: None } => {
            let target = crate::inspect::Target::parse(&path.to_string_lossy());
            copy_image_into_ext(&target, dst_dev, dst)
        }
        Source::Image(target) => copy_image_into_ext(target, dst_dev, dst),
        Source::Layered(layers) => {
            // Flatten the stack to a tempfile (applying whiteouts +
            // opaque-dir semantics), then recurse with the tempfile as
            // a plain tar source. The tempfile must outlive the call.
            let tmp = crate::merge::flatten_to_tempfile(layers)?;
            let merged = Source::TarArchive {
                path: tmp.path().to_path_buf(),
                codec: None,
            };
            let res = populate_ext_from_source(dst_dev, dst, &merged);
            drop(tmp);
            res
        }
    }
}

/// Populate `dst` (a freshly formatted FAT32) with the contents of
/// `source`. The destination is assumed to already exist.
pub fn populate_fat32_from_source(
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::fat::Fat32,
    source: &Source,
) -> Result<()> {
    match source {
        Source::HostDir(p) => dst.populate_from_host_dir(dst_dev, p),
        Source::TarArchive {
            path,
            codec: Some(algo),
        } => {
            let spec = path.to_string_lossy().into_owned();
            let index = build_tar_stream_index(&spec, *algo)?;
            replay_tar_index_into_fat(&spec, *algo, &index, dst_dev, dst)
        }
        Source::TarArchive { path, codec: None } => {
            let target = crate::inspect::Target::parse(&path.to_string_lossy());
            copy_image_into_fat32(&target, dst_dev, dst)
        }
        Source::Image(target) => copy_image_into_fat32(target, dst_dev, dst),
        Source::Layered(layers) => {
            let tmp = crate::merge::flatten_to_tempfile(layers)?;
            let merged = Source::TarArchive {
                path: tmp.path().to_path_buf(),
                codec: None,
            };
            let res = populate_fat32_from_source(dst_dev, dst, &merged);
            drop(tmp);
            res
        }
    }
}

/// Build a [`BuildPlan`](crate::fs::ext::BuildPlan) sized for the
/// source. Walks the source once and feeds entry counts + byte totals
/// into the plan; the resulting `to_format_opts()` is ready to drive
/// `Ext::format_with`.
pub fn ext_build_plan_for_source(
    source: &Source,
    block_size: u32,
    kind: FsKind,
) -> Result<crate::fs::ext::BuildPlan> {
    let mut plan = crate::fs::ext::BuildPlan::new(block_size, kind);
    match source {
        Source::HostDir(p) => plan.scan_host_path(p)?,
        Source::TarArchive {
            path,
            codec: Some(algo),
        } => {
            let spec = path.to_string_lossy().into_owned();
            let index = build_tar_stream_index(&spec, *algo)?;
            walk_tar_index_for_plan(&index, &mut plan);
        }
        Source::TarArchive { path, codec: None } => {
            let target = crate::inspect::Target::parse(&path.to_string_lossy());
            crate::inspect::with_target_device(&target, |src_dev| {
                let mut src_fs = crate::inspect::AnyFs::open(src_dev)?;
                build_ext_plan_inner(src_dev, &mut src_fs, &mut plan)
            })?;
        }
        Source::Image(target) => {
            crate::inspect::with_target_device(target, |src_dev| {
                let mut src_fs = crate::inspect::AnyFs::open(src_dev)?;
                build_ext_plan_inner(src_dev, &mut src_fs, &mut plan)
            })?;
        }
        Source::Layered(layers) => {
            // Plan from the flattened tar; the tempfile lifetime
            // brackets the scan, after which it's dropped.
            let tmp = crate::merge::flatten_to_tempfile(layers)?;
            let merged_path = tmp.path().to_string_lossy().into_owned();
            let target = crate::inspect::Target::parse(&merged_path);
            crate::inspect::with_target_device(&target, |src_dev| {
                let mut src_fs = crate::inspect::AnyFs::open(src_dev)?;
                build_ext_plan_inner(src_dev, &mut src_fs, &mut plan)
            })?;
            drop(tmp);
        }
    }
    Ok(plan)
}

/// Populate any [`crate::fs::Filesystem`] from `source`, dispatching
/// through the trait for every entry create. Works for HFS+, NTFS,
/// F2FS, SquashFS, XFS — whatever implements the trait — though
/// ext/FAT32 callers should prefer [`populate_ext_from_source`] /
/// [`populate_fat32_from_source`] which preserve xattrs and use the
/// per-FS fast paths.
///
/// Tar-archive and existing-image sources route through an internal
/// helper that opens the source via
/// [`crate::inspect::AnyFs`] and replays entries through trait
/// methods.
pub fn populate_fs_from_source<F: crate::fs::Filesystem>(
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut F,
    source: &Source,
) -> Result<()> {
    populate_fs_from_source_dyn(dst_dev, dst, source)
}

/// Trait-object form of [`populate_fs_from_source`]. Used by code
/// paths (e.g. [`crate::inspect::AnyFs`] dispatch helpers) that have
/// a `&mut dyn Filesystem` rather than a known concrete type.
pub fn populate_fs_from_source_dyn(
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut dyn crate::fs::Filesystem,
    source: &Source,
) -> Result<()> {
    match source {
        Source::HostDir(p) => populate_host_dir_via_trait(dst_dev, dst, p),
        Source::TarArchive {
            path,
            codec: Some(_algo),
        } => {
            // Compressed tar: open as image via AnyFs::Tar isn't easy
            // (we'd need to decompress first). For now, the generic
            // path supports plain tar via the image walker below.
            let target = crate::inspect::Target::parse(&path.to_string_lossy());
            populate_image_via_trait(&target, dst_dev, dst)
        }
        Source::TarArchive { path, codec: None } => {
            let target = crate::inspect::Target::parse(&path.to_string_lossy());
            populate_image_via_trait(&target, dst_dev, dst)
        }
        Source::Image(target) => populate_image_via_trait(target, dst_dev, dst),
        Source::Layered(layers) => crate::merge::populate_from_layered(dst_dev, dst, layers),
    }
}

/// Recursively copy a host directory tree into `dst` via the trait.
fn populate_host_dir_via_trait(
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut dyn crate::fs::Filesystem,
    root: &Path,
) -> Result<()> {
    // Stack of (host dir, fs path).
    let mut stack: Vec<(PathBuf, String)> = vec![(root.to_path_buf(), "/".to_string())];
    while let Some((dir, fs_dir)) = stack.pop() {
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let name = entry.file_name();
            let name_str = name.to_str().ok_or_else(|| {
                crate::Error::InvalidArgument(format!("repack: non-UTF-8 host filename {:?}", name))
            })?;
            let dest = join_fs_path(&fs_dir, name_str);
            let dest_path = std::path::Path::new(&dest);
            let meta = entry.metadata()?;
            let ft = meta.file_type();
            let fmeta = host_meta_to_fs(&meta);
            if ft.is_dir() {
                dst.create_dir(dst_dev, dest_path, fmeta)?;
                stack.push((entry.path(), dest));
            } else if ft.is_symlink() {
                let target = std::fs::read_link(entry.path())?;
                dst.create_symlink(dst_dev, dest_path, &target, fmeta)?;
            } else if ft.is_file() {
                let len = meta.len();
                let src = crate::fs::FileSource::HostPath(entry.path());
                dst.create_file(dst_dev, dest_path, src, fmeta)?;
                let _ = len;
            }
        }
    }
    Ok(())
}

/// Open `target` as an image, walk its filesystem, replay entries
/// into `dst` via trait methods.
fn populate_image_via_trait(
    target: &crate::inspect::Target,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut dyn crate::fs::Filesystem,
) -> Result<()> {
    crate::inspect::with_target_device(target, |src_dev| {
        let mut src_fs = crate::inspect::AnyFs::open(src_dev)?;
        let mut stack: Vec<String> = vec!["/".to_string()];
        while let Some(dir) = stack.pop() {
            let entries = src_fs.list(src_dev, &dir)?;
            for e in entries {
                if e.name == "." || e.name == ".." || e.name == "lost+found" {
                    continue;
                }
                let child = join_fs_path(&dir, &e.name);
                let child_path = std::path::Path::new(&child);
                let fmeta = crate::fs::FileMeta::default();
                match e.kind {
                    crate::fs::EntryKind::Dir => {
                        dst.create_dir(dst_dev, child_path, fmeta)?;
                        stack.push(child);
                    }
                    crate::fs::EntryKind::Regular => {
                        // Stream source body through a tempfile so the
                        // destination's create_file can take a HostPath
                        // (works around the trait's source-Read lifetime
                        // borrowing src_dev mutably).
                        let tmp = staging_tempfile(src_dev, &mut src_fs, &child)?;
                        let path = tmp.path().to_path_buf();
                        // Keep tmp alive for the duration of create_file
                        // by binding it; the source path is consumed
                        // before tmp drops.
                        dst.create_file(
                            dst_dev,
                            child_path,
                            crate::fs::FileSource::HostPath(path),
                            fmeta,
                        )?;
                        drop(tmp);
                    }
                    crate::fs::EntryKind::Symlink => {
                        let target_str = read_symlink_via_anyfs(src_dev, &mut src_fs, &child)?;
                        dst.create_symlink(
                            dst_dev,
                            child_path,
                            std::path::Path::new(&target_str),
                            fmeta,
                        )?;
                    }
                    crate::fs::EntryKind::Char
                    | crate::fs::EntryKind::Block
                    | crate::fs::EntryKind::Fifo
                    | crate::fs::EntryKind::Socket => {
                        // Major/minor extraction isn't on AnyFs yet; fall
                        // back to (0, 0) which is enough for FIFO/socket.
                        let dk = match e.kind {
                            crate::fs::EntryKind::Char => crate::fs::DeviceKind::Char,
                            crate::fs::EntryKind::Block => crate::fs::DeviceKind::Block,
                            crate::fs::EntryKind::Fifo => crate::fs::DeviceKind::Fifo,
                            crate::fs::EntryKind::Socket => crate::fs::DeviceKind::Socket,
                            _ => unreachable!(),
                        };
                        let _ = dst.create_device(dst_dev, child_path, dk, 0, 0, fmeta);
                    }
                    crate::fs::EntryKind::Unknown => {
                        eprintln!("repack: skipping unknown entry {child:?}");
                    }
                }
            }
        }
        Ok(())
    })
}

/// Stream a file's body from the source FS into a fresh tempfile and
/// return the handle. Lets the trait-based copier feed
/// `FileSource::HostPath` to the destination without re-borrowing the
/// source device.
fn staging_tempfile(
    src_dev: &mut dyn crate::block::BlockDevice,
    src_fs: &mut crate::inspect::AnyFs,
    fs_path: &str,
) -> Result<tempfile::NamedTempFile> {
    let mut tmp = tempfile::NamedTempFile::new()?;
    src_fs.copy_file_to(src_dev, fs_path, &mut tmp)?;
    tmp.as_file_mut().sync_all()?;
    Ok(tmp)
}

/// Read the target of a symbolic link via the best per-FS reader on
/// `AnyFs`. Different FSes name the reader differently (some take a
/// path, some an inode); we centralise the dispatch here. Sources
/// that don't (yet) expose a symlink reader return `Unsupported`.
fn read_symlink_via_anyfs(
    src_dev: &mut dyn crate::block::BlockDevice,
    src_fs: &mut crate::inspect::AnyFs,
    path: &str,
) -> Result<String> {
    src_fs.read_symlink(src_dev, path)
}

/// Convert host `Metadata` into a public [`crate::fs::FileMeta`].
fn host_meta_to_fs(meta: &std::fs::Metadata) -> crate::fs::FileMeta {
    #[cfg(unix)]
    use std::os::unix::fs::MetadataExt;
    #[cfg(unix)]
    {
        crate::fs::FileMeta {
            mode: (meta.mode() & 0o7777) as u16,
            uid: meta.uid(),
            gid: meta.gid(),
            mtime: meta.mtime() as u32,
            atime: meta.atime() as u32,
            ctime: meta.ctime() as u32,
        }
    }
    #[cfg(not(unix))]
    {
        let _ = meta;
        crate::fs::FileMeta::default()
    }
}

/// Compute the minimum FAT32 byte capacity needed to fit `source`.
/// Bumps to the FAT32 cluster-count minimum + rounds up to a 512-byte
/// sector boundary.
pub fn fat32_min_bytes_for_source(source: &Source) -> Result<u64> {
    let bytes = match source {
        Source::HostDir(p) => sum_host_dir_bytes(p)?,
        Source::TarArchive {
            path,
            codec: Some(algo),
        } => {
            let spec = path.to_string_lossy().into_owned();
            let index = build_tar_stream_index(&spec, *algo)?;
            let (sz, _, _, _, _, _) = size_from_tar_index(&index, "fat32")?;
            return Ok(sz);
        }
        Source::TarArchive { path, codec: None } => {
            let target = crate::inspect::Target::parse(&path.to_string_lossy());
            let mut sum = 0u64;
            crate::inspect::with_target_device(&target, |src_dev| {
                let mut src_fs = crate::inspect::AnyFs::open(src_dev)?;
                sum = sum_source_file_bytes(src_dev, &mut src_fs)?;
                Ok(())
            })?;
            sum
        }
        Source::Image(target) => {
            let mut sum = 0u64;
            crate::inspect::with_target_device(target, |src_dev| {
                let mut src_fs = crate::inspect::AnyFs::open(src_dev)?;
                sum = sum_source_file_bytes(src_dev, &mut src_fs)?;
                Ok(())
            })?;
            sum
        }
        Source::Layered(layers) => {
            // Flatten the layers to a tar, then size from the tar
            // contents (post-whiteout). Tempfile drops at scope end.
            let tmp = crate::merge::flatten_to_tempfile(layers)?;
            let merged_path = tmp.path().to_string_lossy().into_owned();
            let target = crate::inspect::Target::parse(&merged_path);
            let mut sum = 0u64;
            crate::inspect::with_target_device(&target, |src_dev| {
                let mut src_fs = crate::inspect::AnyFs::open(src_dev)?;
                sum = sum_source_file_bytes(src_dev, &mut src_fs)?;
                Ok(())
            })?;
            drop(tmp);
            sum
        }
    };
    let needed = bytes
        .saturating_mul(2)
        .max(crate::fs::fat::MIN_FAT32_CLUSTERS as u64 * 1024);
    Ok(needed.div_ceil(512) * 512)
}

fn sum_host_dir_bytes(root: &Path) -> Result<u64> {
    let mut total = 0u64;
    let mut stack: Vec<PathBuf> = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let meta = entry.metadata()?;
            if meta.is_dir() {
                stack.push(entry.path());
            } else if meta.is_file() {
                total = total.saturating_add(meta.len());
            }
        }
    }
    Ok(total)
}

/// Drive a BuildPlan from any source filesystem through the
/// [`crate::fs::Filesystem`] trait — no per-FS arms. Walks via
/// [`crate::fs::Filesystem::list`], using `DirEntry::size` for files
/// and [`crate::fs::Filesystem::read_symlink`] for each symlink's
/// target length (so the long-symlink branch fires only when needed).
fn build_ext_plan_inner(
    src_dev: &mut dyn crate::block::BlockDevice,
    src_fs: &mut crate::inspect::AnyFs,
    plan: &mut crate::fs::ext::BuildPlan,
) -> Result<()> {
    build_ext_plan_through_trait(src_dev, src_fs, plan)
}

/// Public counterpart of `build_ext_plan_inner` for the binary
/// crate's `build_ext_plan`. Walks the source through the
/// [`crate::fs::Filesystem`] trait, no AnyFs match.
pub fn build_ext_plan_through_trait(
    src_dev: &mut dyn crate::block::BlockDevice,
    src_fs: &mut crate::inspect::AnyFs,
    plan: &mut crate::fs::ext::BuildPlan,
) -> Result<()> {
    src_fs.as_filesystem_dyn(|fs| scan_into_build_plan(src_dev, fs, plan))
}

/// Filesystem-trait-driven recursive scan that fills a BuildPlan.
/// Same shape as the old per-FS walkers; symlink target length is
/// resolved via `Filesystem::read_symlink` (FSes that don't carry
/// symlinks return `Unsupported`, which gets degraded to "assume
/// long symlink — one block").
pub(crate) fn scan_into_build_plan(
    dev: &mut dyn crate::block::BlockDevice,
    fs: &mut dyn crate::fs::Filesystem,
    plan: &mut crate::fs::ext::BuildPlan,
) -> Result<()> {
    use crate::fs::EntryKind;
    let mut stack: Vec<std::path::PathBuf> = vec![std::path::PathBuf::from("/")];
    while let Some(dir) = stack.pop() {
        let entries = fs.list(dev, &dir)?;
        for e in entries {
            if e.name == "." || e.name == ".." || e.name == "lost+found" {
                continue;
            }
            let child = dir.join(&e.name);
            match e.kind {
                EntryKind::Dir => {
                    plan.add_dir();
                    stack.push(child);
                }
                EntryKind::Regular => plan.add_file(e.size),
                EntryKind::Symlink => {
                    let len = fs
                        .read_symlink(dev, &child)
                        .map(|t| t.as_os_str().len())
                        .unwrap_or(usize::MAX);
                    plan.add_symlink(len);
                }
                EntryKind::Char | EntryKind::Block | EntryKind::Fifo | EntryKind::Socket => {
                    plan.add_device()
                }
                EntryKind::Unknown => {}
            }
        }
    }
    Ok(())
}

/// TarStreamIndex variant of [`walk_tar_for_plan`] — adds one entry
/// of each kind to the build plan for every record in the index.
fn walk_tar_index_for_plan(
    index: &crate::fs::tar::TarStreamIndex,
    plan: &mut crate::fs::ext::BuildPlan,
) {
    use crate::fs::tar::EntryKind as TarKind;
    for ix in index.entries() {
        match ix.entry.kind {
            TarKind::Regular | TarKind::HardLink => plan.add_file(ix.entry.size),
            TarKind::Dir => plan.add_dir(),
            TarKind::Symlink => plan.add_symlink(
                ix.entry
                    .link_target
                    .as_deref()
                    .map(|s| s.len())
                    .unwrap_or(0),
            ),
            TarKind::CharDev | TarKind::BlockDev | TarKind::Fifo => plan.add_device(),
        }
    }
}

// ----------------------------------------------------------------------
// Internal helpers (moved verbatim from src/bin/fstool/main.rs)
// ----------------------------------------------------------------------

/// Walk the source filesystem and recreate every entry inside the
/// destination ext. Preserves mode, uid/gid, mtime, atime, ctime; copies
/// symlinks and device nodes verbatim when the source is ext (FAT
/// source has none of those).
pub(crate) fn copy_into_ext(
    src_dev: &mut dyn crate::block::BlockDevice,
    src_fs: &crate::inspect::AnyFs,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::ext::Ext,
) -> crate::Result<()> {
    use crate::fs::FileMeta;
    use crate::inspect::AnyFs;
    match src_fs {
        AnyFs::Ext(src_ext) => copy_ext_dir(src_dev, src_ext, 2, dst_dev, dst, 2),
        AnyFs::Fat32(src_fat) => {
            copy_fat_dir_into_ext(src_dev, src_fat, "/", dst_dev, dst, 2, &FileMeta::default())
        }
        AnyFs::Tar(src_tar) => copy_tar_into_ext(src_dev, src_tar, dst_dev, dst),
        _ => Err(unsupported_repack_src(src_fs)),
    }
}

/// Walk the source filesystem and recreate every entry inside the
/// destination FAT32. FAT can't represent symlinks / device nodes /
/// per-file permissions — those are dropped (with a stderr note when
/// the source had them).
pub(crate) fn copy_into_fat32(
    src_dev: &mut dyn crate::block::BlockDevice,
    src_fs: &crate::inspect::AnyFs,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::fat::Fat32,
) -> crate::Result<()> {
    use crate::inspect::AnyFs;
    match src_fs {
        AnyFs::Ext(src_ext) => copy_ext_dir_into_fat(src_dev, src_ext, 2, "/", dst_dev, dst),
        AnyFs::Fat32(src_fat) => copy_fat_dir_into_fat(src_dev, src_fat, "/", dst_dev, dst),
        AnyFs::Tar(src_tar) => copy_tar_into_fat(src_dev, src_tar, dst_dev, dst),
        _ => Err(unsupported_repack_src(src_fs)),
    }
}

/// Repack-source error for the four read-only FSes (xfs/exfat/hfs+/apfs)
/// — they're inspectable via ls/cat/info but not yet wired into the
/// FS-to-FS copy walkers.
/// If `path` looks like a compressed tar (`.tar.gz`, `.tar.zst`,
/// `.tar.xz`, `.tgz`, `.txz`, `.tar.lz4`, `.tar.lzma`, `.tar.lzo`),
/// return the codec to use; otherwise `None`. Used by repack to pick a
/// streaming compressor for the output file.
pub(crate) fn tar_output_codec(path: &std::path::Path) -> Option<crate::compression::Algo> {
    let s = path.to_string_lossy().to_ascii_lowercase();
    if s.ends_with(".tgz") {
        return Some(crate::compression::Algo::Gzip);
    }
    if s.ends_with(".txz") {
        return Some(crate::compression::Algo::Xz);
    }
    if !s.contains(".tar.") {
        // Bare `.gz` / `.zst` etc. without a `.tar.` prefix isn't tar.
        return None;
    }
    crate::compression::Algo::from_extension(path)
}

/// `Some(algo)` when `path` points at a compressed tar archive that
/// should be stream-walked rather than decompressed-to-tempfile.
/// `None` for plain `.tar` (the regular BlockDevice path handles it
/// fine) and for non-tar files.
pub(crate) fn tar_input_codec(path: &str) -> Option<crate::compression::Algo> {
    // Strip any `:N` partition selector — tar archives don't have
    // partitions, but the parsing helper allows the form.
    let p = std::path::Path::new(path.split(':').next().unwrap_or(path));
    tar_output_codec(p)
}

/// Open `src` as a freshly-decoded `Read` positioned at the
/// decompressed stream's byte 0. Boxed so it composes with the
/// existing helpers; callers feed this to [`TarStreamIndex::open_body`]
/// to seek to a specific entry's body offset.
pub(crate) fn open_decoded_stream(
    src: &str,
    algo: crate::compression::Algo,
) -> crate::Result<Box<dyn std::io::Read>> {
    let p = std::path::Path::new(src.split(':').next().unwrap_or(src));
    let file = std::fs::File::open(p)?;
    let buffered: Box<dyn std::io::Read> =
        Box::new(std::io::BufReader::with_capacity(64 * 1024, file));
    crate::compression::make_reader(algo, buffered)
}

/// Single-pass walk that builds a [`TarStreamIndex`] for a compressed
/// tar source. Bodies are NOT consumed: the underlying reader skips
/// past each body's bytes during `next_entry`, so the only buffered
/// data is the per-entry metadata.
pub(crate) fn build_tar_stream_index(
    src: &str,
    algo: crate::compression::Algo,
) -> crate::Result<crate::fs::tar::TarStreamIndex> {
    let reader = open_tar_stream_reader(src, Some(algo))?;
    crate::fs::tar::TarStreamIndex::build_from(reader)
}

/// Aggregate the size-relevant counters from a built [`TarStreamIndex`]
/// and return `(size_estimate, files, dirs, symlinks, devices, bytes)`.
/// `target_lower` tunes the size estimate per destination FS.
pub(crate) fn size_from_tar_index(
    index: &crate::fs::tar::TarStreamIndex,
    target_lower: &str,
) -> crate::Result<(u64, u64, u64, u64, u64, u64)> {
    use crate::fs::tar::EntryKind as TarKind;
    let mut files = 0u64;
    let mut dirs = 0u64;
    let mut symlinks = 0u64;
    let mut devices = 0u64;
    let mut bytes = 0u64;
    for ix in index.entries() {
        match ix.entry.kind {
            TarKind::Regular => {
                files += 1;
                bytes += ix.entry.size;
            }
            TarKind::HardLink => {
                files += 1;
                bytes += ix.entry.size;
            }
            TarKind::Dir => dirs += 1,
            TarKind::Symlink => symlinks += 1,
            TarKind::CharDev | TarKind::BlockDev | TarKind::Fifo => devices += 1,
        }
    }
    let size_estimate = match target_lower {
        "ext2" | "ext3" | "ext4" => {
            // Conservative ext sizing: file bytes + dir/inode overhead.
            // We give 4 KiB per inode + 1 MiB structural pad; min 8 MiB.
            let inodes = files + dirs + symlinks + devices + 16;
            let raw = bytes + inodes * 4096 + 1024 * 1024;
            raw.max(8 * 1024 * 1024).div_ceil(4096) * 4096
        }
        "fat32" | "vfat" => {
            // FAT32 needs at least MIN_FAT32_CLUSTERS clusters of 1 KiB
            // overhead per cluster. Double the byte total to leave room
            // for cluster fragmentation + FAT tables + dir entries.
            let needed = bytes
                .saturating_mul(2)
                .max(crate::fs::fat::MIN_FAT32_CLUSTERS as u64 * 1024);
            needed.div_ceil(512) * 512
        }
        _ => bytes + 16 * 1024 * 1024,
    };
    Ok((size_estimate, files, dirs, symlinks, devices, bytes))
}

/// Pass 2 (ext): replay the indexed entries into a freshly-formatted
/// ext destination, re-decompressing per regular file via
/// `TarStreamIndex::open_body`.
pub(crate) fn replay_tar_index_into_ext(
    src: &str,
    algo: crate::compression::Algo,
    index: &crate::fs::tar::TarStreamIndex,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::ext::Ext,
) -> crate::Result<()> {
    use crate::fs::tar::EntryKind as TarKind;
    use crate::fs::{DeviceKind, FileMeta};
    let mut path_to_ino: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
    path_to_ino.insert("/".into(), 2);

    for ix in index.entries() {
        let e = &ix.entry;
        let parent_path = parent_of(&e.path);
        let parent_ino = ensure_ext_dir(dst_dev, dst, &mut path_to_ino, &parent_path)?;
        let leaf = leaf_of(&e.path);
        let meta = FileMeta {
            mode: e.mode & 0o7777,
            uid: e.uid,
            gid: e.gid,
            mtime: e.mtime as u32,
            atime: e.mtime as u32,
            ctime: e.mtime as u32,
        };
        let new_ino = match e.kind {
            TarKind::Regular => {
                let mut body = index.open_body(&e.path, || open_decoded_stream(src, algo))?;
                dst.add_file_to_streaming(
                    dst_dev,
                    parent_ino,
                    leaf.as_bytes(),
                    &mut body,
                    e.size,
                    meta,
                )?
            }
            TarKind::HardLink => {
                // Materialise the linked target's content. Preserving
                // ext hard-link semantics across FS types is out of
                // scope; we copy the bytes instead.
                let mut body = index.open_body(&e.path, || open_decoded_stream(src, algo))?;
                let len = body.remaining();
                dst.add_file_to_streaming(
                    dst_dev,
                    parent_ino,
                    leaf.as_bytes(),
                    &mut body,
                    len,
                    meta,
                )?
            }
            TarKind::Dir => ensure_ext_dir(dst_dev, dst, &mut path_to_ino, &e.path)?,
            TarKind::Symlink => {
                let target = e.link_target.as_deref().unwrap_or("");
                dst.add_symlink_to(
                    dst_dev,
                    parent_ino,
                    leaf.as_bytes(),
                    target.as_bytes(),
                    meta,
                )?
            }
            TarKind::CharDev => dst.add_device_to(
                dst_dev,
                parent_ino,
                leaf.as_bytes(),
                DeviceKind::Char,
                e.device_major,
                e.device_minor,
                meta,
            )?,
            TarKind::BlockDev => dst.add_device_to(
                dst_dev,
                parent_ino,
                leaf.as_bytes(),
                DeviceKind::Block,
                e.device_major,
                e.device_minor,
                meta,
            )?,
            TarKind::Fifo => dst.add_device_to(
                dst_dev,
                parent_ino,
                leaf.as_bytes(),
                DeviceKind::Fifo,
                0,
                0,
                meta,
            )?,
        };
        if matches!(e.kind, TarKind::Dir) {
            path_to_ino.insert(e.path.clone(), new_ino);
        }
        if !e.xattrs.is_empty() {
            dst.set_xattrs(dst_dev, new_ino, &e.xattrs)?;
        }
    }
    Ok(())
}

/// Pass 2 (FAT32): same as the ext replay, minus the metadata FAT
/// can't carry. Entries that aren't regular / dir / hard-link are
/// dropped with a stderr note.
pub(crate) fn replay_tar_index_into_fat(
    src: &str,
    algo: crate::compression::Algo,
    index: &crate::fs::tar::TarStreamIndex,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::fat::Fat32,
) -> crate::Result<()> {
    use crate::fs::tar::EntryKind as TarKind;
    let mut made_dirs: std::collections::HashSet<String> =
        std::collections::HashSet::from(["/".into()]);
    for ix in index.entries() {
        let e = &ix.entry;
        let parent = parent_of(&e.path);
        ensure_fat_dir(dst_dev, dst, &mut made_dirs, &parent)?;
        match e.kind {
            TarKind::Regular => {
                let mut body = index.open_body(&e.path, || open_decoded_stream(src, algo))?;
                dst.add_file_from_reader(dst_dev, &e.path, &mut body, e.size)?;
            }
            TarKind::HardLink => {
                let mut body = index.open_body(&e.path, || open_decoded_stream(src, algo))?;
                let len = body.remaining();
                dst.add_file_from_reader(dst_dev, &e.path, &mut body, len)?;
            }
            TarKind::Dir => {
                ensure_fat_dir(dst_dev, dst, &mut made_dirs, &e.path)?;
            }
            _ => {
                eprintln!(
                    "repack: dropping {:?} — FAT32 can't represent {:?}",
                    e.path, e.kind
                );
            }
        }
    }
    Ok(())
}

/// Open a (possibly codec-wrapped) tar archive as a streaming reader.
pub(crate) fn open_tar_stream_reader(
    path: &str,
    algo: Option<crate::compression::Algo>,
) -> crate::Result<crate::fs::tar::TarStreamReader<Box<dyn std::io::Read>>> {
    let p = std::path::Path::new(path.split(':').next().unwrap_or(path));
    let file = std::fs::File::open(p)?;
    let buffered: Box<dyn std::io::Read> =
        Box::new(std::io::BufReader::with_capacity(64 * 1024, file));
    let inner: Box<dyn std::io::Read> = match algo {
        Some(a) => crate::compression::make_reader(a, buffered)?,
        None => buffered,
    };
    Ok(crate::fs::tar::TarStreamReader::new(inner))
}

/// Open the tar source (optionally codec-wrapped) and build a
/// random-access index over it. Shared entry point for the
/// streaming-tar inspector commands.
pub fn open_tar_stream_index(
    image: &str,
    algo: Option<crate::compression::Algo>,
) -> crate::Result<crate::fs::tar::TarStreamIndex> {
    let reader = open_tar_stream_reader(image, algo)?;
    crate::fs::tar::TarStreamIndex::build_from(reader)
}

pub(crate) fn unsupported_repack_src(src_fs: &crate::inspect::AnyFs) -> crate::Error {
    crate::Error::Unsupported(format!(
        "repack: {} source is not yet wired into the FS-to-FS copy path (it's inspectable via `ls`/`cat`/`info` but can't yet be a repack source)",
        src_fs.kind_string()
    ))
}

// ─── ext → ext (full metadata preservation) ─────────────────────────────

pub(crate) fn copy_ext_dir(
    src_dev: &mut dyn crate::block::BlockDevice,
    src: &crate::fs::ext::Ext,
    src_ino: u32,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::ext::Ext,
    dst_ino: u32,
) -> crate::Result<()> {
    use crate::fs::ext::inode::decode_devnum;
    use crate::fs::{DeviceKind, FileMeta};

    let entries = src.list_inode(src_dev, src_ino)?;
    for e in entries {
        if e.name == "." || e.name == ".." || (src_ino == 2 && e.name == "lost+found") {
            continue;
        }
        let inode = src.read_inode(src_dev, e.inode)?;
        let meta = FileMeta {
            mode: inode.mode & 0o7777,
            uid: inode.uid as u32,
            gid: inode.gid as u32,
            mtime: inode.mtime,
            atime: inode.atime,
            ctime: inode.ctime,
        };
        let name = e.name.as_bytes();
        let mode_type = inode.mode & crate::fs::ext::constants::S_IFMT;
        // Read source xattrs once per entry; preserve them across the
        // create + (optional) recursion.
        let xattrs = src.read_xattrs(src_dev, e.inode)?;
        let new_ino = match mode_type {
            t if t == crate::fs::ext::constants::S_IFREG => {
                let mut reader = src.open_file_reader(src_dev, e.inode)?;
                dst.add_file_to_streaming(
                    dst_dev,
                    dst_ino,
                    name,
                    &mut reader,
                    inode.size as u64,
                    meta,
                )?
            }
            t if t == crate::fs::ext::constants::S_IFDIR => {
                let child_ino = dst.add_dir_to(dst_dev, dst_ino, name, meta)?;
                copy_ext_dir(src_dev, src, e.inode, dst_dev, dst, child_ino)?;
                child_ino
            }
            t if t == crate::fs::ext::constants::S_IFLNK => {
                let target = src.read_symlink_target(src_dev, e.inode)?;
                dst.add_symlink_to(dst_dev, dst_ino, name, target.as_bytes(), meta)?
            }
            t if t == crate::fs::ext::constants::S_IFCHR => {
                let (major, minor) = decode_devnum(inode.block[0]);
                dst.add_device_to(dst_dev, dst_ino, name, DeviceKind::Char, major, minor, meta)?
            }
            t if t == crate::fs::ext::constants::S_IFBLK => {
                let (major, minor) = decode_devnum(inode.block[0]);
                dst.add_device_to(
                    dst_dev,
                    dst_ino,
                    name,
                    DeviceKind::Block,
                    major,
                    minor,
                    meta,
                )?
            }
            t if t == crate::fs::ext::constants::S_IFIFO => {
                dst.add_device_to(dst_dev, dst_ino, name, DeviceKind::Fifo, 0, 0, meta)?
            }
            t if t == crate::fs::ext::constants::S_IFSOCK => {
                dst.add_device_to(dst_dev, dst_ino, name, DeviceKind::Socket, 0, 0, meta)?
            }
            _ => {
                eprintln!(
                    "repack: skipping inode {} ({:?}) — unknown mode {:#o}",
                    e.inode, e.name, inode.mode
                );
                continue;
            }
        };
        if !xattrs.is_empty() {
            dst.set_xattrs(dst_dev, new_ino, &xattrs)?;
        }
    }
    Ok(())
}

// ─── FAT32 → FAT32 ──────────────────────────────────────────────────────

pub(crate) fn copy_fat_dir_into_fat(
    src_dev: &mut dyn crate::block::BlockDevice,
    src: &crate::fs::fat::Fat32,
    src_path: &str,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::fat::Fat32,
) -> crate::Result<()> {
    use crate::fs::EntryKind;
    let entries = src.list_path(src_dev, src_path)?;
    for e in entries {
        let child = join_fs_path(src_path, &e.name);
        match e.kind {
            EntryKind::Dir => {
                dst.add_dir(dst_dev, &child)?;
                copy_fat_dir_into_fat(src_dev, src, &child, dst_dev, dst)?;
            }
            EntryKind::Regular => {
                // Resolve the source entry to get its actual file_size.
                let (entry, _) = src.resolve_entry(src_dev, &child)?;
                let mut reader = src.open_file_reader(src_dev, &child)?;
                dst.add_file_from_reader(dst_dev, &child, &mut reader, entry.file_size as u64)?;
            }
            _ => {} // FAT can't carry anything else
        }
    }
    Ok(())
}

// ─── ext → FAT32 (drops metadata FAT can't store) ───────────────────────

pub(crate) fn copy_ext_dir_into_fat(
    src_dev: &mut dyn crate::block::BlockDevice,
    src: &crate::fs::ext::Ext,
    src_ino: u32,
    cur_path: &str,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::fat::Fat32,
) -> crate::Result<()> {
    let entries = src.list_inode(src_dev, src_ino)?;
    for e in entries {
        if e.name == "." || e.name == ".." || (src_ino == 2 && e.name == "lost+found") {
            continue;
        }
        let inode = src.read_inode(src_dev, e.inode)?;
        let mode_type = inode.mode & crate::fs::ext::constants::S_IFMT;
        let child = join_fs_path(cur_path, &e.name);
        match mode_type {
            t if t == crate::fs::ext::constants::S_IFREG => {
                let mut reader = src.open_file_reader(src_dev, e.inode)?;
                dst.add_file_from_reader(dst_dev, &child, &mut reader, inode.size as u64)?;
            }
            t if t == crate::fs::ext::constants::S_IFDIR => {
                dst.add_dir(dst_dev, &child)?;
                copy_ext_dir_into_fat(src_dev, src, e.inode, &child, dst_dev, dst)?;
            }
            t if t == crate::fs::ext::constants::S_IFLNK
                || t == crate::fs::ext::constants::S_IFCHR
                || t == crate::fs::ext::constants::S_IFBLK
                || t == crate::fs::ext::constants::S_IFIFO
                || t == crate::fs::ext::constants::S_IFSOCK =>
            {
                eprintln!(
                    "repack: dropping {child:?} ({:?}) — FAT32 can't represent it",
                    fstool_mode_kind(mode_type)
                );
            }
            _ => {}
        }
    }
    Ok(())
}

// ─── FAT32 → ext ────────────────────────────────────────────────────────

pub(crate) fn copy_fat_dir_into_ext(
    src_dev: &mut dyn crate::block::BlockDevice,
    src: &crate::fs::fat::Fat32,
    src_path: &str,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::ext::Ext,
    dst_ino: u32,
    meta: &crate::fs::FileMeta,
) -> crate::Result<()> {
    use crate::fs::EntryKind;
    let entries = src.list_path(src_dev, src_path)?;
    for e in entries {
        let child = join_fs_path(src_path, &e.name);
        match e.kind {
            EntryKind::Dir => {
                let new_ino = dst.add_dir_to(dst_dev, dst_ino, e.name.as_bytes(), *meta)?;
                copy_fat_dir_into_ext(src_dev, src, &child, dst_dev, dst, new_ino, meta)?;
            }
            EntryKind::Regular => {
                let (entry, _) = src.resolve_entry(src_dev, &child)?;
                let mut reader = src.open_file_reader(src_dev, &child)?;
                dst.add_file_to_streaming(
                    dst_dev,
                    dst_ino,
                    e.name.as_bytes(),
                    &mut reader,
                    entry.file_size as u64,
                    *meta,
                )?;
            }
            _ => {}
        }
    }
    Ok(())
}

// ─── Tar → ext ──────────────────────────────────────────────────────────

/// Replay a tar archive's entries into a fresh ext destination.
/// Preserves mode, uid/gid, mtime, symlinks, device nodes, and xattrs.
pub(crate) fn copy_tar_into_ext(
    src_dev: &mut dyn crate::block::BlockDevice,
    tar: &crate::fs::tar::Tar,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::ext::Ext,
) -> crate::Result<()> {
    use crate::fs::tar::EntryKind;
    use crate::fs::{DeviceKind, FileMeta};
    // Map every absolute path in the tar to its destination inode,
    // creating ancestor dirs on demand so an entry can land before its
    // parent dir appears in the archive.
    let mut path_to_ino: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
    path_to_ino.insert("/".into(), 2);

    let entries: Vec<crate::fs::tar::Entry> = tar.entries().to_vec();
    for e in entries {
        let parent_path = parent_of(&e.path);
        let parent_ino = ensure_ext_dir(dst_dev, dst, &mut path_to_ino, &parent_path)?;
        let leaf = leaf_of(&e.path);
        let meta = FileMeta {
            mode: e.mode & 0o7777,
            uid: e.uid,
            gid: e.gid,
            mtime: e.mtime as u32,
            atime: e.mtime as u32,
            ctime: e.mtime as u32,
        };
        let new_ino = match e.kind {
            EntryKind::Regular => {
                let mut reader = tar.open_file_reader(src_dev, &e.path)?;
                dst.add_file_to_streaming(
                    dst_dev,
                    parent_ino,
                    leaf.as_bytes(),
                    &mut reader,
                    e.size,
                    meta,
                )?
            }
            EntryKind::Dir => {
                // ensure_ext_dir already creates it if missing; we just
                // need its inode.
                ensure_ext_dir(dst_dev, dst, &mut path_to_ino, &e.path)?
            }
            EntryKind::Symlink => {
                let target = e.link_target.as_deref().unwrap_or("");
                dst.add_symlink_to(
                    dst_dev,
                    parent_ino,
                    leaf.as_bytes(),
                    target.as_bytes(),
                    meta,
                )?
            }
            EntryKind::HardLink => {
                // Materialise the link target's content again. Preserves
                // file content across the conversion at the cost of a
                // copy; preserving the link itself across FS types is
                // out of scope.
                let target = e.link_target.as_deref().unwrap_or("");
                let abs_target = if target.starts_with('/') {
                    target.to_string()
                } else {
                    format!("/{target}")
                };
                let target_entry = tar.lookup(&abs_target).ok_or_else(|| {
                    crate::Error::InvalidImage(format!(
                        "tar: hard link {:?}{abs_target:?} (target missing)",
                        e.path
                    ))
                })?;
                let mut reader = tar.open_file_reader(src_dev, &abs_target)?;
                dst.add_file_to_streaming(
                    dst_dev,
                    parent_ino,
                    leaf.as_bytes(),
                    &mut reader,
                    target_entry.size,
                    meta,
                )?
            }
            EntryKind::CharDev => dst.add_device_to(
                dst_dev,
                parent_ino,
                leaf.as_bytes(),
                DeviceKind::Char,
                e.device_major,
                e.device_minor,
                meta,
            )?,
            EntryKind::BlockDev => dst.add_device_to(
                dst_dev,
                parent_ino,
                leaf.as_bytes(),
                DeviceKind::Block,
                e.device_major,
                e.device_minor,
                meta,
            )?,
            EntryKind::Fifo => dst.add_device_to(
                dst_dev,
                parent_ino,
                leaf.as_bytes(),
                DeviceKind::Fifo,
                0,
                0,
                meta,
            )?,
        };
        if matches!(e.kind, EntryKind::Dir) {
            path_to_ino.insert(e.path.clone(), new_ino);
        }
        if !e.xattrs.is_empty() {
            dst.set_xattrs(dst_dev, new_ino, &e.xattrs)?;
        }
    }
    Ok(())
}

pub(crate) fn ensure_ext_dir(
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::ext::Ext,
    path_to_ino: &mut std::collections::HashMap<String, u32>,
    path: &str,
) -> crate::Result<u32> {
    use crate::fs::FileMeta;
    if let Some(&ino) = path_to_ino.get(path) {
        return Ok(ino);
    }
    let parent = parent_of(path);
    let parent_ino = ensure_ext_dir(dst_dev, dst, path_to_ino, &parent)?;
    let leaf = leaf_of(path);
    let meta = FileMeta {
        mode: 0o755,
        ..FileMeta::default()
    };
    let ino = dst.add_dir_to(dst_dev, parent_ino, leaf.as_bytes(), meta)?;
    path_to_ino.insert(path.to_string(), ino);
    Ok(ino)
}

// ─── Tar → FAT32 ────────────────────────────────────────────────────────

pub(crate) fn copy_tar_into_fat(
    src_dev: &mut dyn crate::block::BlockDevice,
    tar: &crate::fs::tar::Tar,
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::fat::Fat32,
) -> crate::Result<()> {
    use crate::fs::tar::EntryKind;
    let mut made_dirs: std::collections::HashSet<String> =
        std::collections::HashSet::from(["/".into()]);
    let entries: Vec<crate::fs::tar::Entry> = tar.entries().to_vec();
    for e in entries {
        let parent = parent_of(&e.path);
        ensure_fat_dir(dst_dev, dst, &mut made_dirs, &parent)?;
        match e.kind {
            EntryKind::Regular => {
                let mut reader = tar.open_file_reader(src_dev, &e.path)?;
                dst.add_file_from_reader(dst_dev, &e.path, &mut reader, e.size)?;
            }
            EntryKind::Dir => {
                ensure_fat_dir(dst_dev, dst, &mut made_dirs, &e.path)?;
            }
            EntryKind::HardLink => {
                let target = e.link_target.as_deref().unwrap_or("");
                let abs_target = if target.starts_with('/') {
                    target.to_string()
                } else {
                    format!("/{target}")
                };
                if let Some(target_entry) = tar.lookup(&abs_target) {
                    let mut reader = tar.open_file_reader(src_dev, &abs_target)?;
                    dst.add_file_from_reader(dst_dev, &e.path, &mut reader, target_entry.size)?;
                }
            }
            _ => {
                eprintln!(
                    "repack: dropping {:?} — FAT32 can't represent {:?}",
                    e.path, e.kind
                );
            }
        }
    }
    Ok(())
}

pub(crate) fn ensure_fat_dir(
    dst_dev: &mut dyn crate::block::BlockDevice,
    dst: &mut crate::fs::fat::Fat32,
    made: &mut std::collections::HashSet<String>,
    path: &str,
) -> crate::Result<()> {
    if made.contains(path) {
        return Ok(());
    }
    let parent = parent_of(path);
    ensure_fat_dir(dst_dev, dst, made, &parent)?;
    dst.add_dir(dst_dev, path)?;
    made.insert(path.to_string());
    Ok(())
}

pub(crate) fn parent_of(path: &str) -> String {
    let p = path.trim_end_matches('/');
    match p.rfind('/') {
        Some(0) | None => "/".into(),
        Some(i) => p[..i].into(),
    }
}

pub(crate) fn leaf_of(path: &str) -> &str {
    let p = path.trim_end_matches('/');
    p.rsplit('/').next().unwrap_or(p)
}

pub(crate) fn join_fs_path(parent: &str, leaf: &str) -> String {
    if parent.ends_with('/') {
        format!("{parent}{leaf}")
    } else {
        format!("{parent}/{leaf}")
    }
}

pub(crate) fn fstool_mode_kind(mode_type: u16) -> &'static str {
    use crate::fs::ext::constants::*;
    match mode_type {
        t if t == S_IFLNK => "symlink",
        t if t == S_IFCHR => "char-device",
        t if t == S_IFBLK => "block-device",
        t if t == S_IFIFO => "fifo",
        t if t == S_IFSOCK => "socket",
        _ => "other",
    }
}

// ─── shrink sizing ───────────────────────────────────────────────────────

/// Sum the size of every regular file in the source filesystem — used
/// by FAT32 shrink sizing.
pub(crate) fn sum_source_file_bytes(
    src_dev: &mut dyn crate::block::BlockDevice,
    src_fs: &mut crate::inspect::AnyFs,
) -> crate::Result<u64> {
    src_fs.total_file_bytes(src_dev)
}