#!/bin/bash

pgrep -x "$(basename "$0")" | grep -v $$ >/dev/null && exit 0

xsetroot -name "Loading ..."

while (true); do
    #set date: 04.03 15:22
    timedate=$(date +"%m.%d %H:%M")

    ## memory in use
    #mem=$(free -m | grep Mem | awk '{print $7}')

    ## load average
    #loadavg=$(cat /proc/loadavg | awk '{print $1 " " $2 " " $3}')


    check_mpd() {
        # check if mpd is playing
        # if yes, output volume and song
        check_play=$(mpc status | grep "playing")
        if [ ! -z "$check_play" ]; then
            play="[ $(mpc status | head -n 1) ]"
            ## volume from mopidy, not useful, use master volume below
            #vol="[$(mpc vol | cut -c 8-)]"
        else 
        #otherwise hide it
            vol=""
            play=""
        fi
    }
    
    # function to call to update volume
    # this is so I don't have to constantly poll it every 0.5
    set_volume() {
        ## using pactl was really unreliable
        #sound_card="$(pactl list sinks short | grep -i audioengine | awk '{print $1}')"
        #sound_card=3
        #vol="$(pactl list sinks | grep '^[[:space:]]Volume:' | head -n $sound_card | tail -n 1 | sed -e 's,.* \([0-9][0-9]*\)%.*,\1,')%"
        vol="$(pulsemixer --get-volume | awk '{print $1}')%"
    }

    ### mouse charging
    # get state (eg "charging")
    #mouse_state="$(upower -i /org/freedesktop/UPower/devices/battery_hidpp_battery_6 | grep state | awk '{print $2}')"
    battery_name=$(upower --dump | grep Device.*battery | awk '{print $2}')
    mouse_state="$(upower -i $battery_name | grep state | awk '{print $2}')"
    # get charge percentage
    mouse_charge="$(upower -i $battery_name | grep percentage | awk '{print $2}')"
    # if the mouse is charging, set state to percentage.  otherwise dont show it ("")
    #if [ $mouse_state == "charging" ] && [ $mouse_state != "discharging" ]; then
   #     mouse_status="[ Mouse: $mouse_charge ]"
   # else
   #     unset mouse_status
   # fi

    # volume up/down scripts will SIGHUP this PID
    # when you receive SIGHUP just run set_volume()
    trap set_volume SIGHUP



    ### weather stuff
    wttr_file="/tmp/weather"
    if [[ -s "$wttr_file" ]]; then
        wttr=$(<"$wttr_file")
        xsetroot -name "$mouse_status $play $vol $wttr $timedate"
    else
        # output to status bar
        xsetroot -name "$mouse_status $play $vol $timedate"
    fi

    sleep 0.5;
done
