#!/bin/sh
# softperfect-ramdisk-troubleshoot — interactive troubleshooter for
# the SoftPerfect RAM Disk daemon and kernel module.
#
# When the GUI starts and can't reach the daemon, it spawns this script
# with no TTY; the script then re-launches itself in a terminal emulator
# so the user sees the output and prompts. When run from a terminal
# directly, the TTY check passes and the troubleshoot logic runs in place.

CHECK=/usr/lib/softperfect-ramdisk/sprd-module-check
MOK=/usr/sbin/softperfect-ramdisk-mok-setup

# Returns 0 if UEFI Secure Boot is enabled. Reads the EFI variable
# directly so we don't depend on mokutil being installed.
sb_enabled() {
	set -- /sys/firmware/efi/efivars/SecureBoot-*
	[ -e "$1" ] || return 1
	# 4-byte attribute header + 1-byte value at offset 4.
	[ "$(od -An -j4 -N1 -tu1 "$1" 2>/dev/null | tr -d ' ')" = "1" ]
}

if [ ! -t 0 ]; then
	for term in xdg-terminal-exec gnome-terminal konsole xfce4-terminal mate-terminal lxterminal alacritty kitty xterm; do
		if command -v "$term" >/dev/null 2>&1; then
			case "$term" in
			xdg-terminal-exec|kitty)      exec "$term" "$0" ;;
			gnome-terminal|mate-terminal) exec "$term" -- "$0" ;;
			*)                            exec "$term" -e "$0" ;;
			esac
		fi
	done
	echo "No supported terminal emulator found." >&2
	exit 1
fi

echo "SoftPerfect RAM Disk troubleshooter"
echo "==================================="
echo

STATE=$("$CHECK" 2>/dev/null)
[ -n "$STATE" ] || STATE="unknown"
echo "Kernel module: $STATE"

if systemctl is-active --quiet ramdiskd 2>/dev/null; then
	DAEMON=active
elif systemctl is-failed --quiet ramdiskd 2>/dev/null; then
	DAEMON=failed
else
	DAEMON=inactive
fi
echo "Daemon:        $DAEMON"
echo

case "$STATE" in
loaded)
	if [ "$DAEMON" = active ]; then
		cat <<EOF
Everything looks healthy. If the GUI still can't connect, the daemon
socket may have wrong permissions. Check:

    ls -la /run/ramdiskd.sock

The socket should be mode 0666.
EOF
	else
		cat <<EOF
The kernel module is loaded but the daemon isn't running.
Start it with:

    sudo systemctl start ramdiskd
    sudo systemctl status ramdiskd

If it keeps failing, check the logs:

    sudo journalctl -u ramdiskd -n 50
EOF
		echo
		printf "Try starting the daemon now? [y/N] "
		read -r REPLY
		case "$REPLY" in
		[Yy]*)
			sudo systemctl start ramdiskd
			sleep 1
			systemctl status ramdiskd --no-pager -n 5
			;;
		esac
	fi
	;;
needs_mok)
	cat <<EOF
Secure Boot is enabled and the kernel module isn't signed by a key
your firmware trusts.

The setup wizard generates a Machine Owner Key, signs the module with
it, and stages the public key for enrolment. You'll reboot twice:
once into the firmware's MokManager to enrol, once for the signed
module to load.
EOF
	if ! command -v mokutil >/dev/null 2>&1; then
		cat <<EOF

The wizard uses 'mokutil', which isn't installed on this system. Install
it first:

  Debian/Ubuntu:  sudo apt install mokutil
  RHEL/Fedora:    sudo dnf install mokutil
  openSUSE:       sudo zypper install mokutil

Then re-run this troubleshooter.
EOF
	else
		echo
		printf "Run the setup wizard now? [y/N] "
		read -r REPLY
		case "$REPLY" in
		[Yy]*) sudo "$MOK" ;;
		esac
	fi
	;;
not_built)
	cat <<EOF
The kernel module hasn't been built for the running kernel — usually
because matching kernel headers aren't installed.

  Debian/Ubuntu: sudo apt install linux-headers-\$(uname -r)
  RHEL/Fedora:   sudo dnf install kernel-devel

Then rebuild the module:

    sudo dkms install -m sprd -v 1.0
EOF
	if sb_enabled; then
		cat <<EOF

NOTE: Secure Boot is enabled on this system. After the module builds,
the firmware won't trust it until you enroll a Machine Owner Key.
Re-run this troubleshooter when the module shows as 'needs_mok' to
walk through that step.
EOF
	fi
	;;
other:*)
	cat <<EOF
The kernel module failed to load with an unexpected error:

  ${STATE#other:}

Check the kernel log for more detail:

    dmesg | tail -30

If this is reproducible, please report it to info@softperfect.com
with the dmesg output.
EOF
	;;
*)
	echo "Unable to determine module state. Make sure SoftPerfect RAM Disk"
	echo "is correctly installed (sprd-module-check should be at $CHECK)."
	;;
esac

echo
printf "Press Enter to close... "
read -r _
