#!/bin/bash
#################################################################################
#                                                                               #
#  Brightness OSD                                                               #
#                                                                               #
#  Depends on: wmctrl                                                           #
#                                                                               #
#  Usage: bright-osd.sh up    =  brightness up                                  #
#         bright-osd.sh down  =  brightness down                                #
#                                                                  version 1    #
#################################################################################

# How much brightness change per step
brightstep="550"

# OSD delay in milliseconds before it disappears
delay="50"

# Minimal brightness
minbright="150"

# Horizontal placement of window
gap_x="0"

# Vertical placement of window
gap_y="-200"

#################################################################################
export DISPLAY=:0

get_brightness () {
  maxbright=$(cat /sys/class/backlight/intel_backlight/max_brightness)
  brightness=$(cat /sys/class/backlight/intel_backlight/brightness)
  echo "$brightness" > ./tempfiles/brightness.tmp
  brightperc=$(printf $(echo "scale=5; $brightness/$maxbright * 100" | bc | awk -F'.' '{print $1}'))
  echo "$brightperc" > ./tempfiles/brightperc.tmp
}
get_brightness


bright_up () {
  brightness=$(($brightness+$brightstep))
  if [ "$brightness" -gt "$maxbright" ]; then
    echo "$maxbright" | sudo tee /sys/class/backlight/intel_backlight/brightness > /dev/null
  else
    echo "$brightness" | sudo tee /sys/class/backlight/intel_backlight/brightness > /dev/null
  fi
}


bright_down () {
  brightness=$(($brightness-$brightstep))
  if [ "$brightness" -lt "$minbright" ]; then
    echo "$minbright" | sudo tee /sys/class/backlight/intel_backlight/brightness > /dev/null
  else
    echo "$brightness" | sudo tee /sys/class/backlight/intel_backlight/brightness > /dev/null
  fi
}


if [ "$1" = "up" ]; then
  bright_up
elif [ "$1" = "down" ]; then
  bright_down
else
  echo
  echo " Conky Brightness OSD"
  echo
  echo " Usage: $(basename $0) up    =  brightness up"
  echo "        $(basename $0) down  =  brightness down"
  echo
fi

get_brightness

active=$(wmctrl -l | grep 'conky-brightness-osd')
if [ "$active" = "" ]; then
  conky -q -y "$gap_y" -x "$gap_x" -i "$delay" -c ./bright-osd.conky &
fi

echo -e "Brightness = $brightperc% \n"
