#!/bin/sh
# Feeds CPU and memory usage to a cont8nuum live tile.
#
# Usage: c8-sysmon-tile [tile-id] [interval-seconds]

tile=${1:-sysmon}
interval=${2:-5}
c8tile=${C8TILE:-c8tile}

case $interval in
''|*[!0-9]*|0)
	echo "c8-sysmon-tile: interval must be a positive integer" >&2
	exit 2
	;;
esac

# Prints "busy total" jiffies from the aggregate cpu line
cpu_sample() {
	awk '/^cpu / {
		idle = $5 + $6
		total = 0
		for (i = 2; i <= NF; i++)
			total += $i
		print total - idle, total
		exit
	}' /proc/stat
}

trap 'exit 0' INT TERM

# When the shell restarts this tile's provider, make way for the new one
"$c8tile" watch "$tile" 2>/dev/null | while read -r event _; do
	[ "$event" = restarting ] && kill $$
done &
watcher=$!
trap 'kill $watcher 2>/dev/null' EXIT

set -- $(cpu_sample)
prev_busy=$1
prev_total=$2
failures=0

while :; do
	sleep "$interval"

	set -- $(cpu_sample)
	busy=$1
	total=$2
	dtotal=$((total - prev_total))
	if [ "$dtotal" -gt 0 ]; then
		cpu=$(( (100 * (busy - prev_busy) + dtotal / 2) / dtotal ))
	else
		cpu=0
	fi
	prev_busy=$busy
	prev_total=$total

	read -r load1 load5 load15 _ < /proc/loadavg

	mem=$(awk '
		/^MemTotal:/ { total = $2 }
		/^MemAvailable:/ { avail = $2 }
		END {
			used = total - avail
			printf "%d|%.1f|%.1f\n", (100 * used + total / 2) / total,
				used / 1048576, total / 1048576
		}' /proc/meminfo)
	mem_pct=${mem%%|*}
	mem=${mem#*|}
	mem_used=${mem%%|*}
	mem_total=${mem#*|}

	ok=1
	"$c8tile" update "$tile" --tag cpu template=block block="$cpu%" \
		meter="$cpu" text1=Processor text2="load $load1 $load5 $load15" ||
		ok=0
	"$c8tile" update "$tile" --tag mem template=block block="$mem_pct%" \
		meter="$mem_pct" text1=Memory text2="$mem_used of $mem_total GiB" ||
		ok=0

	if [ "$ok" -eq 1 ]; then
		failures=0
	else
		failures=$((failures + 1))
		if [ "$failures" -ge 3 ]; then
			echo "c8-sysmon-tile: c8tile failed 3 times in a row, giving up" >&2
			exit 1
		fi
	fi
done
