#!/bin/sh

set -e

# on Linux only:
# these files (separated by newlines) will have the current CPU temperature
# multiplied by $CPU_TEMP_SCALE. this script divides the file contents by scale
# and displays that temperature (assumed to be in Celsius units)
CPU_TEMP_FILES="/sys/devices/platform/coretemp.0/hwmon/hwmon4/temp2_input
/sys/devices/platform/coretemp.0/hwmon/hwmon4/temp3_input"
CPU_TEMP_SCALE=1000

# format for the date (by default in this script, ISO 8601)
DATE="date +%Y-%m-%dT%T"

DELIMITER=" || "

# how fast to refresh the display (in seconds, will be substituted with 1 if
# not an integer)
INTERVAL=1

get_cpu_temp() {
	if streq "$(uname)" "Linux"; then
		RETVAL=""
		# iterate over files, adjust, print out "%dC "
		for file in $CPU_TEMP_FILES;
			do RETVAL="$RETVAL$(fdivide $(cat $file) $CPU_TEMP_SCALE)C "
		done
		# in-line python (bet you've never seen that before) that
		# strips off trailing whitespace. could be done with sed but
		# this was more fun
		printf "%b" "$RETVAL" \
			| python -c "from sys import stdin; print(stdin.read().rstrip() + '\n')"
		return
	elif streq "$(uname)" "NetBSD"; then
		printf "%bC" "$(envstat -s coretemp0:'cpu0 temperature' \
			| sed 1,2d \
			| cut -d ':' -f 2 \
			| awk '{print $1}' \
			| cut -d '.' -f 1)"
		return
	else
		printf "get_cpu_temp: unsupported OS"
	fi
}

get_current_desktop() {
	LASTDESKTOP="$DESKTOP"
	case "$WM" in
	bspwm) 
		DESKTOP="$(bspc query -D -d focused --names 2>/dev/null)" ;;
		
	esac || DESKTOP=""
	printf "[%s] " "$DESKTOP"
	if str isvalue "$LASTDESKTOP" && ! str isvalue "$DESKTOP"; then
		# X is kill
		exit 0
	fi
}

get_memory_usage() {
	if streq "$(uname)" "Linux"; then
		printf "%b" \
			"$(free | head -n 2 | tail -n 1 \
				| awk '{print $3 " used / " $2 " total"}')"
		return
	fi
}

PUBLIC_IP="$(ifpublic)"

printbar() {
	printf "%b" "$(get_current_desktop)"
	printf "%b" $($DATE)
	printf "%b" "$DELIMITER"
	printf "%b" "BAT: $(battery)"
	printf "%b" "$DELIMITER"
	printf "%b" "CPU: $(get_cpu_temp)"
	printf "%b" "$DELIMITER"
	printf "%b" "PuIP: $PUBLIC_IP"
	#printf "%b" "$DELIMITER"
	#printf "%b" "MEM: $(get_memory_usage)"
	printf "\n"
	return
}

# check to make sure customizeable vars are in proper format

str isdigit "$INTERVAL" \
	|| INTERVAL=1

str isdigit "$CPU_TEMP_SCALE" \
		&& [ "$CPU_TEMP_SCALE" -gt 0 ] \
	|| CPU_TEMP_SCALE=1

str isvalue "$CPU_TEMP_FILES" \
	|| alias get_cpu_temp="printf '[no temperature files specified]\n'"

# main loop

while true; do
	printbar
	sleep "$INTERVAL"
	if streq $(date +'%S') 00; then
		# every minute
		PUBLIC_IP="$(ifpublic)"
	fi
done
