stout-install 0.2.1

Package installation for Homebrew-compatible bottles and source builds
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
//! Bottle extraction

use crate::error::{Error, Result};
use flate2::read::GzDecoder;
use memchr::memmem;
use rayon::prelude::*;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use tar::{Archive, EntryType};
use tracing::{debug, info, warn};

/// Extract a bottle tarball to the Cellar
///
/// Bottles are tarballs with structure: `<name>/<version>/...`
/// We extract to: `<cellar>/<name>/<version>/...`
pub fn extract_bottle(bottle_path: impl AsRef<Path>, cellar: impl AsRef<Path>) -> Result<PathBuf> {
    let bottle_path = bottle_path.as_ref();
    let cellar = cellar.as_ref();

    debug!(
        "Extracting {} to {}",
        bottle_path.display(),
        cellar.display()
    );

    let file = File::open(bottle_path)?;
    let decoder = GzDecoder::new(file);
    let mut archive = Archive::new(decoder);

    // Create cellar if it doesn't exist
    create_dir_all_force(cellar)?;

    let mut install_path: Option<PathBuf> = None;
    let mut hardlinks: Vec<(PathBuf, PathBuf)> = Vec::new();

    // Single-pass extraction: regular entries are extracted immediately,
    // hardlinks are collected and resolved in a post-pass. This is required
    // because tar entries stream from a gzip decoder — storing entries for
    // a second pass would consume and invalidate their data.
    for entry in archive.entries()? {
        let mut entry = entry?;
        let path = entry.path()?.to_path_buf();

        // Determine install path from the first entry
        if install_path.is_none() {
            if let Some(component) = path.components().next() {
                let pkg_name = component.as_os_str().to_string_lossy();
                // The path inside the tarball is like `wget/1.24.5/...`
                // We want to extract to `<cellar>/wget/1.24.5/...`
                if let Some(second) = path.components().nth(1) {
                    let version = second.as_os_str().to_string_lossy();
                    let dest_path = cellar.join(&*pkg_name).join(&*version);

                    // Remove existing directory (from previous failed/partial install)
                    if dest_path.exists() {
                        debug!("Removing existing directory: {}", dest_path.display());
                        std::fs::remove_dir_all(&dest_path)?;
                    }

                    install_path = Some(dest_path);
                }
            }
        }

        let dest = cellar.join(&path);

        match entry.header().entry_type() {
            EntryType::Link => {
                let link_target = entry.link_name()?.unwrap_or_default().into_owned();
                hardlinks.push((path, link_target));
            }
            EntryType::Directory => {
                create_dir_all_force(&dest)?;
            }
            _ => {
                // Create parent directories
                if let Some(parent) = dest.parent() {
                    create_dir_all_force(parent)?;
                }

                // Remove existing file/symlink (entry.unpack fails on existing files)
                if dest.exists() || dest.symlink_metadata().is_ok() {
                    if dest.is_dir() {
                        std::fs::remove_dir_all(&dest)?;
                    } else {
                        std::fs::remove_file(&dest)?;
                    }
                }

                entry.set_unpack_xattrs(false);
                entry.unpack(&dest)?;
            }
        }
    }

    // Post-pass: resolve hardlinks
    for (link_path, target_path) in hardlinks {
        let link_dest = cellar.join(&link_path);
        let target_dest = cellar.join(&target_path);

        if let Some(parent) = link_dest.parent() {
            create_dir_all_force(parent)?;
        }

        if link_dest.exists() || link_dest.symlink_metadata().is_ok() {
            std::fs::remove_file(&link_dest)?;
        }

        debug!(
            "Creating hardlink: {} -> {}",
            link_dest.display(),
            target_dest.display()
        );

        if let Err(e) = std::fs::hard_link(&target_dest, &link_dest) {
            warn!(
                "Failed to create hardlink {} -> {}: {}. Falling back to copy.",
                link_dest.display(),
                target_dest.display(),
                e
            );
            std::fs::copy(&target_dest, &link_dest)?;
        }
    }

    let install_path = install_path.ok_or_else(|| {
        Error::InvalidBottle("Could not determine install path from bottle".to_string())
    })?;

    info!("Extracted to {}", install_path.display());
    Ok(install_path)
}

