#!/sbin/runscript
# Copyright 1999-2005 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

CUSTOM_VTABLE=" "
DEFAULT_VTABLE=" "
VTABLE_PATH=" "

depend()
{
  need localmount
  need logger
}


do_error()
{
  # Display an error
  # $1: Error message

  eerror $1
  eerror "see http://gentoo-wiki.com/HOWTO_Undervolt_a_Pentium_M_CPU for further information"
  eend 1
}

sysfs_check()
{
  # Check that the sysfs interface exists

  if [ -e ${VTABLE_PATH_0_3_X} ]; then
    VTABLE_PATH="${VTABLE_PATH_0_3_X}"
    CUSTOM_VTABLE="${CUSTOM_VTABLE_0_3_X}"
    DEFAULT_VTABLE="${DEFAULT_VTABLE_0_3_X}"
    return 0
  else
    if [ -e ${VTABLE_PATH_0_2_X} ]; then
      VTABLE_PATH="${VTABLE_PATH_0_2_X}"
      CUSTOM_VTABLE="${CUSTOM_VTABLE_0_2_X}"
      DEFAULT_VTABLE="${DEFAULT_VTABLE_0_2_X}"
      return 0
    else
      logger "Undervolt: SysFs table not found. Can't modify CPU voltages."
      eerror "SysFs voltage_table not found. Can't modify CPU voltage table."
      eerror "It seems that the undervolting patch has not been applied to the kernel"
      do_error "or that the file /etc/conf.d/undervolt is not correctly configured."
      return 1
    fi
  fi
}

einfo_tables()
{
  # display current table and a custom table
  # $1 : custom table to display

  # Display the voltage table currently used by the CPU
  einfo "Current table:     "`cat ${VTABLE_PATH} `

  # Display the custom voltage table
  einfo "Configured table:  ${1}"
}

set_custom_table()
{
  # Set a custom table through the sysfs interface
  # $1 : custom table to set

  # Display current table and custom table that will be set
  einfo_tables "${1}"

  # Write the custom voltage to the SysFS interface and display the
  # new voltage table that is now used by the CPU if there is no error
  echo "${1}" > ${VTABLE_PATH} && \
  einfo "Applied table:     "`cat ${VTABLE_PATH}`

  return $?
}

start()
{
  ebegin "Changing CPU voltages table"

  if [ "$IS_CONFIGURED" = "yes" ]; then
    sysfs_check || return 1

    set_custom_table "${CUSTOM_VTABLE}"
    eend $?
  else
    do_error "Custom voltage table is not configured. Check the file /etc/conf.d/undervolt"
  fi
}

# I think it is not necessary to switch to the default voltage table on shutdown
# But this init script provides that feature in case you don't agree.
stop()
{
  if [ "$SWITCH_BACK" = "yes" ]; then
    if [ "$IS_CONFIGURED" = "yes" ]; then
      ebegin "Switching back to default CPU voltage table"

      sysfs_check || return 1

      set_custom_table "${DEFAULT_VTABLE}"
      eend $?
    else
      do_error "Default voltage table is not configured. Check the file /etc/conf.d/undervolt"
    fi
  else
    ebegin "Not switching back to default CPU voltage table (disabled in configuration)"
    eend 0
  fi
}