#! /usr/bin/perl -w 

use strict;

	my $first_arg = shift (@ARGV);
	
	if ($first_arg =~ /^button\/lid$/) {
		system ('/usr/X11R6/bin/xset -display :0 dpms force off');
	}
	
	if ($first_arg =~ /^button\/sleep$/) {
		shift (@ARGV);
		shift (@ARGV);
		if (check_ignore ('/etc/acpi/flags/suspend')) {
			clear_ignore ('/etc/acpi/flags/suspend');
		} else {
			set_ignore ('/etc/acpi/flags/suspend');
			system ('/usr/X11R6/bin/xset -display :0 dpms force off');
			system ('echo 1 > /proc/acpi/sleep');
			
		}
	}

	if ($first_arg =~ /^ac_adapter$/) {
		handle_power_change ();
	}

############################################################
sub handle_power_change {
	#I can't make this module autoload, so I'll try loading 
	#when I get an event. 
#Obsolete. Now using cupfreq. 
#	system ('insmod -f processor');

	open (ACSTATUS, '</proc/acpi/ac_adapter/AC/state');
	my $state = <ACSTATUS>;
	close (ACSTATUS);

	chomp $state;

	if ($state =~ /^state:\s+on-line$/) {
		#if ac is on-line, make sure the processor is at top speed.
#For the intel processor.o binary
#		system ('echo "1" > /proc/acpi/processor/CPU0/performance');
#For the built in, new, cpufrequency kernel
		system ('echo 0:1700000:1700000:performance > /proc/cpufreq');

		#turn power managment on the hard drive off.
		system ('hdparm -B 255 /dev/hda');
	} else {
		#if ac is off-line, make sure the processor is at some slower speed (just set it here).
#For the intel processor.o binary
#		system ('echo "6" > /proc/acpi/processor/CPU0/performance');
#For the built in, new, cpufrequency kernel
		system ('echo 0:600000:600000:powersave > /proc/cpufreq');
		#turn power managment on the hard drive to the most agressive level.
		system ('hdparm -B 1 /dev/hda');
	}

}
############################################################
sub check_ignore {
	my $name = shift;

	if (-e $name) {
		return 1;
	} else {
		return 0;
	}

}
############################################################
sub set_ignore {
	my $name = shift;

	system ("touch $name");
}
############################################################
sub clear_ignore {
	my $name = shift;

	system ("rm $name");
}
############################################################

