#!/usr/bin/perl -pi
# cpufreq_defaults
# tweak cpufreqd conf for your system
# idea is based on Debians postinst bash script by Mattia Dongili
# 
# Licence: GPL v2
# Danny Tholen (c) 2004
# 
# 
sub cat_ { local *F; open F, $_[0] or return; my @l = <F>; wantarray ? @l : join '', @l }

my $freq = 0;
my $cpufreqd_pm = 0;
my $cpufreqd_dir = "/sys/devices/system/cpu/cpu0/cpufreq/";


if ( -d "$cpufreqd_dir" || -f "/proc/cpufreq" ) {
    # the order is important, some machines may have apm emulation:
    if ( -e "/proc/pmu" ) {
        $cpufreqd_pm='pmu';
    }
    elsif ( -e "/proc/apm" ) {
        $cpufreqd_pm='apm';
    }
    elsif ( -e "/proc/acpi" ) { 
        $cpufreqd_pm='acpi';
    }
    if ( !$cpufreqd_pm ) {
        print STDERR "No powermanagement found, exiting...\n";
	exit 1;
    }	
    #set the pm type:
    s/(pm_type=)\s*acpi(.*)/\1$cpufreqd_pm\2/
    }
else {
    print STDERR "No kernel support for cpufreq, exiting...\n";
    exit 1;
    }
		

# on 2.6 only:

if ( -d $cpufreqd_dir ) {
    my $max_speed = int(cat_("$cpufreqd_dir/cpuinfo_max_freq"));
    my $min_speed = int(cat_("$cpufreqd_dir/cpuinfo_min_freq"));

    #if minfreq and maxfreq are percentages, convert them to absolute values
    #if value is lower than minimum freq (or higher than max), take that instead
    if (/s*minfreq=\s*(\d+)%/) {
        $freq = int($max_speed/100*$1);
	if ($freq < $min_speed) {
	    $freq = $min_speed;
	}
        if ($freq > $max_speed) {
	    $freq = $max_speed;
        }	    
        s/(minfreq=)\s*\d+%/\1$freq/
    }
    elsif (/s*maxfreq=\s*(\d+)%/) {
	$freq = int($max_speed/100*$1);
	if ($freq < $min_speed) {
	    $freq = $min_speed;
	}
	if ($freq > $max_speed) {
	    $freq = $max_speed;
	}
        s/(maxfreq=)\s*\d+%/\1$freq/
    }
}
