#!/bin/bash
set -e

HOOK=/etc/geninitrd.d/pre-install/dkms-zfs.sh
ORIGINAL=/var/lib/pkgtools/setup/setup.01.mkinitrd

if [ -z "${KERNEL_VERSION:-}" ]; then
    echo "ERROR: KERNEL_VERSION was not provided by geninitrd."
    exit 1
fi

if [ ! -x "$HOOK" ]; then
    echo "ERROR: ZFS DKMS hook is missing or not executable: $HOOK"
    exit 1
fi

if [ ! -x "$ORIGINAL" ]; then
    echo "ERROR: Original initrd setup script is missing: $ORIGINAL"
    exit 1
fi

echo "Building ZFS DKMS module for kernel $KERNEL_VERSION..."
export KERNEL_VERSION
"$HOOK"

echo "=== ZFS diagnostic before initrd generation ==="
echo "KERNEL_VERSION=$KERNEL_VERSION"

echo "--- Installed ZFS and SPL modules ---"
ls -l "/lib/modules/$KERNEL_VERSION/extra/"*zfs* \
      "/lib/modules/$KERNEL_VERSION/extra/"*spl* 2>&1 || true

echo "--- Running depmod ---"
/sbin/depmod -a "$KERNEL_VERSION"

#echo "--- Checking ZFS module resolution ---"
#/sbin/modinfo -k "$KERNEL_VERSION" zfs || true

echo "=== End ZFS diagnostic ==="

echo "ZFS DKMS hook completed. Generating initrd..."
exec "$ORIGINAL"
