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

requested_target_root="${1:-}"
confirmation="${TUXENIX_CONFIRM_BOOTLOADER_INSTALL:-}"

case "$requested_target_root" in
    /*) ;;
    *)
        echo "Calamares target root must be an absolute path: ${requested_target_root:-empty}" >&2
        exit 1
        ;;
esac

requested_normalized="$requested_target_root"
while [ "${requested_normalized%/}" != "$requested_normalized" ]; do
    requested_normalized="${requested_normalized%/}"
done

target_root="$(readlink -f -- "$requested_target_root" 2>/dev/null || true)"
if [ -z "$target_root" ] || [ "$target_root" = "/" ] || [ ! -d "$target_root" ]; then
    echo "Invalid Calamares target root: ${requested_target_root:-empty}" >&2
    exit 1
fi

if [ -L "$requested_target_root" ] || [ "$target_root" != "$requested_normalized" ]; then
    echo "Calamares target root must be canonical and must not contain symlink components." >&2
    exit 1
fi

if ! mountpoint -q -- "$target_root" \
    || [ "$(findmnt -rn -M "$target_root" -o TARGET 2>/dev/null || true)" != "$target_root" ]; then
    echo "Calamares target root is not a dedicated mount point: $target_root" >&2
    exit 1
fi

if [ "$confirmation" != "YES" ]; then
    echo "Refusing to install the EFI bootloader without installer confirmation." >&2
    exit 1
fi

esp_path="$target_root/boot/efi"
esp="$(readlink -f -- "$esp_path" 2>/dev/null || true)"
if [ -L "$target_root/boot" ] || [ -L "$esp_path" ] \
    || [ -z "$esp" ] || [ "$esp" != "$esp_path" ] || [ ! -d "$esp" ]; then
    echo "EFI mount path is missing, non-canonical, or contains a symlink: $esp_path" >&2
    exit 1
fi

if ! mountpoint -q -- "$esp" \
    || [ "$(findmnt -rn -M "$esp" -o TARGET 2>/dev/null || true)" != "$esp" ]; then
    echo "EFI system partition is not mounted exactly at $esp" >&2
    exit 1
fi

root_source="$(findmnt -rn -M "$target_root" -o SOURCE 2>/dev/null | sed 's/\[.*$//' || true)"
esp_source="$(findmnt -rn -M "$esp" -o SOURCE 2>/dev/null | sed 's/\[.*$//' || true)"
root_fstype="$(findmnt -rn -M "$target_root" -o FSTYPE 2>/dev/null || true)"
esp_fstype="$(findmnt -rn -M "$esp" -o FSTYPE 2>/dev/null || true)"
kernel_path="$(find "$target_root/boot" -maxdepth 1 -type f -name 'vmlinuz*tuxenix*' -print -quit)"

if [ -z "$root_source" ] || [ ! -b "$root_source" ]; then
    echo "Unable to identify the selected Tuxenix root partition." >&2
    exit 1
fi

if [ -z "$esp_source" ] || [ ! -b "$esp_source" ]; then
    echo "Unable to identify the selected EFI system partition." >&2
    exit 1
fi

root_device="$(readlink -f -- "$root_source" 2>/dev/null || true)"
esp_device="$(readlink -f -- "$esp_source" 2>/dev/null || true)"
if [ -z "$root_device" ] || [ ! -b "$root_device" ] \
    || [ -z "$esp_device" ] || [ ! -b "$esp_device" ] \
    || [ "$root_device" = "$esp_device" ]; then
    echo "The root and EFI selections do not resolve to two different partitions." >&2
    exit 1
fi

host_root_source="$(findmnt -rn -M / -o SOURCE 2>/dev/null | sed 's/\[.*$//' || true)"
host_root_device="$(readlink -f -- "$host_root_source" 2>/dev/null || true)"
if [ -n "$host_root_device" ] && [ "$root_device" = "$host_root_device" ]; then
    echo "Refusing to install over the running live system root device." >&2
    exit 1
fi

if [ "$root_fstype" != "ext4" ]; then
    echo "The selected Tuxenix root partition was not formatted as ext4: $root_source ($root_fstype)" >&2
    exit 1
fi

case "$esp_fstype" in
    vfat|fat|fat32) ;;
    *)
        echo "The selected EFI partition is not FAT32/vfat: $esp_source ($esp_fstype)" >&2
        exit 1
        ;;
esac

if [ -z "$root_fstype" ] || [ -z "$kernel_path" ]; then
    echo "Unable to find the installed root filesystem or Tuxenix kernel." >&2
    exit 1
fi

root_partuuid="$(blkid -s PARTUUID -o value "$root_source" 2>/dev/null || true)"
esp_partuuid="$(blkid -s PARTUUID -o value "$esp_source" 2>/dev/null || true)"
limine_efi="$target_root/usr/share/limine/BOOTX64.EFI"

if [ ! -s "$limine_efi" ]; then
    echo "Limine EFI executable is missing from the installed system: $limine_efi" >&2
    exit 1
fi

ensure_line() {
    file="$1"
    pattern="$2"
    line="$3"

    touch "$file"
    if ! grep -Eq "$pattern" "$file"; then
        printf '%s\n' "$line" >> "$file"
    fi
}

ensure_target_runtime() {
    if [ ! -x "$target_root/usr/sbin/dinit" ]; then
        echo "Installed root is missing dinit." >&2
        exit 1
    fi

    mkdir -p "$target_root/usr/lib/tmpfiles.d"         "$target_root/var/lib/dbus"         "$target_root/etc/profile.d"

    ensure_line "$target_root/etc/group" '^messagebus:'         'messagebus:x:18:'
    ensure_line "$target_root/etc/passwd" '^messagebus:'         'messagebus:x:18:18:System Message Bus:/run/dbus:/bin/false'

    rm -f "$target_root/usr/sbin/init"
    ln -snf dinit "$target_root/usr/sbin/init"

    if [ -d "$target_root/usr/lib/modules" ] && [ ! -e "$target_root/lib/modules" ]; then
        mkdir -p "$target_root/lib"
        ln -snf ../usr/lib/modules "$target_root/lib/modules"
    fi

    cat > "$target_root/usr/lib/tmpfiles.d/tuxenix-dbus.conf" <<'EOF'
d /run/dbus 0755 messagebus messagebus -
L /var/lib/dbus/machine-id - - - - /etc/machine-id
EOF
    ln -snf /etc/machine-id "$target_root/var/lib/dbus/machine-id"
    chmod 755 "$target_root/var/lib/dbus"
}

# Revalidate the mount immediately before invoking the EFI writer.
if [ "$(findmnt -rn -M "$esp" -o SOURCE 2>/dev/null | sed 's/\[.*$//')" != "$esp_source" ]; then
    echo "EFI mount changed after validation; refusing to install bootloader files." >&2
    exit 1
fi

ensure_target_runtime
helper_dir="$(dirname -- "$(readlink -f -- "$0")")"
python3 "$helper_dir/tuxenix-efi-install.py" \
    "$target_root" "$esp" "$kernel_path" "$limine_efi" \
    "$esp_source" "$esp_partuuid" "$root_partuuid"
sync