/// Homebrew placeholder byte patterns used in bottle binaries and text files.
const HOMEBREW_MARKER: &[u8] = b"@@HOMEBREW_";
/// Check if a file is an ELF binary
fn is_elf_binary(path: &Path) -> bool {
    if let Ok(mut file) = File::open(path) {
        let mut magic = [0u8; 4];
        if file.read_exact(&mut magic).is_ok() {
            // ELF magic number: 0x7f 'E' 'L' 'F'
            return magic == [0x7f, b'E', b'L', b'F'];
        }
    }
    false
}

/// Check if a file is a Mach-O binary (macOS executable, dylib, or bundle)
fn is_macho_binary(path: &Path) -> bool {
    if let Ok(mut file) = File::open(path) {
        let mut magic = [0u8; 4];
        if file.read_exact(&mut magic).is_ok() {
            // Mach-O magic numbers (both endianness variants):
            // 0xfeedface / 0xcefaedfe — Mach-O 32-bit
            // 0xfeedfacf / 0xcffaedfe — Mach-O 64-bit
            // 0xcafebabe / 0xbebafeca — FAT / universal binary
            return matches!(
                magic,
                [0xfe, 0xed, 0xfa, 0xce]
                    | [0xce, 0xfa, 0xed, 0xfe]
                    | [0xfe, 0xed, 0xfa, 0xcf]
                    | [0xcf, 0xfa, 0xed, 0xfe]
                    | [0xca, 0xfe, 0xba, 0xbe]
                    | [0xbe, 0xba, 0xfe, 0xca]
            );
        }
    }
    false
}
/// Relocate ELF binary using patchelf
fn relocate_elf_binary(path: &Path, prefix: &str) -> Result<bool> {
    // Check if patchelf is available
    let patchelf = std::process::Command::new("patchelf")
        .arg("--version")
        .output();

    if patchelf.is_err() {
        // patchelf not available, skip with warning
        warn!(
            "patchelf not found - ELF binaries may not work correctly. \
             Install patchelf for proper binary relocation."
        );
        return Ok(false);
    }

    // Read current interpreter
    let output = std::process::Command::new("patchelf")
        .arg("--print-interpreter")
        .arg(path)
        .output();

    let interp = match output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
        _ => return Ok(false), // Not a dynamically linked executable
    };

    // Check if interpreter contains a placeholder
    if !interp.contains("@@HOMEBREW") && !interp.contains("linuxbrew") {
        return Ok(false);
    }

    // Compute new interpreter path
    let new_interp = if interp.contains("@@HOMEBREW_PREFIX@@") {
        interp.replace("@@HOMEBREW_PREFIX@@", prefix)
    } else if interp.contains("/home/linuxbrew/.linuxbrew") {
        interp.replace("/home/linuxbrew/.linuxbrew", prefix)
    } else {
        return Ok(false);
    };

    // Check if the new interpreter exists, if not use system ld
    let final_interp = if Path::new(&new_interp).exists() {
        new_interp
    } else {
        // Fall back to system dynamic linker
        let system_ld = find_system_ld();
        if let Some(ld) = system_ld {
            debug!("Using system linker {} instead of {}", ld, new_interp);
            ld
        } else {
            warn!("Cannot find suitable dynamic linker for {}", path.display());
            return Ok(false);
        }
    };

    // Set the new interpreter
    let result = std::process::Command::new("patchelf")
        .arg("--set-interpreter")
        .arg(&final_interp)
        .arg(path)
        .output();

    match result {
        Ok(o) if o.status.success() => {
            debug!(
                "Patched ELF interpreter: {} -> {}",
                path.display(),
                final_interp
            );
            Ok(true)
        }
        Ok(o) => {
            warn!(
                "patchelf failed for {}: {}",
                path.display(),
                String::from_utf8_lossy(&o.stderr)
            );
            Ok(false)
        }
        Err(e) => {
            warn!("patchelf error for {}: {}", path.display(), e);
            Ok(false)
        }
    }
}

