#!/bin/sh

# Print a compact, single-line system summary for vev's top-right bar anchor.
# When available, segments are ordered as workspace, CPU, memory, then clock.
# Segments that cannot be read are omitted without producing stderr.
#
# The workspace segment needs the NeferWL compositor and a local client
# (VEV_CLIENT_PID set), plus jq. It shows the client's monitor and its workspaces,
# e.g. "DP-2 [x][ ][ ]". A remote client or another compositor omits it.

workspace=
if [ -n "${VEV_CLIENT_PID:-}" ] && command -v neferwl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1; then
	workspace=$(
		neferwl state output-of "$VEV_CLIENT_PID" 2>/dev/null |
			jq -r '
				if .workspace != "" and .active == 0 then "\(.name) \(.workspace)"
				else "\(.name) " + ([range(1; .count + 1) as $i | if $i == .active then "[x]" else "[ ]" end] | join(""))
				end
			' 2>/dev/null || true
	)
fi

now=$(date +%H:%M 2>/dev/null || true)

cpu_pct=
if [ -r /proc/stat ]; then
	first=$(awk '$1 == "cpu" { idle = $5 + $6; total = 0; for (i = 2; i <= NF; i++) total += $i; print idle, total; exit }' /proc/stat 2>/dev/null || true)
	sleep 0.1 2>/dev/null || true
	second=$(awk '$1 == "cpu" { idle = $5 + $6; total = 0; for (i = 2; i <= NF; i++) total += $i; print idle, total; exit }' /proc/stat 2>/dev/null || true)
	if [ -n "$first" ] && [ -n "$second" ]; then
		cpu_pct=$(
			awk -v first="$first" -v second="$second" '
				BEGIN {
					split(first, a, " ")
					split(second, b, " ")
					idle = b[1] - a[1]
					total = b[2] - a[2]
					if (total > 0) printf "%d", ((total - idle) * 100) / total
				}
			' 2>/dev/null || true
		)
	fi
fi

mem_pct=
if [ -r /proc/meminfo ]; then
	mem_pct=$(
		awk '
			$1 == "MemTotal:" { total = $2 }
			$1 == "MemAvailable:" { available = $2 }
			END {
				if (total > 0 && available >= 0) printf "%d", ((total - available) * 100) / total
			}
		' /proc/meminfo 2>/dev/null || true
	)
fi

line=$workspace
if [ -n "$cpu_pct" ]; then
	if [ -n "$line" ]; then
		line="$line C $cpu_pct%"
	else
		line="C $cpu_pct%"
	fi
fi
if [ -n "$mem_pct" ]; then
	if [ -n "$line" ]; then
		line="$line M $mem_pct%"
	else
		line="M $mem_pct%"
	fi
fi
if [ -n "$now" ]; then
	if [ -n "$line" ]; then
		line="$line $now"
	else
		line="$now"
	fi
fi

printf '%s\n' "$line"
