#!/bin/bash

## usage function
function usage {

    local ecode=${2:-0}

    test -n "$1" && printf "\n %s\n" "$1" >&2

cat >&2 << helpMessage

 usage: ${0//*\//} [ delay (default: 2 sec) ]

  This script monitors kmix volume by dcop call to get Mixer0 masterVolume. When
  the volume changes, a dialog is displayed showing the difference and asking
  whether to continue monitoring. The program loop sleeps for delay (default: 2)
  seconds. If run in the foreground, 'q' quits at any time.

 Options/Arguments:

    -h  | --help      program help (this file)
    int               sets the delay (sleep time) for program loop, 2 sec defaut

helpMessage

    exit $ecode;
}

## check kdialog installed
if ! type kdialog &>/dev/null; then
  usage "error: kdialog required to monitor kmix volume" 1
fi

## respond to help
test "$1" = -h -o "$1" = --help && usage

## initialize last and current variables and default delay
last="$(dcop kmix Mixer0 masterVolume)"
curr="$last"
delay=2

## validate argument is int > 0 before accepting as delay
if [ "$1" -eq "$1" 2>/dev/null -a "$1" -gt 0 ]; then
  delay="$1"
fi


## volume monitor loop
while : ; do
  ## if foreground also test for 'q' (quit), if backgroundind, just use sleep
  case $(ps -o stat= -p $$) in
    *+* ) read -s -N 1 -t $delay resp     # read 'q' or 'Q' for quit in $delay secs
          [ "$resp" = 'q' ] && break;;
     *  ) sleep "$delay";;
  esac

  ## update last and current values
  last="$curr"
  curr="$(dcop kmix Mixer0 masterVolume)"

  ## if they differ, display kdialog yesno with change
  if [ "$curr" -ne "$last" ]; then
    kdialog --caption "Kmix Volume Monitor" \
            --yesno "Kmix volumne has changed:\n  last: $last\n  curr: $curr\nContinue?"
  fi

  ## if answer 'no' to continue?, break
  [ $? -eq 1 ] && break

done
