zoi-install 1.29.3

Advanced Package Manager & Environment Orchestrator
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
use std::collections::{BTreeMap, HashSet};
use std::fs::{self, File};
use std::io::{Read, Seek};
use std::path::{Path, PathBuf};

use anyhow::{Result, anyhow};
use colored::Colorize;
use tar::Archive;
use tempfile::Builder;
use walkdir::WalkDir;
use zoi_core::hash::{HashAlgorithm, calculate_file_hash};
use zoi_core::types;
use zoi_core::utils::{self, copy_dir_all};
use zoi_db as db;
use zoi_resolver::local;
use zstd::stream::read::Decoder as ZstdDecoder;

/// Returns the root directory where binary shims should be created for a given
/// scope.
fn get_bin_root(scope: types::Scope) -> Result<PathBuf> {
    match scope {
        types::Scope::User => zoi_core::utils::get_user_bin_dir(),
        types::Scope::System => Ok(zoi_core::utils::get_system_bin_dir()),
        types::Scope::Project => {
            let current_dir = std::env::current_dir()?;
            Ok(current_dir.join(".zoi").join("pkgs").join("bin"))
        }
    }
}

/// Returns the root directory where shell completions should be installed for a
/// given scope and shell.
fn get_completions_root(scope: types::Scope, shell: &str) -> Result<PathBuf> {
    match scope {
        types::Scope::User => zoi_core::utils::get_user_completions_dir(shell),
        types::Scope::System => {
            if cfg!(target_os = "windows") {
                Ok(zoi_core::sysroot::apply_sysroot(PathBuf::from(format!(
                    "C:\\ProgramData\\zoi\\pkgs\\shell\\{shell}"
                ))))
            } else if zoi_core::utils::is_zoios() {
                let base = match shell {
                    "bash" => "/usr/share/bash-completion/completions",
                    "zsh" => "/usr/share/zsh/site-functions",
                    "fish" => "/usr/share/fish/vendor_completions.d",
                    "elvish" => "/usr/share/elvish/lib",
                    _ => "/usr/share/zoi/completions"
                };
                Ok(zoi_core::sysroot::apply_sysroot(PathBuf::from(base)))
            } else {
                let base = match shell {
                    "bash" => "/usr/share/bash-completion/completions",
                    "zsh" => "/usr/share/zsh/site-functions",
                    "fish" => "/usr/share/fish/vendor_completions.d",
                    "elvish" => "/usr/share/elvish/lib",
                    _ => "/usr/local/share/zoi/completions"
                };
                Ok(zoi_core::sysroot::apply_sysroot(PathBuf::from(base)))
            }
        }
        types::Scope::Project => {
            let current_dir = std::env::current_dir()?;
            Ok(current_dir
                .join(".zoi")
                .join("pkgs")
                .join("shell")
                .join(shell))
        }
    }
}

/// Creates a symlink for a shell completion file, removing any existing file or
/// link at the destination.
fn create_completion_symlink(source: &Path, link: &Path) -> Result<()> {
    if link.exists() || link.is_symlink() {
        fs::remove_file(link)?;
    }
    if let Some(parent) = link.parent() {
        fs::create_dir_all(parent)?;
    }
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(source, link)
            .map_err(|e| anyhow!("Failed to create completion symlink: {e}"))?;
    }
    #[cfg(windows)]
    {
        std::os::windows::fs::symlink_file(source, link).map_err(|e| {
            anyhow!("Failed to create completion symlink: {}", e)
        })?;
    }
    Ok(())
}

/// A destination path that an incoming file would overwrite, and who, if
/// anyone, already claims it.
struct FileConflict {
    /// The absolute path the incoming file would be written to.
    path: PathBuf,
    /// The packages that already record this path in `package_files`.
    ///
    /// Empty means the path exists on disk but no installed package claims
    /// it, which is a stray file rather than a package overlap.
    owners: Vec<String>
}

/// Identifies the package being installed, so that the ownership lookup can
/// exclude its own earlier claims.
///
/// A reinstall legitimately rewrites files the package already owns, and those
/// must not be reported as conflicts against another package. Without the
/// identity, every package would appear to conflict with itself.
struct InstallingPackage<'a> {
    /// Package name as recorded in the `packages` table.
    name: &'a str,
    /// Sub-package name for a split package, `None` otherwise.
    sub_package: Option<&'a str>,
    /// Repository tier the package was installed from.
    repo: &'a str,
    /// Registry handle the package belongs to.
    registry: &'a str
}

