#!/usr/bin/perl
# 
# TODO: check intel' backlight path too if generic is not found
# this script should have suid bit set and must have root owner :(

use strict;
use warnings "all";

my $arg = $ARGV[0];
my $step = 10; # measured in percents

sub fsread($);  # read 1-st line from file
sub fswrite(@); # write string to file

#my $prefix = "/sys/class/backlight/acpi_video0";
my $prefix = "/sys/class/backlight/intel_backlight";

my $brightnessfile = "$prefix/brightness";
my $maxbrightness = fsread("$prefix/max_brightness");
my $currbrightness = fsread("$prefix/brightness");

my $p = $maxbrightness / 100;
$step = int($step * $p);

if ( $arg eq "up" ) {
	if ($currbrightness != $maxbrightness) {
		my $projectedbrightness = $currbrightness + $step;

		if ($projectedbrightness > $maxbrightness) {
			$projectedbrightness = $maxbrightness;
		}

		fswrite($projectedbrightness, $brightnessfile);
	}
} elsif ( $arg eq "down" ) {
	if ($currbrightness != 0) {
		my $projectedbrightness = $currbrightness - $step;

		if ($projectedbrightness < 0) {
			$projectedbrightness = 0;
		}

		fswrite($projectedbrightness, $brightnessfile);
	}
}


sub fsread($) {
	my $fname = shift;
	open (F, $fname) || die "Unable to read $fname: $!\n";
	my $str = <F>;
	close F;
	return $str;
}

sub fswrite (@) {
	my $str = shift;
	my $fname = shift;
	open(OF, ">", $fname) || die "Unable to write $fname: $!\n";
	print OF $str;
	close OF;
}
