#!/bin/sh

kldstat -n nvidia > /dev/null 2>&1; RESULT=$?
if [ ${RESULT} -eq 0 ]; then
	kldunload -n nvidia > /dev/null 2>&1; RESULT=$?
	if [ ${RESULT} -ne 0 ]; then
		echo 'ERROR: Failed to unload the NVIDIA module!'
		echo 'ERROR: Is nvidia.ko in use?'
		exit 1;
	fi
fi

kldload nvidia > /dev/null 2>&1 ; RESULT=$?
if [ ${RESULT} -ne 0 ]; then
	echo 'ERROR: Failed to load the NVIDIA module!'
	exit 1;
fi

grep nvidia_load /boot/loader.conf > /dev/null 2>&1; RESULT=$?
if [ ${RESULT} -eq 0 ]; then
	# Present.
	sed -e s/nvidia_load.*/nvidia_load=\"YES\"/g -i.orig /boot/loader.conf
else
	# Not present.
	echo 'nvidia_load="YES"' >> /boot/loader.conf
fi