/// Checks for file conflicts between a source directory and a destination
/// directory, prompting the user for confirmation if conflicts are found.
///
/// The check consults the global `package_files` index rather than only the
/// incoming package's own previous manifest. That distinction is what lets a
/// clobber be reported as a clobber: an unowned file is a stray the user may
/// reasonably want replaced, while a file another package owns is a conflict
/// between two packages that should not be resolved silently by whoever
/// installed last.
///
/// `owned_files` is the caller's existing footprint for this package. It is
/// still needed because the ownership index is only populated once a package
/// has been installed at least once, and it is also the only record for a
/// package installed before this index existed.
fn check_and_handle_file_conflicts(
    source_dir: &Path,
    dest_dir: &Path,
    owned_files: &HashSet<String>,
    package: Option<&InstallingPackage<'_>>,
    yes: bool
) -> Result<()> {
    let mut stray_files = Vec::new();
    let mut owned_by_others: Vec<FileConflict> = Vec::new();

    // Resolved once rather than per file: this runs for every incoming file,
    // and a system-scope package contributes thousands of them.
    //
    // A database that cannot be opened, or a package with no row yet, both
    // degrade to "no owners known" rather than failing the install. Losing the
    // ownership index turns a cross-package clobber back into the plain
    // stray-file prompt, which is the behaviour this check had before, so the
    // failure mode is a weaker check and never a broken install.
    let (conn, current_pkg_id) = match package {
        Some(pkg) => {
            // `open_connection` keys the database file by registry handle, and
            // an empty handle is how the local store is named.
            let registry_key = if pkg.registry.is_empty() {
                "local"
            } else {
                pkg.registry
            };
            match db::open_connection(registry_key) {
                Ok(conn) => {
                    let id = db::get_package_id(
                        &conn,
                        pkg.name,
                        pkg.sub_package,
                        pkg.repo,
                        registry_key
                    )
                    .ok();
                    (Some(conn), id)
                }
                Err(_) => (None, None)
            }
        }
        None => (None, None)
    };

    for entry in WalkDir::new(source_dir)
        .into_iter()
        .filter_map(std::result::Result::ok)
        .skip(1)
    {
        if !entry.file_type().is_file() {
            continue;
        }

        let relative_path = entry.path().strip_prefix(source_dir)?;
        let dest_path = dest_dir.join(relative_path);

        if !dest_path.exists() {
            continue;
        }

        // `owned_files` stores placeholder-form paths such as
        // `${usrroot}/usr/bin/zoi`, so the comparison has to be made against
        // that same form rather than the expanded destination path. Comparing
        // the expanded path against the stored form never matches, which made
        // every reinstall look like a conflict against itself.
        let expanded = zoi_core::utils::expand_placeholders(
            &dest_path.to_string_lossy(),
            Path::new(""),
            types::Scope::System
        );
        let is_self_owned = expanded
            .as_ref()
            .is_ok_and(|p| owned_files.contains(p))
            || owned_files.contains(&dest_path.to_string_lossy().to_string());

        if is_self_owned {
            continue;
        }

        let owners = conn
            .as_ref()
            .and_then(|c| {
                db::get_other_owners(
                    c,
                    &dest_path.to_string_lossy(),
                    current_pkg_id
                )
                .ok()
            })
            .unwrap_or_default();

        if owners.is_empty() {
            stray_files.push(dest_path);
        } else {
            owned_by_others.push(FileConflict {
                path: dest_path,
                owners
            });
        }
    }

    if !stray_files.is_empty() {
        println!();
        println!("{}", "File Conflict Detected:".red().bold());
        println!(
            "The following files that this package wants to install already \
             exist on your system:"
        );
        for file in &stray_files {
            println!("- {}", file.display());
        }
        println!();

        if !utils::ask_for_confirmation(
            "Do you want to overwrite these files and continue with the \
             installation?",
            yes
        ) {
            return Err(anyhow!(
                "Installation aborted by user due to file conflicts."
            ));
        }
    }

    if !owned_by_others.is_empty() {
        println!();
        println!("{}", "File Conflict With Another Package:".red().bold());
        println!(
            "The following files are owned by other installed packages. \
             Installing this package would replace them, leaving the other \
             package broken:"
        );
        for conflict in &owned_by_others {
            println!(
                "- {} (owned by {})",
                conflict.path.display(),
                conflict.owners.join(", ")
            );
        }
        println!();

        if !utils::ask_for_confirmation(
            "Do you want to overwrite these files anyway? The packages listed \
             above may stop working correctly.",
            yes
        ) {
            return Err(anyhow!(
                "Installation aborted by user due to file conflicts with \
                 other packages."
            ));
        }
    }

    Ok(())
}

