#!/usr/bin/bash
set -eu

target_root="${1:-}"

if [ -z "$target_root" ] || [ "$target_root" = "/" ]; then
    echo "Invalid Calamares target root: ${target_root:-empty}" >&2
    exit 1
fi

if [ ! -d "$target_root/boot/efi" ]; then
    echo "EFI system partition is not mounted at $target_root/boot/efi" >&2
    exit 1
fi

mkdir -p "$target_root/usr/lib/tmpfiles.d" \
    "$target_root/var/lib/dbus" \
    "$target_root/boot/efi/EFI/Tuxenix" \
    "$target_root/boot/grub"

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

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

ensure_target_account() {
    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'
}

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

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

ensure_runtime_layout() {
    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

    mkdir -p "$target_root/etc/profile.d"
    cat > "$target_root/etc/profile.d/00-tuxenix-path.sh" <<'EOF'
# Make base admin tools available in text logins.
case ":$PATH:" in
    *:/usr/sbin:*) ;;
    *) PATH="/usr/sbin:$PATH" ;;
esac
case ":$PATH:" in
    *:/sbin:*) ;;
    *) PATH="/sbin:$PATH" ;;
esac
export PATH
EOF
    chmod 644 "$target_root/etc/profile.d/00-tuxenix-path.sh"

    cat > "$target_root/etc/resolv.conf" <<'EOF'
nameserver 1.1.1.1
nameserver 8.8.8.8
EOF
    chmod 644 "$target_root/etc/resolv.conf"
}

ensure_target_account
ensure_login_target
ensure_runtime_layout

install_dinit_grub_entry() {
    root_source="$(findmnt -n -o SOURCE --target "$target_root" 2>/dev/null | sed 's/\[.*$//' || true)"
    root_uuid=""
    root_partuuid=""
    root_fstype="$(findmnt -n -o FSTYPE --target "$target_root" 2>/dev/null || true)"
    kernel_path="$(find "$target_root/boot" -maxdepth 1 -type f -name 'vmlinuz*' -print -quit)"

    if [ -n "$root_source" ] && [ -b "$root_source" ]; then
        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)"
    fi

    if [ -z "$root_uuid" ] || [ -z "$root_fstype" ] || [ -z "$kernel_path" ]; then
        echo "Unable to create dinit GRUB entry: root or kernel details are missing." >&2
        exit 1
    fi

    case "$root_fstype" in
        ext2|ext3|ext4) grub_fs_module=ext2 ;;
        *) grub_fs_module="$root_fstype" ;;
    esac

    # The installed system currently has no initramfs. Linux resolves a GPT
    # PARTUUID itself, while filesystem UUID= lookup requires an initramfs.
    if [ -n "$root_partuuid" ]; then
        kernel_root="PARTUUID=$root_partuuid"
    else
        kernel_root="$root_source"
    fi

    kernel_basename="$(basename "$kernel_path")"
    dinit_grub="$target_root/etc/grub.d/09_tuxenix_dinit"
    cat > "$dinit_grub" <<EOF
#!/bin/sh
cat <<'DINIT_EOF'
menuentry "Tuxenix" {
    insmod part_gpt
    insmod search_fs_uuid
    insmod $grub_fs_module
    search --no-floppy --fs-uuid --set=root $root_uuid
    linux /boot/$kernel_basename root=$kernel_root rootfstype=$root_fstype rw rootwait init=/usr/sbin/dinit
}
DINIT_EOF
EOF
    chmod 755 "$dinit_grub"

    mkdir -p "$target_root/etc/default"
    cat > "$target_root/etc/default/grub" <<'EOF'
GRUB_DEFAULT=0
GRUB_TIMEOUT=8
GRUB_DISTRIBUTOR=Tuxenix
GRUB_CMDLINE_LINUX_DEFAULT=""
GRUB_CMDLINE_LINUX=""
EOF
}

install_dinit_grub_entry

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"

for mountpoint in dev proc sys run; do
    if ! mountpoint -q "$target_root/$mountpoint"; then
        mount --bind "/$mountpoint" "$target_root/$mountpoint"
    fi
done

if [ -d /sys/firmware/efi/efivars ] && [ -d "$target_root/sys/firmware/efi/efivars" ]; then
    mountpoint -q "$target_root/sys/firmware/efi/efivars" \
        || mount -t efivarfs efivarfs "$target_root/sys/firmware/efi/efivars" 2>/dev/null \
        || true
fi

if [ ! -s "$target_root/etc/machine-id" ]; then
    echo "Generating installed-system machine-id..."
    chroot "$target_root" dbus-uuidgen --ensure=/etc/machine-id
fi

custom_grub="$target_root/etc/grub.d/40_custom"
cat > "$custom_grub" <<'EOF'
#!/bin/sh
exec tail -n +3 $0
EOF

