#!/bin/ksh

#pids=

#trap 'for p in $pids ; do kill $p ; done ' EXIT

declare -A state

update() {
	local what="$1"
	local new="$2"

	if [[ "${state[$what]}" != "$new"  ]]
	then
		herbstclient emit_hook "$(printf '%s\t%s' "$what" "$new")"
#		echo "$what :: $new"
		state[$what]="$new"
	fi
}

(
playerctl metadata --format '{{playerName}}|{{status}}|{{artist}}|{{xesam:comment}}|{{title}}' -a -F |
while IFS='|' read -r player status artist comment title
do
	test -n "$status" || status=off
	update "$(echo -en "player\t$player")" "$(printf '%s\t%s\t%s\t%s' "$status" "$artist" "$comment" "$title")"
done
notify-send -u critical  "Player" "Player monitoring loop failed!"

) &
#pids="$!"

(
while :
do
    pactl subscribe | ag "Event 'change' on sink" | while read -r _
    do 
        volume="$(pactl get-sink-volume "$(pactl get-default-sink)" | grep -E -o '[0-9]+%' | uniq | tr '\n' ',' | sed 's/,$//')"
        update volume "$volume"
    done
    sleep 10
done
) &

while :
do
	# shellcheck source=/sys/class/power_supply/BAT0/uevent # most likely
	#. /sys/class/power_supply/$batt_name/uevent
	read -r batt_perc < /sys/devices/platform/smapi/BAT0/remaining_percent
	read -r ac < /sys/devices/platform/smapi/BAT0/state
	read -r load _ < /proc/loadavg
	read -r temp < /sys/devices/platform/coretemp.0/hwmon/hwmon4/temp1_input

	update ac "$ac"

	update load "$load"

	update battery "$batt_perc"

	update temperature "$((temp / 1000 ))"

	update network "$(ip -br addr show dev eth0 | awk '{ print $2"\t"$3 }')"

	update wifi "$(iwctl station wlan0 show |grep 'Connected network' | sed 's/  */ /g' | cut -d ' ' -f 4-)"

	#if [ -e /run/user/1000/cmus-socket ]
	#then
		#update player "$(printf '%s\t%s \t%s' "$(playerctl metadata artist | tr -d "'" )" "$(playerctl metadata xesam:comment)" "$(playerctl metadata title)")"
	#else
		#update player ""
	#fi

	update date "%{T2}%{T-} $(date '+%{F#efefef}%H:%M%{F#909090}, %Y-%m-%{F#efefef}%d')"
	
	sleep 10
done