/// Performs the low-level extraction and staging of a package archive.
///
/// Atomic Staging Pattern:
/// - The archive is unpacked into a temporary system `temp_dir`.
/// - Files are then moved into a `.tmp-install-` subdirectory within the target
///   store.
/// - Only after ALL files are staged and shims are verified does Zoi move the
///   staging folder to its final versioned path (`{version}/`).
///
/// This ensures that a crash, power loss, or network failure during extraction
/// never leaves a partially-installed or broken package in the Zoi store.
///
/// # Errors
///
/// Returns an error if:
/// - The archive file cannot be opened or read.
/// - The archive format is invalid.
/// - Extraction fails.
/// - Metadata parsing fails.
/// - Required permissions are missing.
/// - Filesystem operations (copying, directory creation) fail.
pub fn run(
    package_file: &Path,
    scope_override: Option<types::Scope>,
    registry_handle: &str,
    version_override: Option<&str>,
    yes: bool,
    sub_packages: Option<Vec<String>>,
    link_bins: bool,
    pb: Option<&indicatif::ProgressBar>
) -> Result<(Vec<String>, BTreeMap<String, String>)> {
    let scope = scope_override.unwrap_or(types::Scope::User);

    // Handle meta-packages with no archive
    if package_file.as_os_str().is_empty() {
        if pb.is_none() {
            println!("Initializing meta-package...");
        }
        return Ok((Vec::new(), BTreeMap::new()));
    }

    if pb.is_none() {
        println!(
            "Installing from package archive: {}",
            package_file.display()
        );
    }

    let file_metadata = fs::metadata(package_file)
        .map_err(|e| anyhow!("Failed to get archive metadata: {e}"))?;
    let file_size = file_metadata.len();

    if pb.is_none() {
        println!("Archive size: {}", zoi_core::utils::format_bytes(file_size));
    }

    let mut file = File::open(package_file)
        .map_err(|e| anyhow!("Failed to open package archive: {e}"))?;

    let mut magic = [0u8; 4];
    if file.read_exact(&mut magic).is_ok() && magic != [0x28, 0xB5, 0x2F, 0xFD]
    {
        return Err(anyhow!(
            "Invalid archive format: expected zstd magic number 28 B5 2F FD, \
             but found {magic:02X?}. This file is likely not a valid .zst \
             archive."
        ));
    }

    file.rewind()
        .map_err(|e| anyhow!("Failed to rewind archive file: {e}"))?;

    let decoder = ZstdDecoder::new(file)
        .map_err(|e| anyhow!("Failed to initialize zstd decoder: {e}"))?;
    let mut archive = Archive::new(decoder);

    #[cfg(target_os = "linux")]
    archive.set_unpack_xattrs(true);

    let temp_dir = Builder::new().prefix("zoi-install-").tempdir()?;
    let unpack_path = temp_dir.path().to_path_buf();

    for entry_res in archive
        .entries()
        .map_err(|e| anyhow!("Failed to read archive entries: {e}"))?
    {
        let mut entry = entry_res.map_err(|e| {
            anyhow!(
                "Failed to process archive entry: {e}. The archive may be \
                 truncated or corrupted."
            )
        })?;
        let path = entry
            .path()
            .map_err(|e| anyhow!("Failed to get entry path: {e}"))?
            .to_path_buf();
        entry.unpack_in(&unpack_path).map_err(|e| {
            anyhow!("Failed to unpack file '{}': {}", path.display(), e)
        })?;
    }

    let mut pkg_lua_path = None;
    for entry in WalkDir::new(temp_dir.path())
        .into_iter()
        .filter_map(std::result::Result::ok)
    {
        if entry.file_name().to_string_lossy().ends_with(".pkg.lua") {
            pkg_lua_path = Some(entry.path().to_path_buf());
            break;
        }
    }
    let pkg_lua_path = pkg_lua_path.ok_or_else(|| {
        anyhow!(
            "Could not find .pkg.lua file in archive '{}'",
            package_file.display()
        )
    })?;

    let platform = utils::get_platform()?;
    let metadata = zoi_lua::parser::parse_lua_package_for_platform(
        pkg_lua_path.to_str().ok_or_else(|| {
            anyhow!(
                "Path contains invalid UTF-8 characters: {}",
                pkg_lua_path.display()
            )
        })?,
        &platform,
        version_override,
        Some(scope),
        true
    )?;

    let pooled_manifest_path =
        utils::safe_join(&unpack_path, Path::new("manifest.json"))?;
    if pooled_manifest_path.exists() {
        let content =
            utils::read_file_within(&unpack_path, &pooled_manifest_path)?;
        if let Ok(pooled_manifest) =
            serde_json::from_str::<types::PooledZpaManifest>(&content)
        {
            return extract_pooled_zpa(
                &pooled_manifest,
                &unpack_path,
                scope,
                &metadata,
                sub_packages,
                link_bins,
                pb,
                yes,
                registry_handle
            );
        }
    }

    let version = metadata.version.as_ref().ok_or_else(|| {
        anyhow!(
            "Package '{}' is missing version field in its metadata.",
            metadata.name
        )
    })?;

    if pb.is_none() {
        println!(
            "Installing package: {} v{}",
            metadata.name.cyan(),
            version.yellow()
        );
    }

    let package_dir = local::get_package_dir(
        scope,
        registry_handle,
        &metadata.repo,
        &metadata.name
    )?;
    fs::create_dir_all(&package_dir)?;

    let staging_dir = tempfile::Builder::new()
        .prefix(".tmp-install-")
        .tempdir_in(&package_dir)?;

    let mut installed_files: Vec<String> = Vec::new();
    let version_dir = package_dir.join(version);

    let data_dir = temp_dir.path().join("data");
    if data_dir.exists() {
        if let Some(p) = pb {
            p.set_message(format!("Installing {}...", metadata.name.cyan()));
        } else {
            println!("Installing {}...", metadata.name.cyan());
        }

        let subs_to_install = if let Some(subs) = sub_packages {
            subs
        } else if let Some(subs) = &metadata.sub_packages {
            if let Some(main_subs) = &metadata.main_subs {
                main_subs.clone()
            } else {
                let mut all = vec![String::new()];
                all.extend(subs.clone());
                all
            }
        } else {
            vec![String::new()]
        };

        for sub in subs_to_install {
            let sub_data_dir = if sub.is_empty() {
                data_dir.clone()
            } else {
                utils::validate_path_component(&sub)?;
                if pb.is_none() {
                    println!("Installing sub-package: {}", sub.bold());
                }
                utils::safe_join(&data_dir, Path::new(&sub))?
            };

            if !sub_data_dir.exists() {
                if pb.is_none() {
                    eprintln!(
                        "Warning: sub-package '{sub}' not found in archive, \
                         skipping."
                    );
                }
                continue;
            }

            let mut owned_files = HashSet::new();
            let sub_opt = if sub.is_empty() {
                None
            } else {
                Some(sub.as_str())
            };
            if let Ok(Some(manifest)) =
                local::is_package_installed(&metadata.name, sub_opt, scope)
            {
                owned_files.extend(manifest.installed_files);
            }

            let pkgstore_src = sub_data_dir.join("pkgstore");
            if pkgstore_src.exists() {
                copy_dir_all(&pkgstore_src, staging_dir.path())?;
            }

            let usrroot_src = sub_data_dir.join("usrroot");
            if usrroot_src.exists() {
                if !utils::is_admin() {
                    return Err(anyhow!(
                        "Administrator privileges required to install \
                         system-wide files. Please run with sudo or as an \
                         administrator."
                    ));
                }
                let root_dest =
                    zoi_core::sysroot::apply_sysroot(PathBuf::from("/"));
                check_and_handle_file_conflicts(
                    &usrroot_src,
                    &root_dest,
                    &owned_files,
                    Some(&InstallingPackage {
                        name: &metadata.name,
                        sub_package: sub_opt,
                        repo: &metadata.repo,
                        registry: registry_handle
                    }),
                    yes
                )?;
                copy_dir_all(&usrroot_src, &root_dest)?;
                for entry in WalkDir::new(&usrroot_src)
                    .into_iter()
                    .filter_map(std::result::Result::ok)
                {
                    // Symlinks are recreated by copy_dir_all and must be
                    // tracked too, otherwise they survive uninstall.
                    if entry.file_type().is_file()
                        || entry.file_type().is_symlink()
                    {
                        let rel_to_root =
                            entry.path().strip_prefix(&usrroot_src)?;
                        installed_files.push(format!(
                            "${{usrroot}}/{}",
                            rel_to_root.to_string_lossy().replace('\\', "/")
                        ));
                    }
                }
            }

            let usrhome_src = sub_data_dir.join("usrhome");
            if usrhome_src.exists() {
                let home_dest = zoi_core::utils::get_user_home()
                    .ok_or_else(|| anyhow!("Could not find home directory"))?;
                check_and_handle_file_conflicts(
                    &usrhome_src,
                    &home_dest,
                    &owned_files,
                    Some(&InstallingPackage {
                        name: &metadata.name,
                        sub_package: sub_opt,
                        repo: &metadata.repo,
                        registry: registry_handle
                    }),
                    yes
                )?;
                copy_dir_all(&usrhome_src, &home_dest)?;
                for entry in WalkDir::new(&usrhome_src)
                    .into_iter()
                    .filter_map(std::result::Result::ok)
                {
                    // Track symlinks here as well so cleanup stays complete.
                    if entry.file_type().is_file()
                        || entry.file_type().is_symlink()
                    {
                        let rel_to_home =
                            entry.path().strip_prefix(&usrhome_src)?;
                        installed_files.push(format!(
                            "${{usrhome}}/{}",
                            rel_to_home.to_string_lossy().replace('\\', "/")
                        ));
                    }
                }
            }
        }
    }

    if let Some(p) = pb {
        p.set_position(60);
    }

    for entry in WalkDir::new(staging_dir.path())
        .into_iter()
        .filter_map(std::result::Result::ok)
    {
        // copy_dir_all preserves symlinks into the store, so they must be
        // recorded here as well.
        if entry.file_type().is_file() || entry.file_type().is_symlink() {
            let rel_path = entry.path().strip_prefix(staging_dir.path())?;
            installed_files.push(format!(
                "${{pkgstore}}/{}",
                rel_path.to_string_lossy().replace('\\', "/")
            ));
        }
    }

    copy_dir_all(staging_dir.path(), &version_dir)?;

    finalize_installation(
        &version_dir,
        &metadata,
        scope,
        link_bins,
        pb,
        &mut installed_files
    )?;

    if let Some(p) = pb {
        p.set_position(100);
    } else {
        println!("{} Installation complete.", "Success:".green());
    }
    Ok((installed_files, BTreeMap::new()))
}

