#!/bin/bash
#20200620 BK: v1.1: aarch64 fix.
#20201115 BK: v1.2: hardware profiling, when usb-stick booted on different computers.
#20201115 BK: v1.2: fix range. ref: https://easyos.org/forum/showthread.php?tid=83

TMP=~/.config/pmcputemp
arch=`uname -m`

#20201115 BK note, /proc/cpuinfo also works arm boards. not complete motherboard info though.
HWprofile="$(/usr/local/pmcputemp/hwprofile.sh)"
# ex: IntelRCoreTMi38100CPU360GHz
unset FILE

load_module_func() {
	[ -z "$1" ] || mod=$1 # manually specified on cli
	#echo "test module" # COMMENT THIS IN REAL LIFE
	for m in ${mod} coretemp k10temp k8temp it87 lm85 # more can be added
	do 
		#echo "$m" # COMMENT THIS IN REAL LIFE
		lsmod|grep -q $m # check if loaded
		ret=$?
		if [ $ret -ne 0 ];then
			modprobe $m 2>/dev/null # load if not already
		fi
		check_temp_data_exists # returns 0 on success
		dat=$?
		if [ $dat -eq 0 ];then
			return 0 # success, break here
		else
			rmmod $m 2>/dev/null # try to unload as it is useless to us
			continue # module failed, try next module
		fi
	done		
	# if we get here it failed
	echo "Can't load a temperature module"
	return 1
}

find_func() {
	FILES="$1"
	for n in `echo $FILES`; do
		read p < $n
		if [ $? = 0 ];then
			NUM=$(($p+0)) #BK 20201115 this "castes" a string to a number
			if [ $NUM -gt 110000 ];then #BK 20201115 check number too big
			 continue
			fi
			FILE=$n # found it
				if [ "$(echo "$FILES" |grep applesmc)" != "" ]; then
					FILE=$(grep -rs TC0P /sys/devices/platform* | cut -f1 -d: |sed 's/label/input/')
				fi
			break
		else
			continue # didn't find, search again
		fi
	done
	# if we get here we didn't find anything useful
}

check_temp_data_exists() {
	#echo "checking data" # COMMENT THIS IN REAL LIFE
	# the rough order is Intel, AMD, whatever else
	for a in `find /sys/devices/platform -type f -name 'temp*_input'|sort` \
			`find /sys/devices/pci* -type f -name 'temp*_input'|sort` \
			`find /sys/devices/virtual -type f -name 'temp'|sort`
	do find_func "$a"
		[ -z "$FILE" ] && continue || break # if we found data break
	done
	if [ ! "$FILE" ];then echo "Failed to find file" && return 1 # bail out
	fi
	# if we get here we found it, so we write to file
	[ ! -d $TMP ] && mkdir $TMP
	echo -e "\"${FILE}\" is written to : \n${TMP}/pmcputemprc.${HWprofile}" #BK 20201115
	echo -n ${FILE} > $TMP/pmcputemprc.${HWprofile} #BK 20201115
	[ ! -d /tmp/pmcputemp ] && mkdir /tmp/pmcputemp #BK 20200620
	return 0
}

cputempfunc() {
	#echo "starting" # COMMENT THIS IN REAL LIFE
	if [ "${arch:0:3}" != "arm" -a "${arch:0:7}" != "aarch64" ];then #BK 20200620
		load_module_func
		[ $? -ne 0 ] && exit 1
	else
		check_temp_data_exists
		return $?
	fi
	return 0
}

if [ -z "$1" ];then
	cputempfunc # start
else
	cli_mod=$1
	load_module_func $cli_mod # module specified on pmcputemp cli
fi
