#!/bin/bash
# 
# CPU control utility
# Andrew Wyatt
# Generic FSB control utility to shift between modes
#

JUPITER_PATH="/usr/lib/jupiter/scripts"
JUPITER_HW="/usr/lib/jupiter/vendors"
JUPITER_VAR="/var/lib/jupiter"

if [[ "$*" =~ "silent" ]]; then
  NO_NOTIFY=1
fi

. $JUPITER_PATH/notify

NICON="/usr/share/jupiter/jupiter.png"
BATSTATE=$($JUPITER_PATH/state)
FSB_SAVED=$(cat $JUPITER_VAR/cpu_mode)

VENDOR=$(cat /sys/devices/virtual/dmi/id/sys_vendor)

function cleanup {
  if [ -e "$JUPITER_VAR/cpu-control-busy" ]; then
    rm -f $JUPITER_VAR/cpu-control-busy 2>/dev/null
  fi
}

if [ -e "$JUPITER_VAR/cpu-control-busy" ]; then
  countdown="2"
  while [ $countdown -gt 0 ]; do
    sleep 1
    if [ ! -e "$JUPITER_VAR/cpu-control-busy" ]; then
      break
    fi
    countdown=$[$countdown-1]
  done
  rm -f $JUPITER_VAR/cpu-control-busy
else
  touch "$JUPITER_VAR/cpu-control-busy"
fi

if [ -e "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor" ]; then
  FSB_CPU0=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
fi

function fsb_mode {
  FSBTARGET=$1

  if [ "$FSBTARGET" = "super" ]; then
    RMODE="Maximum Performance"
    CPUMODE="performance"
    NICON="/usr/share/jupiter/bolt2.png"
  fi

  if [ "$FSBTARGET" = "high" ]; then
    RMODE="Performance On Demand"
    CPUMODE="ondemand"
    NICON="/usr/share/jupiter/bolt1.png"
  fi
  
  if [ "$FSBTARGET" = "powersave" ]; then
    RMODE="Power Savings"
    CPUMODE="powersave"
    NICON="/usr/share/jupiter/bolt4.png"
  fi

  if [ ! "$CPUMODE" ]; then
    CPUMODE="$FSBTARGET"
  fi

  if [ "$FASTER_POWERSAVE" = "1" ]; then
    if [ "$FSBTARGET" = "powersave" ]; then
      CPUMODE="ondemand"
    fi
  fi

  cpus=(`ls /sys/devices/system/cpu/ | grep cpu[0-9]`)
  cpucount=${#cpus[@]}
  for (( i=0; i<cpucount; i++ ));
  do
    if [ -e "/sys/devices/system/cpu/${cpus[$i]}/cpufreq/scaling_governor" ]; then
      echo $CPUMODE > /sys/devices/system/cpu/${cpus[$i]}/cpufreq/scaling_governor
    fi
  done

  notify $"$RMODE Mode" $NICON

  if [ ! "$FSBTARGET" = "default" ]; then
    echo $FSBTARGET >$JUPITER_VAR/cpu_mode
    echo $FSBTARGET >$JUPITER_VAR/$BATSTATE
    if [ -e "$JUPITER_HW/$VENDOR/cpu-control" ]; then
      "$JUPITER_HW/$VENDOR/cpu-control" $FSBTARGET
    fi
  fi
}

function fsb_toggle {
  FSB_SAVED=$(cat $JUPITER_VAR/cpu_mode)
  if [ "$FSB_SAVED" = "super" ]; then
    fsb_mode "high"
  elif [ "$FSB_SAVED" = "high" ]; then
    fsb_mode "powersave"
  elif [ "$FSB_SAVED" = "powersave" ]; then
    fsb_mode "super"
  fi
}

case $1 in
  restore)
    NO_NOTIFY=1
    fsb_mode $FSB_SAVED
  ;;
  super)
    fsb_mode "super"
  ;;
  high)
    fsb_mode "high"
  ;;
  powersave)
    fsb_mode "powersave"
  ;;
  initial)
    /etc/pm/power.d/00-jupiter-cpu
  ;;
  vendor)
    echo "$VENDOR"
  ;;
  default)
    fsb_mode "default"
  ;;
  *)
    fsb_toggle
  ;;
esac
cleanup
