#!/bin/bash
# Copyright (C) 2005 Meethune Bhowmick <meethune@mercymachines.net>
# Wrapper for emerge to set cpufreq to performance and then
# reset it to the original state.
#  
# 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

SUDO="sudo"
FREQ=$(cpufreq-info -p 2>/dev/null | cut -f 3 -d ' ')
EMERGE="/usr/bin/emerge"

function die()
{
    echo "I died." 1>&2
    exit 1
}

function setCpuFreq()
{
    if [ ${FREQ} == "performance" ]
    then
        echo "CPU already set to performance"
        return 
    else
        if [ ${1} ] && [ ${1} == "UNSET" ]
        then
            ${SUDO} cpufreq-set -g ${FREQ}
            echo "Resetting CPU to ${FREQ}"
            return 
        else
            ${SUDO} cpufreq-set -g performance
            echo "Set CPU governor to performance"
            return 
        fi
    fi
}

function checkSetup()
{
    if [ $(basename ${0}) != "emerge" ]
    then
        echo "Either alias $(basename ${0}) as emerge or" 1>&2
        echo "rename/symlink $(basename ${0}) to emerge" 1>&2
        return 1
    fi
    if [ ! $(which ${SUDO} 2>/dev/null) ]
    then
        echo "Cannot find sudo, bye." 1>&2
        return 1
    fi
    if [ ! $(which cpufreq-info 2>/dev/null) ] ||
       [ ! $(which cpufreq-set 2>/dev/null) ]
    then
        echo "Cannot find cpufreq set or info, bye." 1>&2
        return 1
    fi

    if [ ! ${FREQ} ]
    then
        echo "Cannot determine governor, bye." 1>&2
        return 1
    fi
    return 0
}

checkSetup || die
setCpuFreq
${SUDO} ${EMERGE} ${*}
setCpuFreq "UNSET"
