#!/bin/env sh

cpu()
{
	cpu=$(top -bn1 | awk '/Cpu\(s\):/ {print $2 + $4 "%"}')
}

memory()
{
	memory=$(free -m | awk '/^Mem:/ {printf "%.1f", $3/2024}')
}

disk() {
	disk="$(df -h | awk 'NR==2{print $4}')"
}

cdate()
{
	cdate="$(date "+%a %d %b")"
}

ctime()
{
	ctime="$(date "+%I:%M:%S %p")"
}

bat() {
	# read -r bat_status </sys/class/power_supply/BAT0/status
	read -r bat_capacity </sys/class/power_supply/BAT0/capacity
	bat="$bat_capacity%"
}

vol() {
	vol=$(wpctl get-volume @DEFAULT_AUDIO_SINK@ | awk '{printf "%.0f%%\n", $2*100}')
}

display() {
	echo "all status  $memory  $cpu 󰁹$bat 󰋋 $vol 󰃭 $cdate 󰥔 $ctime" >"$FIFO"
}

printf "%s" "$$" > "$XDG_RUNTIME_DIR/status_pid"
FIFO="$XDG_RUNTIME_DIR/sandbar"
[ -e "$FIFO" ] || mkfifo "$FIFO"
sec=0

while true; do
	sleep 1 &
	wait && {
		[ $((sec % 1)) -eq 0 ] && memory
		[ $((sec % 1)) -eq 0 ] && cpu
		# [ $((sec % 1)) -eq 0 ] && disk
		[ $((sec % 60)) -eq 0 ] && bat
		[ $((sec % 1)) -eq 0 ] && vol
		[ $((sec % 1)) -eq 0 ] && cdate
		[ $((sec % 1)) -eq 0 ] && ctime

		[ $((sec % 1)) -eq 0 ] && display

		sec=$((sec + 1))
	}
done
