#!/bin/sh
. "$HOME/.local/libexec/statusbar/colors"

cache=$XDG_RUNTIME_DIR/cpubarscache

temp=$(sensors | awk '/CPU/ {printf ("%.f°C", $2)}' | tr -d "+")
[ -n "$temp" ] && temp="$temp "
stats=$(awk '/cpu[0-9]+/ {printf "%d %d %d\n", substr($1,4), ($2 + $3 + $4 + $5), $5 }' /proc/stat 2>/dev/null)

[ ! -f "$cache" ] && echo "$stats" >"$cache" && exit
old=$(cat "$cache")
printf "%b" "  $temp"

first=true
echo "$stats" | while read -r row; do
	id=${row%% *}
	rest=${row#* }
	total=${rest%% *}
	idle=${rest##* }
	case "$(
		echo "$old" |
			awk '{if ($1 == id) printf "%d\n", (1 - (idle - $3)  / (total - $2))*100 /12.5}' \
				id="$id" total="$total" idle="$idle" 2>/dev/null
	)" in
	"0") col=$fggreen icon=▁ ;;
	"1") col=$fggreen icon=▂ ;;
	"2") col=$fggreen icon=▃ ;;
	"3") col=$fgorange icon=▄ ;;
	"4") col=$fgorange icon=▅ ;;
	"5") col=$fgorange icon=▆ ;;
	"6" | "7" | "8") col=$fgred icon=▇ ;;
	esac
    if [ "$col" != "$prevcol" ]; then
        [ "$first" != "true" ] && printf "%b" "</span>"
        printf "%b" "<span $col>"
    fi
    printf "%b" "$icon"

    first=false
    prevcol=$col
done

printf "%b" "</span>"

echo "$stats" >"$cache"