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

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

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 wipe the existing 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_uuid="$(blkid -s UUID -o value "$root_source" 2>/dev/null || true)"
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 [ -z "$root_uuid" ]; then
    echo "The selected root partition has no filesystem UUID." >&2
    exit 1
fi

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"
}

ensure_target_runtime

install -d -m 1777 "$target_root/tmp"

kernel_basename="$(basename "$kernel_path")"
if [ -n "$root_partuuid" ]; then
    kernel_root="PARTUUID=$root_partuuid"
else
    kernel_root="$root_source"
fi

config_tmp="$(mktemp "$target_root/tmp/tuxenix-limine.XXXXXX")"
cleanup() {
    rm -f "$config_tmp"
}
trap cleanup EXIT

cat > "$config_tmp" <<EOF
timeout: 5
default_entry: 1
remember_last_entry: yes
term_font_scale: 2x2

/Tuxenix 1-LTS
    protocol: linux
    path: uuid($root_uuid):/boot/$kernel_basename
    cmdline: root=$kernel_root rootfstype=$root_fstype rw rootwait init=/usr/sbin/dinit
EOF
chmod 600 "$config_tmp"

echo "WARNING: wiping every existing EFI bootloader file from $esp_source"
echo "Installing Limine as the only bootloader for this EFI partition."

verified_esp="$(readlink -f -- "$esp_path" 2>/dev/null || true)"
verified_esp_source="$(findmnt -rn -M "$esp" -o SOURCE 2>/dev/null | sed 's/\[.*$//' || true)"
if [ "$verified_esp" != "$esp" ] || ! mountpoint -q -- "$esp" \
    || [ "$verified_esp_source" != "$esp_source" ]; then
    echo "EFI mount changed after validation; refusing to wipe bootloader files." >&2
    exit 1
fi

rm -rf -- "$esp/EFI"
rm -rf -- "$target_root/boot/grub"
mkdir -p "$esp/EFI/BOOT"
install -m 0644 "$limine_efi" "$esp/EFI/BOOT/BOOTX64.EFI"
install -m 0644 "$config_tmp" "$esp/EFI/BOOT/limine.conf"

if ! cmp -s "$limine_efi" "$esp/EFI/BOOT/BOOTX64.EFI"; then
    echo "Limine EFI executable verification failed after copying." >&2
    exit 1
fi

esp_parent="$(lsblk -no PKNAME "$esp_source" 2>/dev/null || true)"
esp_part="$(lsblk -no PARTN "$esp_source" 2>/dev/null || true)"
esp_disk=""
if [ -n "$esp_parent" ]; then
    esp_disk="/dev/$esp_parent"
fi

if command -v efibootmgr >/dev/null 2>&1     && [ -d /sys/firmware/efi/efivars ]     && [ -n "$esp_partuuid" ]; then
    efi_output="$(efibootmgr -v 2>/dev/null || true)"
    while IFS= read -r line; do
        case "$line" in
            Boot[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]*)
                if printf '%s\n' "$line" | grep -Fqi "$esp_partuuid"; then
                    entry_id="$(printf '%s\n' "$line" | sed -n 's/^Boot\([0-9A-Fa-f]\{4\}\).*/\1/p')"
                    if [ -n "$entry_id" ]; then
                        echo "Removing old EFI entry Boot$entry_id for the selected EFI partition."
                        efibootmgr -b "$entry_id" -B || true
                    fi
                fi
                ;;
        esac
    done <<< "$efi_output"

    if [ -n "$esp_disk" ] && [ -n "$esp_part" ]; then
        efibootmgr             -c             -d "$esp_disk"             -p "$esp_part"             -L "Tuxenix (Limine)"             -l '\EFI\BOOT\BOOTX64.EFI'             || echo "Firmware entry creation failed; the standard EFI fallback path remains installed." >&2
    fi
fi

cat > "$target_root/etc/tuxenix-bootloader" <<EOF
bootloader=limine
efi_partition=$esp_source
efi_path=/EFI/BOOT/BOOTX64.EFI
root_partition=$root_source
EOF
chmod 644 "$target_root/etc/tuxenix-bootloader"

sync
trap - EXIT
cleanup

echo "Limine bootloader install complete."
echo "Existing bootloader files on $esp_source were wiped as confirmed in the installer."