/// Finalizes the installation by creating backups, linking binaries,
/// and installing shell completions and application bundles.
fn finalize_installation(
    version_dir: &Path,
    metadata: &types::Package,
    scope: types::Scope,
    link_bins: bool,
    pb: Option<&indicatif::ProgressBar>,
    _installed_files: &mut Vec<String>
) -> Result<()> {
    // Create .zoiorig copies for 3-way merge support
    if let Some(backup_files) = &metadata.backup {
        for backup_file_rel in backup_files {
            let expanded_path = utils::expand_placeholders(
                backup_file_rel,
                version_dir,
                scope
            )?;
            // Backup paths in package metadata are relative to the package
            // store (version dir), so resolve them against it here.
            let backup_src = if Path::new(&expanded_path).is_absolute() {
                PathBuf::from(expanded_path)
            } else {
                version_dir.join(expanded_path)
            };

            if backup_src.exists() && backup_src.is_file() {
                let mut orig_path = backup_src.clone();
                let ext =
                    orig_path.extension().and_then(|s| s.to_str()).map_or_else(
                        || "zoiorig".to_string(),
                        |s| format!("{s}.zoiorig")
                    );
                orig_path.set_extension(ext);

                if let Err(e) = fs::copy(&backup_src, &orig_path)
                    && pb.is_none()
                {
                    eprintln!(
                        "Warning: failed to create .zoiorig for {}: {}",
                        backup_src.display(),
                        e
                    );
                }
            }
        }
    }

    if link_bins && let Some(bins) = &metadata.bins {
        let bin_root = get_bin_root(scope)?;
        fs::create_dir_all(&bin_root)?;

        let mut created_shims = Vec::new();
        let mut link_error: Option<String> = None;

        for bin_name in bins {
            let mut found_bin = false;
            for entry in WalkDir::new(version_dir)
                .into_iter()
                .filter_map(std::result::Result::ok)
            {
                if entry.file_type().is_file()
                    && entry.file_name().to_string_lossy() == *bin_name
                {
                    let link_path = bin_root.join(bin_name);

                    let zoi_exe = std::env::current_exe()?;
                    if let Err(e) =
                        zoi_core::utils::symlink_file(&zoi_exe, &link_path)
                    {
                        link_error = Some(e.to_string());
                        break;
                    }
                    created_shims.push(link_path);

                    if pb.is_none() {
                        println!("Created shim for: {}", bin_name.green());
                    }
                    found_bin = true;
                    break;
                }
            }
            if link_error.is_some() {
                break;
            }
            if !found_bin && pb.is_none() {
                eprintln!(
                    "Warning: could not find binary '{}' to link.",
                    bin_name.yellow()
                );
            }
        }

        if let Some(e) = link_error {
            for shim in created_shims {
                let _ = fs::remove_file(shim);
            }
            return Err(anyhow!("Failed to create shims: {e}"));
        }
    }

    let shell_dir = version_dir.join("shell");
    if shell_dir.exists() {
        for shell_entry in fs::read_dir(&shell_dir).map_err(|e| {
            anyhow!("Failed to read shell completions directory: {e}")
        })? {
            let shell_entry = shell_entry?;
            if !shell_entry.file_type()?.is_dir() {
                continue;
            }
            let shell_name =
                shell_entry.file_name().to_string_lossy().to_string();
            let completions_root = get_completions_root(scope, &shell_name)?;
            let pkg_completions_dir = completions_root.join(&metadata.name);
            fs::create_dir_all(&pkg_completions_dir)?;

            for file_entry in fs::read_dir(shell_entry.path()).map_err(|e| {
                anyhow!("Failed to read shell/{shell_name}/ directory: {e}")
            })? {
                let file_entry = file_entry?;
                if !file_entry.file_type()?.is_file() {
                    continue;
                }
                let filename =
                    file_entry.file_name().to_string_lossy().to_string();
                let store_path = file_entry.path();
                let link_path = pkg_completions_dir.join(&filename);
                create_completion_symlink(&store_path, &link_path)?;
                if pb.is_none() {
                    println!(
                        "Linked {} completion: {}",
                        shell_name.green(),
                        filename.cyan()
                    );
                }
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        let applications_dir = match scope {
            types::Scope::System => PathBuf::from("/Applications"),
            types::Scope::User => {
                let home_dir = zoi_core::utils::get_user_home()
                    .ok_or_else(|| anyhow!("Could not find home directory."))?;
                home_dir.join("Applications")
            }
            types::Scope::Project => {
                std::env::current_dir()?.join("Applications")
            }
        };

        let mut app_bundles = Vec::new();
        for entry in WalkDir::new(version_dir)
            .max_depth(2)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            if entry.file_type().is_dir()
                && entry.file_name().to_string_lossy().ends_with(".app")
            {
                app_bundles.push(entry.path().to_path_buf());
            }
        }

        if !app_bundles.is_empty() {
            fs::create_dir_all(&applications_dir)?;
            for app_path in app_bundles {
                if zoi_core::utils::command_exists("xattr") {
                    let _ = std::process::Command::new("xattr")
                        .arg("-r")
                        .arg("-d")
                        .arg("com.apple.quarantine")
                        .arg(&app_path)
                        .status();
                }

                let app_name = app_path.file_name().ok_or_else(|| {
                    anyhow!("App path has no filename: {:?}", app_path)
                })?;
                // `file_name` already yields a single component, but the bundle
                // name comes from inside the package archive, so pin the link
                // to the applications directory explicitly rather than relying
                // on that invariant holding upstream.
                let symlink_path = zoi_core::utils::safe_join(
                    &applications_dir,
                    Path::new(app_name)
                )?;

                if symlink_path.exists() {
                    let _ = fs::remove_file(&symlink_path);
                    let _ = fs::remove_dir_all(&symlink_path);
                }

                if std::os::unix::fs::symlink(&app_path, &symlink_path).is_ok()
                {
                    _installed_files.push(format!(
                        "${{applications}}/{}",
                        app_name.to_string_lossy().replace('\\', "/")
                    ));
                    if pb.is_none() {
                        println!(
                            "Linked {} to {}",
                            app_name.to_string_lossy().green(),
                            applications_dir.display()
                        );
                    }
                }
            }
        }
    }

    Ok(())
}

/// Extracts and installs a pooled ZPA package using its manifest
/// to map files from the pool to their final destinations.
fn extract_pooled_zpa(
    pooled_manifest: &types::PooledZpaManifest,
    unpack_path: &Path,
    scope: types::Scope,
    metadata: &types::Package,
    sub_packages: Option<Vec<String>>,
    link_bins: bool,
    pb: Option<&indicatif::ProgressBar>,
    yes: bool,
    registry_handle: &str
) -> Result<(Vec<String>, BTreeMap<String, String>)> {
    let version = metadata.version.as_ref().ok_or_else(|| {
        anyhow!(
            "Package '{}' is missing version field in its metadata.",
            metadata.name
        )
    })?;

    if pb.is_none() {
        println!(
            "Installing pooled package: {} v{} [{:?}]",
            metadata.name.cyan(),
            version.yellow(),
            scope
        );
    }

    let package_dir = local::get_package_dir(
        scope,
        registry_handle,
        &metadata.repo,
        &metadata.name
    )?;
    fs::create_dir_all(&package_dir)?;

    let staging_dir = tempfile::Builder::new()
        .prefix(".tmp-install-")
        .tempdir_in(&package_dir)?;

    let mut installed_files: Vec<String> = Vec::new();
    // Content digests recorded for post-install verification (`zoi package
    // verify`). Keyed by the same tracked path that goes into
    // installed_files.
    let mut file_digests: BTreeMap<String, String> = BTreeMap::new();
    let version_dir = package_dir.join(version);

    let subs_to_install = if let Some(subs) = sub_packages {
        subs
    } else if let Some(subs) = &metadata.sub_packages {
        if let Some(main_subs) = &metadata.main_subs {
            main_subs.clone()
        } else {
            subs.clone()
        }
    } else {
        vec![String::new()]
    };

    let pool_dir = unpack_path.join("pool");

    let mut conflicts = Vec::new();
    let mut owned_files = HashSet::new();

    // ${createpkgdir} resolves to the invocation directory, so its absolute
    // location is recorded at install time instead of the placeholder.
    // Otherwise cleanup from a different directory could not find (or worse,
    // could mis-target) these artifacts.
    let track_dest = |dest: &str| -> Result<String> {
        if dest.starts_with("${createpkgdir}") {
            Ok(expand_pooled_path(dest, staging_dir.path(), scope)?
                .to_string_lossy()
                .to_string())
        } else {
            Ok(dest.to_string())
        }
    };

    for sub in &subs_to_install {
        let sub_opt = if sub.is_empty() {
            None
        } else {
            Some(sub.as_str())
        };
        if let Ok(Some(manifest)) =
            local::is_package_installed(&metadata.name, sub_opt, scope)
        {
            owned_files.extend(manifest.installed_files);
        }

        if let Some(sub_mapping) = pooled_manifest.mappings.get(sub)
            && let Some(scope_mapping) = sub_mapping.scopes.get(&scope)
        {
            for mapped_file in &scope_mapping.files {
                let dest_path = expand_pooled_path(
                    &mapped_file.dest,
                    staging_dir.path(),
                    scope
                )?;
                // We only check conflicts for files that land outside the Zoi
                // store's staging area
                if !mapped_file.dest.starts_with("${pkgstore}")
                    && dest_path.exists()
                    && !owned_files.contains(&mapped_file.dest)
                    // Older manifests may have recorded the expanded form.
                    && !owned_files
                        .contains(&dest_path.to_string_lossy().to_string())
                {
                    conflicts.push(dest_path);
                }
            }
        }
    }

    if !conflicts.is_empty() {
        println!();
        println!("{}", "File Conflict Detected:".red().bold());
        println!(
            "The following files that this package wants to install already \
             exist on your system:"
        );
        for file in &conflicts {
            println!("- {}", file.display());
        }
        println!();

        if !utils::ask_for_confirmation(
            "Do you want to overwrite these files and continue with the \
             installation?",
            yes
        ) {
            return Err(anyhow!(
                "Installation aborted by user due to file conflicts."
            ));
        }
    }

    for sub in subs_to_install {
        let Some(sub_mapping) = pooled_manifest.mappings.get(&sub) else {
            if pb.is_none() {
                eprintln!(
                    "Warning: mapping for sub-package '{sub}' not found in \
                     archive, skipping."
                );
            }
            continue;
        };

        let Some(scope_mapping) = sub_mapping.scopes.get(&scope) else {
            if pb.is_none() {
                eprintln!(
                    "Warning: mapping for scope {scope:?} not found for \
                     sub-package '{sub}', skipping."
                );
            }
            continue;
        };

        // Step 1: Create directories
        for mapped_dir in &scope_mapping.dirs {
            let dest_path = expand_pooled_path(
                &mapped_dir.path,
                staging_dir.path(),
                scope
            )?;
            fs::create_dir_all(&dest_path)?;

            #[cfg(unix)]
            {
                if let Some(mode) = mapped_dir.mode {
                    use std::os::unix::fs::PermissionsExt;
                    fs::set_permissions(
                        &dest_path,
                        fs::Permissions::from_mode(mode)
                    )?;
                }
                if let (Some(owner), Some(group)) =
                    (&mapped_dir.owner, &mapped_dir.group)
                {
                    let _ = utils::set_path_owner(&dest_path, owner, group);
                }
            }
        }

        // Step 2: Extract files
        for mapped_file in &scope_mapping.files {
            let pool_file =
                utils::safe_join(&pool_dir, Path::new(&mapped_file.hash))?;
            if !pool_file.exists() {
                return Err(anyhow!("Pool file missing: {}", mapped_file.hash));
            }
            let expected_hash =
                mapped_file.hash.strip_prefix("sha256-").ok_or_else(|| {
                    anyhow!(
                        "Unsupported pool hash format: {}",
                        mapped_file.hash
                    )
                })?;
            let pool_entry = pooled_manifest
                .pool
                .get(&mapped_file.hash)
                .ok_or_else(|| {
                    anyhow!("Pool manifest entry missing: {}", mapped_file.hash)
                })?;
            if pool_file.metadata()?.len() != pool_entry.size {
                return Err(anyhow!(
                    "Pool file size does not match manifest: {}",
                    mapped_file.hash
                ));
            }
            let actual_hash =
                calculate_file_hash(&pool_file, HashAlgorithm::Sha256)?;
            if actual_hash != expected_hash {
                return Err(anyhow!(
                    "Pool file hash does not match manifest: {}",
                    mapped_file.hash
                ));
            }

            let dest_path = expand_pooled_path(
                &mapped_file.dest,
                staging_dir.path(),
                scope
            )?;

            if let Some(parent) = dest_path.parent() {
                fs::create_dir_all(parent)?;
            }

            fs::copy(&pool_file, &dest_path)?;

            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                fs::set_permissions(
                    &dest_path,
                    fs::Permissions::from_mode(mapped_file.mode)
                )?;
                if let (Some(owner), Some(group)) =
                    (&mapped_file.owner, &mapped_file.group)
                {
                    let _ = utils::set_path_owner(&dest_path, owner, group);
                }
            }

            let tracked = track_dest(&mapped_file.dest)?;
            file_digests.insert(tracked.clone(), mapped_file.hash.clone());
            installed_files.push(tracked);
        }

        // Step 3: Create symlinks
        for mapped_link in &scope_mapping.symlinks {
            let dest_path = expand_pooled_path(
                &mapped_link.link,
                staging_dir.path(),
                scope
            )?;

            if let Some(parent) = dest_path.parent() {
                fs::create_dir_all(parent)?;
            }

            if dest_path.exists() || dest_path.is_symlink() {
                fs::remove_file(&dest_path).ok();
            }

            // Resolve target placeholders if any
            let target = mapped_link.target.clone();

            utils::symlink_file(Path::new(&target), &dest_path)?;
            installed_files.push(track_dest(&mapped_link.link)?);
        }
    }

    // Finalize staging-to-store move
    fs::create_dir_all(&version_dir)?;
    copy_dir_all(staging_dir.path(), &version_dir)?;

    finalize_installation(
        &version_dir,
        metadata,
        scope,
        link_bins,
        pb,
        &mut installed_files
    )?;

    if let Some(p) = pb {
        p.set_position(100);
    }

    Ok((installed_files, file_digests))
}

