#!/usr/bin/env bash

#
# Troubleshoot the nvidia_bl/mbp_nvidia_bl setup
# Copyright (c) 2008-2010 Mario Schwalbe <schwalbe@inf.tu-dresden.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
NAME=${0##*/}

# determine which driver to check
DRIVER=${NAME%-diagnostics}
DRIVER=${DRIVER//-/_}

# print header line
echo "----------=[ verifying $DRIVER ]=----------"

# print kernel version
KERNEL=$(uname -r)
echo "* Kernel version: $KERNEL"

# print loaded graphics drivers
echo -n "* Graphics drivers loaded: "
for d in nouveau lbm-nouveau nvidia ; do
	if lsmod | grep -qE "^$d[[:space:]]+" ; then
		echo -n "$d "
	fi
done
echo

# check whether the driver is correctly installed
for f in /lib/modules/$KERNEL/updates/dkms/$DRIVER.ko \
		/lib/modules/$KERNEL/kernel/drivers/video/backlight/$DRIVER.ko ; do
	if [ -e $f ] ; then
		echo "* Driver installed as: $f"
		DRIVER_INSTALLED=1
		break
	fi
done

if [ -z "$DRIVER_INSTALLED" ] ; then
	echo "$NAME: Driver $DRIVER is not installed."
	exit 1
fi

# check for some options
if [ ! -f /etc/X11/xorg.conf ] ; then
	echo "* No custom xorg.conf found: OK"
elif ! grep '^[^#]*EnableBrightnessControl.*' /etc/X11/xorg.conf ; then
	echo "* No old options in xorg.conf: OK"
else
	echo "* 'EnableBrightnessControl' option found in /etc/X11/xorg.conf: Please remove."
fi

# check whether the driver is loaded and load it if requested
if ! lsmod | grep -q $DRIVER ; then
	if [ "$1" = --load ] ; then
		if sudo modprobe $DRIVER > /dev/null 2>&1 ; then
			DRIVER_LOADED=1
		else
			echo "$NAME: Couldn't load driver $DRIVER. The kernel said:"
			tail /var/log/kern.log | grep $DRIVER
			exit 1
		fi
	else
		echo "$NAME: Driver $DRIVER is not loaded."
		exit 1
	fi
fi

# check whether the sysfs interface is present
if [ "$DRIVER" = nvidia_bl ] ; then
	SYSFS=/sys/class/backlight/nvidia_backlight
elif [ "$DRIVER" = mbp_nvidia_bl ] ; then
	SYSFS=/sys/class/backlight/mbp_backlight
fi

if [ ! -d "$SYSFS" ] ; then
	echo "$NAME: No display backlight sysfs interface found."
	if [ -n "$DRIVER_LOADED" ] ; then
		sudo rmmod $DRIVER > /dev/null 2>&1
	fi
	exit 1
fi

# try to change brightness
MAX=$(cat $SYSFS/max_brightness)
let MED="$MAX / 2"
MIN=0

for b in $MIN $MED $MAX ; do
	echo "* Setting brightness to: $b"
	echo $b | sudo tee "$SYSFS/brightness" > /dev/null
	sleep 1
done

# cleanup
if [ -n "$DRIVER_LOADED" ] ; then
	sudo rmmod $DRIVER > /dev/null 2>&1
fi

# ***** end of source *****