/// Find the system dynamic linker
fn find_system_ld() -> Option<String> {
    let candidates = [
        "/lib64/ld-linux-x86-64.so.2",
        "/lib/ld-linux-x86-64.so.2",
        "/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2",
        "/lib/ld-linux-aarch64.so.1",
        "/lib/aarch64-linux-gnu/ld-linux-aarch64.so.1",
    ];

    for candidate in candidates {
        if Path::new(candidate).exists() {
            return Some(candidate.to_string());
        }
    }
    None
}

/// File extensions that are compressed or non-textual archives — these never
/// contain Homebrew placeholders and can be safely skipped during scanning.
const SCAN_SKIP_EXTENSIONS: &[&str] = &[
    "gz", "bz2", "xz", "zst", "zip", "tar", "png", "jpg", "jpeg", "gif", "ico", "bmp", "tiff",
    "webp", "ttf", "otf", "woff", "woff2", "pyc", "pyo", "class", "jar", "db", "sqlite", "wasm",
];
/// Relocate Homebrew placeholders in the extracted bottle
///
/// Replaces @@HOMEBREW_PREFIX@@ and similar placeholders with actual paths
pub fn relocate_bottle(install_path: impl AsRef<Path>, prefix: impl AsRef<Path>) -> Result<usize> {
    let install_path = install_path.as_ref();
    let prefix = prefix.as_ref();
    let cellar = prefix.join("Cellar");

    let prefix_str = prefix.to_string_lossy();
    let cellar_str = cellar.to_string_lossy();

    // Walk all files, then process in parallel
    let files = walkdir(install_path)?;
    let relocated_count = AtomicUsize::new(0);

    // Clean up orphaned .stout-reloc temp files from interrupted runs
    for path in &files {
        if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
            if name.ends_with(".stout-reloc") {
                let _ = fs::remove_file(path);
            }
        }
    }

    files.par_iter().for_each(|path| {
        let metadata = match fs::symlink_metadata(path) {
            Ok(m) => m,
            Err(_) => return,
        };

        if !metadata.is_file() {
            return;
        }

        if is_elf_binary(path) {
            if relocate_elf_binary(path, &prefix_str).unwrap_or(false) {
                relocated_count.fetch_add(1, Ordering::Relaxed);
            }
        } else if is_macho_binary(path) {
            #[cfg(target_os = "macos")]
            if relocate_macho_binary(path, &prefix_str, &cellar_str).unwrap_or(false) {
                relocated_count.fetch_add(1, Ordering::Relaxed);
            }
        } else if relocate_file(path, &prefix_str, &cellar_str).unwrap_or(false) {
            relocated_count.fetch_add(1, Ordering::Relaxed);
        }
    });

    let count = relocated_count.load(Ordering::Relaxed);
    if count > 0 {
        debug!("Relocated {} files", count);
    }

    Ok(count)
}

/// Recursively walk a directory and return all file paths
fn walkdir(dir: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    walkdir_recursive(dir.as_ref(), &mut files)?;
    Ok(files)
}

fn walkdir_recursive(dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            let ft = fs::symlink_metadata(&path)?.file_type();
            if ft.is_dir() {
                walkdir_recursive(&path, files)?;
            } else if !ft.is_symlink() || !path.is_dir() {
                files.push(path);
            }
        }
    }
    Ok(())
}

/// Relocate a single file, replacing Homebrew placeholders
fn relocate_file(path: &Path, prefix: &str, cellar: &str) -> Result<bool> {
    let _guard = match WriteGuard::acquire(path) {
        Ok(g) => g,
        Err(e) => {
            warn!("Could not make file writable: {}: {}", path.display(), e);
            return Ok(false);
        }
    };

    // Read the file
    let mut file = match File::open(path) {
        Ok(f) => f,
        Err(e) => {
            warn!(
                "Could not open file for relocation: {}: {}",
                path.display(),
                e
            );
            return Ok(false);
        }
    };

    let mut contents = Vec::new();
    if let Err(e) = file.read_to_end(&mut contents) {
        warn!(
            "Could not read file for relocation: {}: {}",
            path.display(),
            e
        );
        return Ok(false);
    }
    drop(file);

    // Check if file contains any placeholders
    if memmem::find(&contents, HOMEBREW_MARKER).is_none() {
        return Ok(false);
    }

    // Perform replacements
    let library = format!("{}/Library", prefix);
    let java_home = std::process::Command::new("/usr/libexec/java_home")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "/Library/Java/JavaVirtualMachines".to_string());
    let pairs: &[(&[u8], &[u8])] = &[
        (PH_PREFIX, prefix.as_bytes()),
        (PH_CELLAR, cellar.as_bytes()),
        (PH_LIBRARY, library.as_bytes()),
        (PH_REPOSITORY, prefix.as_bytes()),
        (PH_JAVA, java_home.as_bytes()),
    ];

    let mut new_contents = contents;
    let mut modified = false;

    for &(needle, replacement) in pairs {
        let after = replace_bytes(&new_contents, needle, replacement);
        if after != new_contents {
            modified = true;
            new_contents = after;
        }
    }

    if modified {
        atomic_write(path, &new_contents)?;
        debug!("Relocated: {}", path.display());
    }

    Ok(modified)
}

