#!/bin/sh
# /etc/kernel/postinst.d/zz-htx301 — installed by htx301-libpal.
# Runs automatically whenever a new kernel is installed (apt upgrade, HWE roll, etc.).
# If this package bundles a prebuilt htx301.ko for the kernel being installed, activate it
# into that kernel's module tree so the driver "just works" after the upgrade WITHOUT a deb
# reinstall.
#
# The kernel hook contract passes the new kernel version as $1 (and its image path as $2).
set -e
KVER="$1"
[ -n "$KVER" ] || exit 0
PREBUILT_DIR=/usr/lib/htx301/prebuilt
KO="${PREBUILT_DIR}/${KVER}/htx301.ko"

if [ ! -f "$KO" ]; then
  # Binary-only coverage: this kernel is outside the prebuilt set. Say so LOUDLY.
  # An earlier version exited 0 in silence here, which meant a customer who upgraded onto
  # an uncovered ABI lost the driver on next boot with no warning anywhere -- their last
  # signal was a successful `apt upgrade`. A hook must not fail the kernel install, so we
  # still exit 0, but the operator now gets a message in the apt output.
  echo "htx301-libpal: WARNING: no prebuilt htx301.ko for kernel ${KVER}." >&2
  echo "  The HTX301 driver will NOT load after booting ${KVER}." >&2
  echo "  This package ships prebuilt modules for a fixed kernel set; ${KVER} is not in it." >&2
  echo "  Install an htx301-libpal build that covers ${KVER}, or boot a covered kernel." >&2
  exit 0
fi

DEST="/lib/modules/${KVER}/updates"
mkdir -p "$DEST"
cp "$KO" "${DEST}/htx301.ko"
depmod -a "${KVER}" || true
echo "htx301-libpal: activated prebuilt htx301.ko for kernel ${KVER}"
exit 0
