#!/usr/bin/env bash
set -euo pipefail

project_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
tools_directory="$project_root/Linux/.tools/fakeroot"
fakeroot_binary="$tools_directory/usr/bin/fakeroot"
fakeroot_library="$tools_directory/usr/lib/x86_64-linux-gnu/libfakeroot"
fakeroot_script="$tools_directory/usr/bin/fakeroot-sysv"
faked_binary="$tools_directory/usr/bin/faked-sysv"
preload_library="$fakeroot_library/libfakeroot-sysv.so"

if [[ ! -x "$fakeroot_binary" ]]; then
    download_directory="$project_root/Linux/.tools/fakeroot-download"
    mkdir -p "$download_directory" "$tools_directory"
    echo "Lade fakeroot und libfakeroot aus den Ubuntu-Paketquellen"
    (
        cd "$download_directory"
        apt-get download fakeroot libfakeroot
    )
    while IFS= read -r package; do
        dpkg-deb --extract "$package" "$tools_directory"
    done < <(find "$download_directory" -maxdepth 1 -type f -name '*.deb' -print)
fi

if [[ ! -x "$fakeroot_binary" && -x "$fakeroot_script" && -x "$faked_binary" && -f "$preload_library" ]]; then
    printf '#!/bin/sh\nexec "%s" -f "%s" -l "%s" "$@"\n' \
        "$fakeroot_script" "$faked_binary" "$preload_library" > "$fakeroot_binary"
    chmod +x "$fakeroot_binary"
fi

if [[ ! -x "$fakeroot_binary" || ! -f "$preload_library" ]]; then
    echo "Die projektlokale fakeroot-Installation ist unvollständig." >&2
    exit 1
fi

export PATH="$tools_directory/usr/bin:$PATH"
export LD_LIBRARY_PATH="$fakeroot_library:${LD_LIBRARY_PATH:-}"
fakeroot true
echo "Projektlokales fakeroot geprüft: $fakeroot_binary"
printf '%s\n' "$tools_directory"