/// Replace all occurrences of a byte pattern in a byte vector
///
/// Note: This does NOT pad with nulls, so the file size may change.
/// This works for both text files and binaries where the placeholder
/// is part of a longer path (e.g., @@HOMEBREW_PREFIX@@/lib/ld.so).
fn replace_bytes(haystack: &[u8], needle: &[u8], replacement: &[u8]) -> Vec<u8> {
    if needle.is_empty() {
        return haystack.to_vec();
    }

    let finder = memmem::Finder::new(needle);
    let mut result = Vec::with_capacity(haystack.len());
    let mut start = 0;

    while let Some(pos) = finder.find(&haystack[start..]) {
        result.extend_from_slice(&haystack[start..start + pos]);
        result.extend_from_slice(replacement);
        start += pos + needle.len();
    }

    result.extend_from_slice(&haystack[start..]);
    result
}

#[cfg(target_os = "macos")]
fn replace_bytes_padded(haystack: &[u8], needle: &[u8], replacement: &[u8]) -> Option<Vec<u8>> {
    if needle.is_empty() {
        return Some(haystack.to_vec());
    }
    if replacement.len() > needle.len() {
        return None;
    }

    let finder = memmem::Finder::new(needle);
    let mut result = Vec::with_capacity(haystack.len());
    let mut start = 0;

    while let Some(pos) = finder.find(&haystack[start..]) {
        result.extend_from_slice(&haystack[start..start + pos]);
        result.extend_from_slice(replacement);
        // Null-pad to preserve the original needle length
        let pad_len = needle.len() - replacement.len();
        result.extend(std::iter::repeat_n(0, pad_len));
        start += pos + needle.len();
    }

    result.extend_from_slice(&haystack[start..]);
    Some(result)
}
/// Remove an installed package from the Cellar
pub fn remove_package(cellar: impl AsRef<Path>, name: &str, version: &str) -> Result<()> {
    let package_path = cellar.as_ref().join(name).join(version);

    if !package_path.exists() {
        return Err(Error::PackageNotFound(format!("{}/{}", name, version)));
    }

    debug!("Removing {}", package_path.display());
    std::fs::remove_dir_all(&package_path)?;

    // Remove parent directory if empty
    let parent = cellar.as_ref().join(name);
    if parent.read_dir()?.next().is_none() {
        std::fs::remove_dir(&parent)?;
    }

    info!("Removed {}-{}", name, version);
    Ok(())
}

const PH_REPOSITORY: &[u8] = b"@@HOMEBREW_REPOSITORY@@";
const PH_JAVA: &[u8] = b"@@HOMEBREW_JAVA@@";

/// RAII guard that restores file permissions on drop.
struct WriteGuard<'a> {
    path: &'a Path,
    perms: Option<std::fs::Permissions>,
}

/// Check if a file should be skipped during scanning.
fn should_skip_scan(path: &Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| SCAN_SKIP_EXTENSIONS.contains(&e))
        .unwrap_or(false)
}