/// Expands placeholders in a pooled path to their absolute filesystem paths.
fn expand_pooled_path(
    path: &str,
    staging_path: &Path,
    _scope: types::Scope
) -> Result<PathBuf> {
    let safe_join = |base: PathBuf, relative: &str| -> Result<PathBuf> {
        let relative_path = Path::new(relative);
        if !utils::is_safe_path(&base, relative_path) {
            return Err(anyhow!(
                "Pooled path escapes its destination root: {path}"
            ));
        }
        Ok(base.join(relative_path))
    };

    if let Some(rel) = path.strip_prefix("${pkgstore}/") {
        safe_join(staging_path.to_path_buf(), rel)
    } else if let Some(rel) = path.strip_prefix("${usrroot}/") {
        safe_join(zoi_core::sysroot::apply_sysroot(PathBuf::from("/")), rel)
    } else if let Some(rel) = path.strip_prefix("${usrhome}/") {
        let home_dir = zoi_core::utils::get_user_home()
            .ok_or_else(|| anyhow!("Home dir not found"))?;
        safe_join(home_dir, rel)
    } else if let Some(rel) = path.strip_prefix("${createpkgdir}/") {
        safe_join(std::env::current_dir()?, rel)
    } else {
        Err(anyhow!("Invalid pooled path placeholder: {path}"))
    }
}

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

    #[test]
    fn pooled_paths_should_not_escape_their_roots() {
        let staging =
            tempfile::tempdir().expect("staging directory should exist");

        assert!(
            expand_pooled_path(
                "${pkgstore}/../outside",
                staging.path(),
                types::Scope::User
            )
            .is_err()
        );
    }
}