#!/bin/bash
set -e

DKMS=/usr/sbin/dkms
KERNEL_VERSION=${KERNEL_VERSION:-}

if [ -z "$KERNEL_VERSION" ]; then
    echo "ERROR: KERNEL_VERSION is not set."
    exit 1
fi

KERNEL_SOURCE="/usr/src/linux-${KERNEL_VERSION}"
MODULE_DIR="/lib/modules/$KERNEL_VERSION"

if [ ! -f "$KERNEL_SOURCE/Makefile" ]; then
    echo "ERROR: Kernel sources for $KERNEL_VERSION are missing."
    exit 1
fi

ZFS_VERSION=$("$DKMS" status 2>/dev/null |
    sed -n 's|^zfs/\([^,]*\),.*|\1|p' |
    sort -Vu | tail -n 1)

if [ -z "$ZFS_VERSION" ]; then
    echo "ERROR: No ZFS version found in DKMS."
    exit 1
fi

find_zfs_module() {
    find "$MODULE_DIR" -type f \
        \( -name 'zfs.ko' -o -name 'zfs.ko.*' \) -print -quit 2>/dev/null
}

ZFS_MODULE=$(find_zfs_module)

if [ -n "$ZFS_MODULE" ]; then
    echo "ZFS module already exists: $ZFS_MODULE"
    exit 0
fi

echo "Forcing ZFS $ZFS_VERSION rebuild and reinstall for kernel $KERNEL_VERSION..."

"$DKMS" build -m zfs -v "$ZFS_VERSION" -k "$KERNEL_VERSION" \
    --kernelsourcedir "$KERNEL_SOURCE" --force

"$DKMS" install -m zfs -v "$ZFS_VERSION" -k "$KERNEL_VERSION" \
    --kernelsourcedir "$KERNEL_SOURCE" --force

depmod -a "$KERNEL_VERSION"

ZFS_MODULE=$(find_zfs_module)

if [ -z "$ZFS_MODULE" ]; then
    echo "ERROR: ZFS module is still missing for kernel $KERNEL_VERSION."
    exit 1
fi

echo "ZFS module successfully installed: $ZFS_MODULE"