#[cfg(target_os = "macos")]
fn parse_macho_load_commands(path: &Path) -> Result<Vec<MachLoadCommand>> {
    let output = std::process::Command::new("otool")
        .arg("-l")
        .arg(path)
        .output()
        .map_err(Error::Io)?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut commands = Vec::new();

    let mut current_cmd = None;

    for line in stdout.lines() {
        let trimmed = line.trim();

        if let Some(rest) = trimmed.strip_prefix("cmd ") {
            current_cmd = Some(rest.trim().to_string());
        } else if let Some(rest) = trimmed.strip_prefix("name ") {
            if let Some(cmd) = &current_cmd {
                let name = rest.split('(').next().unwrap_or("").trim().to_string();
                match cmd.as_str() {
                    "LC_ID_DYLIB" => commands.push(MachLoadCommand::DylibId(name)),
                    "LC_LOAD_DYLIB" | "LC_LOAD_WEAK_DYLIB" => {
                        commands.push(MachLoadCommand::LoadDylib(name))
                    }
                    _ => {}
                }
            }
        } else if let Some(rest) = trimmed.strip_prefix("path ") {
            if let Some(cmd) = &current_cmd {
                if cmd == "LC_RPATH" {
                    let rpath = rest.split('(').next().unwrap_or("").trim().to_string();
                    commands.push(MachLoadCommand::Rpath(rpath));
                }
            }
        }
    }

    Ok(commands)
}

impl<'a> WriteGuard<'a> {
    /// Make a file writable, returning a guard that restores permissions on drop.
    fn acquire(path: &'a Path) -> Result<Self> {
        let metadata = fs::metadata(path).map_err(Error::Io)?;
        let perms = metadata.permissions();
        let was_readonly = perms.mode() & 0o200 == 0;
        if was_readonly {
            let mut writable = perms.clone();
            writable.set_mode(perms.mode() | 0o200);
            fs::set_permissions(path, writable)?;
        }
        Ok(Self {
            path,
            perms: if was_readonly { Some(perms) } else { None },
        })
    }
}

const PH_PREFIX: &[u8] = b"@@HOMEBREW_PREFIX@@";

const PH_LIBRARY: &[u8] = b"@@HOMEBREW_LIBRARY@@";

impl Drop for WriteGuard<'_> {
    fn drop(&mut self) {
        if let Some(perms) = self.perms.take() {
            let _ = fs::set_permissions(self.path, perms);
        }
    }
}

const PH_CELLAR: &[u8] = b"@@HOMEBREW_CELLAR@@";

#[cfg(target_os = "macos")]
enum MachLoadCommand {
    /// LC_ID_DYLIB — the dylib's own identifier
    DylibId(String),
    /// LC_LOAD_DYLIB / LC_LOAD_WEAK_DYLIB — linked library
    LoadDylib(String),
    /// LC_RPATH — runtime search path
    Rpath(String),
}

/// Write data to a file atomically: write to a temp file, then rename.
/// Preserves the original file's permissions.
fn atomic_write(path: &Path, contents: &[u8]) -> Result<()> {
    let tmp = path.with_extension(".stout-reloc");

    (|| -> std::io::Result<()> {
        let mut file = File::create(&tmp)?;
        file.write_all(contents)?;
        file.sync_all()?;
        Ok(())
    })()
    .map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        Error::Io(e)
    })?;

    if let Ok(meta) = fs::metadata(path) {
        let _ = fs::set_permissions(&tmp, meta.permissions());
    }

    fs::rename(&tmp, path).map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        Error::Io(e)
    })?;

    Ok(())
}

#[cfg(target_os = "macos")]
fn replace_homebrew_placeholders(s: &str, prefix: &str, cellar: &str) -> String {
    let library = format!("{}/Library", prefix);
    s.replace("@@HOMEBREW_PREFIX@@", prefix)
        .replace("@@HOMEBREW_CELLAR@@", cellar)
        .replace("@@HOMEBREW_LIBRARY@@", &library)
        .replace("@@HOMEBREW_REPOSITORY@@", prefix)
        .replace("@@HOMEBREW_JAVA@@", &java_home_path())
}

#[cfg(target_os = "macos")]
fn java_home_path() -> String {
    std::process::Command::new("/usr/libexec/java_home")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "/Library/Java/JavaVirtualMachines".to_string())
}

