#!/usr/bin/env bash

# Exit immediately if a command exits with a non-zero status
set -euo pipefail

# Visual colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0;3m' # No Color
INFO='\033[0;34m[INFO]\033[0m'

echo -e "${INFO} Starting OpenZFS installation for Fedora 44..."

# 1. Ensure the script is run as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: Please run this script as root or with sudo.${NC}"
    exit 1
fi

# 2. Check if Secure Boot is enabled
if mokutil --sb-state 2>/dev/null | grep -q "SecureBoot enabled"; then
    echo -e "${RED}Warning: Secure Boot is ENABLED.${NC}"
    echo "Out-of-tree kernel modules like ZFS will fail to load unless you manually sign them."
    echo "It is highly recommended to disable Secure Boot in your BIOS before proceeding."
    read -p "Do you want to continue anyway? (y/N): " choice
    if [[ ! "$choice" =~ ^[Yy]$ ]]; then
        echo "Installation aborted."
        exit 1
    fi
fi

# 3. Clean up conflicting legacy packages
echo -e "${INFO} Removing legacy zfs-fuse if present..."
if rpm -q zfs-fuse &>/dev/null; then
    rpm -e --nodeps zfs-fuse
fi

# 4. Resolve the distribution release name and install the official OpenZFS repository
echo -e "${INFO} Fetching system release token..."
DIST_TAG=$(rpm --eval "%{dist}") # Generates '.fc44'

echo -e "${INFO} Adding OpenZFS repository for ${DIST_TAG}..."
REPO_URL="https://zfsonlinux.org/fedora/zfs-release-3-1${DIST_TAG}.noarch.rpm"
dnf install -y "$REPO_URL"

# 5. Install required kernel development files matching the active kernel
echo -e "${INFO} Installing matching kernel-devel and headers..."
CURRENT_KERNEL=$(uname -r | awk -F'-' '{print $1}')
dnf install -y kernel-devel-"${CURRENT_KERNEL}"

# 6. Install the main OpenZFS packages
echo -e "${INFO} Installing OpenZFS package (this compiles the DKMS module, please wait)..."
dnf install -y zfs

# 7. Configure automatic module loading at boot
echo -e "${INFO} Configuring system to load ZFS module at boot..."
mkdir -p /etc/modules-load.d
echo "zfs" > /etc/modules-load.d/zfs.conf

# 8. Attempt to load the module immediately
echo -e "${INFO} Loading ZFS kernel module..."
if modprobe zfs; then
    echo -e "${GREEN}Success! OpenZFS has been installed and loaded successfully.${NC}"
    echo -e "Installed version: $(zfs version)"
else
    echo -e "${RED}Error: Failed to load the ZFS kernel module.${NC}"
    echo "If you recently updated your kernel, you may need to reboot your system first."
    exit 1
fi

