#!/bin/sh
# sprd-module-check — report the state of the RAM Disk kernel module.
#
# Prints one of: loaded | needs_mok | not_built | other:<detail>
# Exit codes:    0      | 1         | 2         | 3
#
# Callable as root (modprobe path, distinguishes specific load failures)
# or as a regular user (heuristic path using /sys/firmware/efi state).

# Already loaded?
if grep -q '^sprd[[:space:]]' /proc/modules 2>/dev/null; then
	echo loaded
	exit 0
fi

# Module file installed for the running kernel?
if ! modinfo sprd >/dev/null 2>&1; then
	echo not_built
	exit 2
fi

# Non-root: modprobe returns EPERM before even attempting, so the
# error string doesn't reveal why the kernel rejected the module.
# Fall back to: built but not loaded + Secure Boot enabled means the
# auto-load (systemd-modules-load) was rejected for signature reasons.
if [ "$(id -u)" != 0 ]; then
	sb=$(od -An -j4 -N1 -tu1 /sys/firmware/efi/efivars/SecureBoot-* 2>/dev/null | tr -d ' ')
	if [ "$sb" = "1" ]; then
		echo needs_mok
		exit 1
	fi
	echo "other:run as root for details"
	exit 3
fi

# Root path: try to load and parse the kernel's response.
err=$(modprobe sprd 2>&1)
rc=$?
if [ "$rc" = 0 ]; then
	echo loaded
	exit 0
fi

case "$err" in
*"Key was rejected"*|*"key was rejected"*|\
*"Required key"*|*"required key"*|\
*"module verification failed"*|\
*"PKCS#7"*|\
*"not signed"*|\
*"Lockdown"*|*"lockdown"*)
	echo needs_mok
	exit 1
	;;
esac

echo "other:$err"
exit 3