#[cfg(target_os = "macos")]
fn relocate_macho_binary(path: &Path, prefix: &str, cellar: &str) -> Result<bool> {
    let _guard = match WriteGuard::acquire(path) {
        Ok(g) => g,
        Err(e) => {
            warn!(
                "Could not make Mach-O binary writable: {}: {}",
                path.display(),
                e
            );
            return Ok(false);
        }
    };

    // Read file and check for any Homebrew placeholders
    let mut file = match File::open(path) {
        Ok(f) => f,
        Err(e) => {
            warn!("Could not open Mach-O binary: {}: {}", path.display(), e);
            return Ok(false);
        }
    };
    let mut contents = Vec::new();
    if let Err(e) = file.read_to_end(&mut contents) {
        warn!("Could not read Mach-O binary: {}: {}", path.display(), e);
        return Ok(false);
    }
    drop(file);

    if memmem::find(&contents, HOMEBREW_MARKER).is_none() {
        return Ok(false);
    }

    let mut modified = false;

    // Step 1: Fix load commands using install_name_tool.
    // Must run before byte replacement so otool can parse the original paths.
    match parse_macho_load_commands(path) {
        Ok(load_commands) => {
            for lc in &load_commands {
                let old_path = match lc {
                    MachLoadCommand::DylibId(p)
                    | MachLoadCommand::LoadDylib(p)
                    | MachLoadCommand::Rpath(p) => p.as_str(),
                };

                if !old_path.contains("@@HOMEBREW_") {
                    continue;
                }

                let new_path = replace_homebrew_placeholders(old_path, prefix, cellar);

                let result = match lc {
                    MachLoadCommand::DylibId(_) => std::process::Command::new("install_name_tool")
                        .args(["-id", &new_path])
                        .arg(path)
                        .output(),
                    MachLoadCommand::LoadDylib(_) => {
                        std::process::Command::new("install_name_tool")
                            .args(["-change", old_path, &new_path])
                            .arg(path)
                            .output()
                    }
                    MachLoadCommand::Rpath(_) => {
                        // Rpath needs delete + add (no in-place replace)
                        let del = std::process::Command::new("install_name_tool")
                            .args(["-delete_rpath", old_path])
                            .arg(path)
                            .output();
                        if del.as_ref().is_ok_and(|o| o.status.success()) {
                            std::process::Command::new("install_name_tool")
                                .args(["-add_rpath", &new_path])
                                .arg(path)
                                .output()
                        } else {
                            del
                        }
                    }
                };

                match result {
                    Ok(o) if o.status.success() => {
                        debug!("install_name_tool: {} → {}", old_path, new_path);
                        modified = true;
                    }
                    Ok(o) => {
                        warn!(
                            "install_name_tool failed for {}: {}",
                            path.display(),
                            String::from_utf8_lossy(&o.stderr)
                        );
                    }
                    Err(e) => {
                        warn!("Could not run install_name_tool: {}", e);
                    }
                }
            }
        }
        Err(e) => {
            warn!(
                "Could not parse load commands for {}: {}",
                path.display(),
                e
            );
        }
    }

    // Step 2: Re-read the file if install_name_tool modified it on disk.
    let post_contents = if modified {
        let mut file = File::open(path)?;
        let mut buf = Vec::new();
        file.read_to_end(&mut buf)?;
        buf
    } else {
        contents
    };

    // Step 3: Fix remaining embedded strings with null-padded replacement.
    // install_name_tool handles structured load commands, but some binaries
    // (Python, Ruby) embed the prefix in their __TEXT segment for sys.prefix.
    // LC_DYLD_ENVIRONMENT entries are also handled here.
    let library = format!("{}/Library", prefix);
    let pairs: &[(&[u8], &[u8])] = &[
        (PH_PREFIX, prefix.as_bytes()),
        (PH_CELLAR, cellar.as_bytes()),
        (PH_LIBRARY, library.as_bytes()),
        (PH_REPOSITORY, prefix.as_bytes()),
    ];

    let mut new_contents = post_contents;
    let mut embedded_modified = false;

    for &(needle, replacement) in pairs {
        if replacement.len() > needle.len() {
            // Longer replacements (CELLAR, LIBRARY on ARM Mac) are handled by
            // install_name_tool for load commands. For embedded strings, we
            // can't safely expand without parsing Mach-O structure.
            if memmem::find(&new_contents, needle).is_some() {
                debug!(
                    "Skipping longer placeholder {:?} in embedded strings of {} \
                     (expected to be handled by install_name_tool)",
                    std::str::from_utf8(needle).unwrap_or("???"),
                    path.display()
                );
            }
            continue;
        }

        let Some(next) = replace_bytes_padded(&new_contents, needle, replacement) else {
            continue;
        };

        if next != new_contents {
            new_contents = next;
            embedded_modified = true;
        }
    }

    if embedded_modified {
        atomic_write(path, &new_contents)?;
        debug!(
            "Relocated embedded strings in Mach-O binary: {}",
            path.display()
        );
        modified = true;
    }

    // Step 4: Ad-hoc re-sign to fix invalidated code signature.
    // install_name_tool also invalidates signatures, so this covers both steps.
    if modified {
        match std::process::Command::new("codesign")
            .args(["--force", "--sign", "-"])
            .arg(path)
            .output()
        {
            Ok(o) if o.status.success() => {
                debug!("Ad-hoc re-signed: {}", path.display());
            }
            Ok(o) => {
                warn!(
                    "codesign failed for {}: {}",
                    path.display(),
                    String::from_utf8_lossy(&o.stderr)
                );
            }
            Err(e) => {
                warn!("Could not run codesign for {}: {}", path.display(), e);
            }
        }
    }

    Ok(modified)
}

