#!/usr/bin/env bash
# $Id$

# Allows user to change CPU governor from within gnome
# Copyright (C) 2005 Meethune Bhowmick (meethune@oss-institute.org)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, 
# Boston, MA  02110-1301, USA.

# 1) Depends on sys-power/cpufrequtils
# 2) You need sudo access for cpufreq-set and id
# 3) This command will return a list of valid governors
#       ${GOVINFO} | grep governors | sed 's/^.*\: //;s/, /\n/g'

GOVINFO=$(which cpufreq-info 2>/dev/null)
GOVSET=$(which cpufreq-set 2>/dev/null)
if [ -z ${GOVINFO} ] || [ -z ${GOVSET} ]
then
    zenity --error --text "Couldn't find governor utilities."
    exit 1
fi

# Try and get sudo password
SUDOPASS=""
SUDO="sudo -S"
SUID=$(echo ${SUDOPASS} | ${SUDO} id -u)
RETRIES=0
while [ "${SUID}" != "0" ] 
do
	SUDOPASS=$(zenity --entry --title="Need sudo password"\
			--text="Enter Password:" --hide-text)
	if [ ${?} == 1 ]
	then
		exit 1
	fi
	RETRIES=$(expr ${RETRIES} + 1)
	if [ ${RETRIES} == 3 ]
	then
		zenity --error --text "Unable to authenticate sudo password."
		exit 1
	fi
	SUID=$(echo ${SUDOPASS} | ${SUDO} id -u)
done

while [ -z ${GOV} ] # Make sure user selects something
do
GOV=$(\
      zenity --window-icon=info --width=250 --height=250 \
      --list --title "Governor Switch" \
      --column="Select" --column "Governor" --radiolist \
      0 `cpufreq-info | grep governors | sed 's/^.*\: //;s/,/ 0/g'`\
     )
	 if [ ${?} == 1 ]
	 then
		 exit 1
	 fi
done

echo ${SUDOPASS} | ${SUDO} ${GOVSET} -g ${GOV}  
if [ $? != 0 ]
then
    MESSAGE="Unable to select $GOV governor"
    ICON="warning"
else
    MESSAGE="Succesfully changed to $GOV governor"
    ICON="info"
fi
zenity --notification --window-icon=${ICON} --text="${MESSAGE}"
exit 0

# vim:syntax=sh
# vim:sw=4:softtabstop=4:expandtab
