#!/bin/bash

#pids=

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

batt_name=BAT0

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
}

if type playerctl &>/dev/null
then
    (
    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!"

    ) &
fi
#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
) &

root_dev="$(stat --printf %Hd,%Ld /)"
home_dev="$(stat --printf %Hd,%Ld "$HOME")"
check_df() {
    df=""
    df="/:$(df --output=pcent / | tail -n+2 | xargs)"

    if [[ "$root_dev" != "$home_dev" ]]
    then
        df+="	$USER:$(df --output=pcent "$HOME" | tail -n+2 | xargs)"
    fi

    update df "$df"
}

check_mem() {
    local mem
    mem="$(awk '
    /^MemAvailable/ { memavail=$2 }
    /^SwapTotal/ { swaptotal=$2}
    /^SwapFree/ { swapfree=$2 }
    /^MemTotal/ { memtotal=$2 }
    END { print memtotal"\t"memtotal-memavail"\t"swaptotal"\t"swaptotal-swapfree }
    ' < /proc/meminfo )"

    update memory "$mem"
}

while :
do
	# shellcheck source=/sys/class/power_supply/BAT0/uevent # most likely
	#. /sys/class/power_supply/$batt_name/uevent
    if [[ -e /sys/devices/platform/smapi/BAT0/ ]]
    then
        read -r batt_perc < /sys/devices/platform/smapi/BAT0/remaining_percent
        read -r ac < /sys/devices/platform/smapi/BAT0/state
    fi
	[[ -e "/sys/devices/platform/coretemp.0/hwmon/" ]] && read -r temp < /sys/devices/platform/coretemp.0/hwmon/hwmon?/temp1_input
	read -r load _ < /proc/loadavg

	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 }')"

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

    check_df
    check_mem
	#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