/// Scan a directory for files containing unresolved @@HOMEBREW_*@@ placeholders.
///
/// Scans all files including binaries and dylibs so they can be reported.
/// Both text files and Mach-O binaries are fixed via `relocate_bottle`.
pub fn scan_unrelocated_files(install_path: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
    let install_path = install_path.as_ref();
    let mut unrelocated = Vec::new();

    let finder = memmem::Finder::new(HOMEBREW_MARKER);

    for entry in walkdir(install_path)? {
        let metadata = match fs::symlink_metadata(&entry) {
            Ok(m) => m,
            Err(_) => continue,
        };

        if !metadata.is_file() || should_skip_scan(&entry) {
            continue;
        }

        if let Ok(mut file) = File::open(&entry) {
            let mut buf = Vec::new();
            if file.read_to_end(&mut buf).is_ok() && finder.find(&buf).is_some() {
                unrelocated.push(entry);
            }
        }
    }

    Ok(unrelocated)
}

/// Scan all packages in a cellar directory for unresolved placeholders in parallel.
///
/// Returns a vec of (package_name, package_path, affected_file_count) tuples.
pub fn scan_cellar_unrelocated(
    cellar_packages: &[crate::cellar::CellarPackage],
) -> Vec<(String, PathBuf, usize)> {
    cellar_packages
        .par_iter()
        .filter_map(|pkg| {
            scan_unrelocated_files(&pkg.path)
                .ok()
                .filter(|files| !files.is_empty())
                .map(|files| (pkg.name.clone(), pkg.path.clone(), files.len()))
        })
        .collect()
}

/// Create directory and all parents, removing any conflicting files in the path
///
/// Unlike std::fs::create_dir_all, this will remove files that exist where
/// directories need to be created.
pub(crate) fn create_dir_all_force(path: &Path) -> std::io::Result<()> {
    // First try the normal way
    if path.exists() && path.is_dir() {
        return Ok(());
    }

    // Collect all ancestors that need to be checked
    let mut to_create: Vec<&Path> = Vec::new();
    let mut current = path;

    // Find the first ancestor that exists
    while !current.exists() {
        to_create.push(current);
        match current.parent() {
            Some(p) if !p.as_os_str().is_empty() => current = p,
            _ => break,
        }
    }
    to_create.reverse();

    // Check each ancestor - if any is a file, remove it
    for dir_path in &to_create {
        if dir_path.symlink_metadata().is_ok() && !dir_path.is_dir() {
            debug!(
                "Removing conflicting file at {}: need directory",
                dir_path.display()
            );
            std::fs::remove_file(dir_path)?;
        }
    }

    // Now create directories
    std::fs::create_dir_all(path)
}