#!/bin/sh -eu

CPU=
GOVERNOR_AC_ON=
GOVERNOR_AC_OFF=

. shell-error

[ -f /etc/sysconfig/cpufreq-simple ] && . /etc/sysconfig/cpufreq-simple

CPUFREQ=/sys/devices/system/cpu/cpu0/cpufreq
GOVERNORS="$CPUFREQ/scaling_available_governors"
cmd="${1-}"

get_ac_state()
{
	local state_file
	if [ -d /proc/acpi/ac_adapter/ ]; then
		state_file="$(find /proc/acpi/ac_adapter/ -name state | head -1)"
		if [ -n "$state_file" -a -r "$state_file" ]; then
			sed 's;^state:[[:blank:]]*;;' "$state_file" | head -1
		fi
	else
		# Treat unknown AC state as on-line
		echo "on-line"
	fi
}

init_command()
{
	local ac_state="$(get_ac_state)"
	[ -n "$ac_state" ] && echo "ac-$ac_state"
}

set_cpufreq()
{
	# getopt seems overkill right now
	if [ "$1" = "-g" -a -n "$2" ]; then
		grep -Fq -- "$2" "$GOVERNORS" || modprobe "cpufreq_$2"
	fi
	for i in $CPU; do
		cpufreq-set -c "$i" "$@"
	done
}

if ! [ -f "$CPUFREQ/scaling_governor" -a -f "$GOVERNORS" ]; then
	fatal "system not configured correctly for CPU frequency scaling"
fi

[ -n "$cmd" ] || cmd="$(init_command)"

if [ -z "$cmd" ]; then
	fatal "couldn't apply initial settings"
fi

[ -n "$CPU" ] || CPU="$(grep '^processor' /proc/cpuinfo | sed 's/^.*: //;' | tr '\n' ' ')"
if [ -z "$CPU" ]; then
	fatal "couldn't detect the number of CPUs"
fi

case "$cmd" in
	ac-on-line)
		[ -z "$GOVERNOR_AC_ON" ] || set_cpufreq -g "$GOVERNOR_AC_ON"
		;;
	ac-off-line)
		[ -z "$GOVERNOR_AC_OFF" ] || set_cpufreq -g "$GOVERNOR_AC_OFF"
		;;
	*)
		fatal "unknown command: '$cmd'"
		;;
esac
