#!/bin/bash
# Script to set the monitor brightness
# Creates a notification icon UI

ERR(){ echo "ERROR: $1" 1>&2; }

declare -i DEPCOUNT=0
for DEP in /usr/bin/{xdotool,yad,xrandr};do
    [ -x "$DEP" ] || {
        ERR "$LINENO Dependency '$DEP' not met."
        DEPCOUNT+=1
        }
done

[ $DEPCOUNT -eq 0 ] || exit 1

VERSION=`yad --version | awk '{ print $1 }'`
verlte() {
    [  "$1" = "`echo -e "$1\n$2" | sort -V | head -n1`" ]
}

verlt() {
    [ "$1" = "$2" ] && return 1 || verlte $1 $2
}

if verlt $VERSION 0.38.2; then
   yad --text=" The version of yad installed is too old for to run this program, \n Please upgrade yad to a version higher than 0.38.2   " \
       --button="gtk-close"
   exit
fi 


# Set the icon here
ICON="sunny"

# fifo
export YAD_NOTIF=$(mktemp -u --tmpdir YAD_NOTIF.XXXXXX)
mkfifo "$YAD_NOTIF" 

# trap that removes fifo
trap "rm -f $YAD_NOTIF" EXIT 

# window class for the list dialog
export CLASS="brightness_001" 

yad_scale() {
# Ensures only one instance of this window
# if there is another yad window close any dialog with the mathing class
if [[ $(pgrep -c $(basename $0)) -ne 1 ]]; then
   pids="$(xdotool search --class "$CLASS")"
   wpid="$(xdotool getwindowfocus)"

   for pid in $pids; do
        # Compares window class pid with the pid of a window in focus
        if [[ "$pid" == "$wpid" ]]; then
           xdotool windowunmap $pid
           exit 1
        fi
   done
fi 


# detect monitor
MON=$(xrandr -q | grep " connected" | cut -f1 -d ' ')

# find current xrandr brightness value
XR=$(xrandr --verbose | grep -i brightness | cut -f2 -d ' ' | head -n1)
BrCur=`awk "BEGIN {print $XR*100}"` # calculate, so e.g. 0.5 gets 50
BrMax="100"
BrMin="5"

yad --scale  --mouse   --class="$CLASS" --skip-taskbar --min-value $BrMin --max-value $BrMax \
    --value $BrCur --print-partial --undecorated --width 300 \
    --on-top --escape-ok --no-buttons --hide-value --close-on-unfocus \
| while read BrNew; do
    # division using awk, so xrandr value gets e.g. 0.5 rather than 50
    xrandr --output $MON --brightness $(awk "BEGIN {print $BrNew/100}")
done
}
export -f yad_scale

# fuction to set the notification icon
function set_notification_icon() {
  echo "icon:$ICON"
  echo "tooltip:brighness control"
  echo "menu:About!bash -c 'yad --about'!gtk-about||Quit!quit!gtk-quit"
}

exec 3<> $YAD_NOTIF

yad --notification --command="bash -c yad_scale" --listen <&3 & notifpid=$!

# waits until the notification icon is ready
until xdotool getwindowname $(xdotool search --pid "$notifpid" | tail -1) &>/dev/null; do
        # sleep until the window opens
        sleep 0.5       
done

set_notification_icon >&3 
