#!/bin/bash
#
# nvidiablctl v0.2
#
# Copyright (c) 2011, Piotr Karbowski <piotr.karbowski@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
#   list of conditions and the following disclaimer in the documentation and/or other
#   materials provided with the distribution.
# * Neither the name of the Piotr Karbowski nor the names of its contributors may be
#   used to endorse or promote products derived from this software without specific
#   prior written permission.

backlights_path='/sys/class/backlight/nvidia_backlight'
max_brightness="$(< ${backlights_path}/max_brightness)"
current_brightness="$(< ${backlights_path}/actual_brightness)"

adjust_brightness() {
	if [ "$1" -gt "${max_brightness}" ]; then
		new_value="${max_brightness}"
	elif [ "$1" -lt '0' ]; then
		new_value="0"
	else
		new_value="$1"
	fi
	echo "${new_value}" > "${backlights_path}/brightness"
}

printhelp() {
	name="${0##*/}"
	echo " * ${name} v0.1

	${name} up
		brightness +10

	${name} down
		brightness -10

	${name} full
		full brightness

	${name} off
		turn off screen (brightness 0)

	${name} set <n>
		set brightness to <n>
"
}

case "$1" in
	up)
		adjust_brightness "$((${current_brightness}+10))"
	;;
	down)
		adjust_brightness "$((${current_brightness}-10))"
	;;
	off)
		adjust_brightness '0'
	;;
	full)
		adjust_brightness "${max_brightness}"
	;;
	set)
		if [ -n "$2" ] && [[ "$2" =~ ^[0-9]+$ ]]; then
			adjust_brightness "$2"
		else
			echo "set need numeric second argument."; exit 1
		fi
	;;
	*)
		printhelp; exit 1
	;;
esac
