#!/usr/bin/env bash
# The Sway configuration file in ~/.config/sway/config calls this script.
# status_command should just be: ~/.config/sway/status.sh
# (no outer while/sleep needed anymore — this script loops itself)

get_title() {
	local t
	t=$(swaymsg -t get_tree | jq -r '.. | select(.type?=="con" and .focused==true) | .name // empty' 2>/dev/null)
	t=${t:-Desktop}
	local max_len=50
	if [ ${#t} -gt $max_len ]; then
		t="${t:0:$((max_len - 1))}…"
	fi
	echo "$t"
}

refresh_slow() {
	date_formatted=$(date "+%a %F %H:%M")
	cpu_percentage=$(top -b -n2 -p 1 | fgrep "Cpu(s)" | tail -1 | awk -F'id,' '{ split($1, vs, ","); v=vs[length(vs)]; sub("%", "", v); printf "%.1f%%\n", 100 - v }')
	ram_percentage="$(free | grep Mem | awk '{print substr($3/$2 * 100.0, 1, 3)}')%"
	cpu_percentage=$(printf "%5s" "$cpu_percentage")
	ram_percentage=$(printf "%4s" "$ram_percentage")
}

# Prime the slow-changing values once before the loop starts
refresh_slow
tick=0

while true; do
	window_title=$(get_title)

	# Emojis and characters for the status bar
	# 💎 💻 💡 🔌 ⚡ 📁 \|
	echo "\
$window_title | \
$ram_percentage RAM |\
$cpu_percentage CPU | \
$date_formatted\
"

	if [ "$tick" -ge 29 ]; then
		refresh_slow
		tick=0
	else
		tick=$((tick + 1))
	fi

	sleep 1
done