#!/bin/bash
# Show current CPU temperature.  May not work on anything but a thinkpad

XMLOCAL=$HOME/.xmonad/lib/Local.hs

# Extract the first number on a line.
first_number () {
    sed -e 's/^[^0-9]*//' | sed -e 's/[^0-9].*//' 
}

# dzen2 options.  Some may eventually be adjustable
#WIDTH=900
TW=80
XPOS=1000
YPOS=0
LINES=25
HEIGHT=24

fgCol=green
bgCol=gray25

if [ -e $XMLOCAL ]; then
    # Get the x position from the xmonad local parameters
    XPOS=$(grep firstTopBarWidth $XMLOCAL | first_number)
elif [ -x /usr/bin/xrandr ]; then
    # try to get the width of the primary monitor
    line=$(/usr/bin/xrandr | grep primary)
    tail=${line%%x*}
    screen_width=${tail##*\ }
    XPOS=$(( $screen_width - $TW ))
fi

DZEN_PARAMS=" -fg $fgCol -bg $bgCol -x $XPOS -y $YPOS -l $LINES -tw $TW -h $HEIGHT"
DZEN_OPTS="-dock -ta r -sa l"
# dzen2 event handlers
DZEN_EVENTS="-e button1=togglecollapse,unhide;button2=collapse"

## main loop

while true; do
    SENSORS=$(sensors)		# save command output - we only want to do it once/loop
    # grab the first line that contains both a temperature and a critical temperature
    # This probably won't always work, but it works on two of my thinkpads.
    LINE=$(<<<"$SENSORS"  grep 'C  (crit' | head -1)
    t=${LINE#*+}; TEMP=${t%%\ *}   # extract temperature + units
    ITEMP=${TEMP%%.*}		   # truncate TEMP to an integer
    t=${LINE#*+*+}; CTEMP=${t%%.*} # extract and truncate critical temp.
    WTEMP=$((($CTEMP * 85) / 100)) # warn at 85% of critical
    if [ $ITEMP -ge $CTEMP ]; then
	bg=red
	fg=black
    elif [ $ITEMP -ge $WTEMP ]; then
	bg=yellow
	fg=black
    else
	bg=black
	fg=
    fi

    echo -e "^cs()\n" "^tw()" "^bg($bg)" "^fg($fg)" $TEMP ' '
    echo "$SENSORS"
    sleep 5;
done | dzen2 $DZEN_OPTS $DZEN_PARAMS $DZEN_EVENTS