add_efi_chainloader() {
    title="$1"
    loader_path="$2"

    if [ ! -f "$target_root/boot/efi/$loader_path" ]; then
        return 0
    fi

    cat >> "$custom_grub" <<EOF

menuentry "$title" {
    insmod part_gpt
    insmod fat
    search --no-floppy --file --set=esp /$loader_path
    chainloader (\$esp)/$loader_path
}
EOF
}

add_efi_chainloader "Windows Boot Manager" "EFI/Microsoft/Boot/bootmgfw.efi"
add_efi_chainloader "Existing GRUB" "EFI/GRUB/grubx64.efi"
add_efi_chainloader "Ubuntu / Arch GRUB" "EFI/ubuntu/shimx64.efi"
add_efi_chainloader "Ubuntu / Arch GRUB fallback" "EFI/ubuntu/grubx64.efi"
add_efi_chainloader "Fedora GRUB" "EFI/fedora/shimx64.efi"
add_efi_chainloader "Fedora GRUB fallback" "EFI/fedora/grubx64.efi"

chmod 755 "$custom_grub"

esp="$target_root/boot/efi"
has_existing_bootloader=false
existing_bootloader="$(find "$esp/EFI" -mindepth 2 -maxdepth 3 -type f \( -iname '*.efi' -o -iname '*.EFI' \) \
    ! -path "$esp/EFI/Tuxenix/*" \
    ! -path "$esp/EFI/BOOT/*" \
    -print -quit 2>/dev/null || true)"

if [ -n "$existing_bootloader" ]; then
    has_existing_bootloader=true
fi

write_tuxenix_chainloader_entry() {
    cfg="$1"

    if [ ! -f "$cfg" ] || grep -q 'Tuxenix' "$cfg"; then
        return 0
    fi

    if ! grep -q '^[[:space:]]*menuentry[[:space:]]' "$cfg"; then
        return 0
    fi

    cat >> "$cfg" <<'EOF'

menuentry "Tuxenix" {
    insmod part_gpt
    insmod fat
    search --no-floppy --file --set=esp /EFI/Tuxenix/grubx64.efi
    chainloader ($esp)/EFI/Tuxenix/grubx64.efi
}
EOF
}

write_entry_dropin() {
    cat > "$esp/EFI/Tuxenix/grub-entry.cfg" <<'EOF'
menuentry "Tuxenix" {
    insmod part_gpt
    insmod fat
    search --no-floppy --file --set=esp /EFI/Tuxenix/grubx64.efi
    chainloader ($esp)/EFI/Tuxenix/grubx64.efi
}
EOF
}

echo "Installing GRUB EFI loader without firmware NVRAM writes..."
chroot "$target_root" grub-install \
    --target=x86_64-efi \
    --efi-directory=/boot/efi \
    --bootloader-id=Tuxenix \
    --no-nvram \
    --force

if [ "$has_existing_bootloader" = false ]; then
    echo "No existing EFI bootloader found; installing removable EFI fallback loader..."
    chroot "$target_root" grub-install \
        --target=x86_64-efi \
        --efi-directory=/boot/efi \
        --bootloader-id=Tuxenix \
        --removable \
        --no-nvram \
        --force
else
    echo "Existing EFI bootloader found; preserving EFI/BOOT fallback loader."
    write_entry_dropin
    for cfg in "$esp"/EFI/*/grub.cfg "$esp"/EFI/*/*.cfg; do
        [ -f "$cfg" ] || continue
        write_tuxenix_chainloader_entry "$cfg"
    done
fi

echo "Generating GRUB configuration..."
chroot "$target_root" grub-mkconfig -o /boot/grub/grub.cfg

if command -v efibootmgr >/dev/null 2>&1 && [ -d /sys/firmware/efi/efivars ]; then
    efi_output="$(efibootmgr 2>/dev/null || true)"
    old_order="$(awk -F': ' '/^BootOrder:/{print $2; exit}' <<< "$efi_output")"
    esp_source="$(findmnt -n -o SOURCE --target "$esp" 2>/dev/null || true)"
    esp_disk=""
    esp_part=""

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

    if [ -n "$esp_disk" ] && [ -n "$esp_part" ]; then
        efibootmgr -c -d "$esp_disk" -p "$esp_part" -L Tuxenix -l '\EFI\Tuxenix\grubx64.efi' || true
        efi_output="$(efibootmgr 2>/dev/null || true)"
        tuxenix_id="$(awk '/Tuxenix/{id=$1; sub(/^Boot/, "", id); sub(/\*.*/, "", id)} END{print id}' <<< "$efi_output")"
        if [ "$has_existing_bootloader" = true ] && [ -n "$old_order" ] && [ -n "$tuxenix_id" ]; then
            case ",$old_order," in
                *,"$tuxenix_id",*) efibootmgr -o "$old_order" || true ;;
                *) efibootmgr -o "$old_order,$tuxenix_id" || true ;;
            esac
        fi
    fi
fi

echo "GRUB bootloader install complete."
