#!/bin/bash
# 
# Copyright (c) 2003, MiTAC Inc.
#
# a script dump temperatures and fan speeds. rain.w 20031107.
#

root=/proc/sys/dev/sensors/w83782d-i2c-0-29
mode="count"
count=1
interval=2
file=""
pwm=""

usage () {
	echo "usage: $0 [-h] [-m mode] [-c count] [-i interval] [-f file] [pwm]"
	echo "   -h: help, show this help messages"
	echo "   -m: mode, running mode of 'count' or 'loop'"
	echo "   -c: count, set show times when in count mode"
	echo "   -i: interval, loop interval when in loop mode"
	echo "   -f: file, messages to a file when in loop mode"
	echo "  pwm: show PWM values when this argument is passed"
}

output1 () {
	echo -e $1
	if [ -n "$file" ]; then
		echo -e $1 >> $file
	fi
}

output2 () {
	echo -en $1
	if [ -n "$file" ]; then
		echo -en $1 >> $file
	fi
}

show_item () {
	value=$( cat $root/$1 | awk '{print $'$2'}' )
    	value=$(echo $value| awk -F. '{ printf $1;}');
	if [ $1 = "temp2" -o $1 = "temp3" ]; then
	  	value=$(($value + 7))
	fi
	if [ $value -lt 100 ]; then
	  	output2 "$value\40"
    	else
	  	output2 "0\40"
	fi
	if [ -n "$pwm" ] && [ $pwm = "pwm" ]; then
		if [ $value -lt 100 ];then
	  		value=$( cat $root/$3 )
			output2 "/$value"
		else
		  output2 "/None"
		fi
	fi
	value=$( cat $root/$4 | awk '{print $'$5'}' )
	output2 "/$value\t"
	if [ $value -eq 0 ]; then
		output2 "\t"
	fi
}

while [ $# -gt 0 ]; do
	case $1 in
	-m*)
		mode=$2
		shift
		;;
	-c*)
		count=$2
		shift
		;;
	-i*)
		interval=$2
		shift
		;;
	-f*)
		file=$2
		shift
		;;
	pwm)
		pwm=$1
		;;
	*)
		usage
		exit
	esac
	shift
done

if [ ! -d $root ]; then
	echo check your driver
	exit
fi

output1 "time\t\t\tVRM \t\tCPU1 \t\tCPU2 " 
if [ -n "$pwm" ] && [ $pwm = "pwm" ]; then
  output1 "\t\t\t(Temp/PWM/RPM)\t(Temp/PWM/RPM)\t(Temp/PWM/RPM)"
else
  output1 "\t\t\t(Temp/RPM)\t(Temp/RPM)\t(Temp/RPM)"
fi

while [ $mode = "loop" ] || [ $(( count-- )) -gt 0 ]; do
	output2 "$( date +%D' '%R:%S )\t" 
	show_item temp1 3 pwm4 fan3 2
	show_item temp2 3 pwm1 fan1 2
	show_item temp3 3 pwm3 fan2 2
	output1 ""
	sleep $interval
done

exit $?
