#!/bin/sh
#
# vim:sw=2 ts=8:et sta:fdm=marker
#
#
# Copyright (c) 2008 Ariff Abdullah <skywizard@MyBSD.org.my>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#        $FreeBSD$
#
# Date: Sun Dec 14 12:07:19 MYT 2008
#   OS: FreeBSD miki.MyBSD.org.my 8.0-CURRENT i386
#

apps=""
vol=""
reqop=""
devdir="/dev"

usage() {
    echo "Usage: ${0##*/} apps [pcm/rec] [left:right]"
    exit 1
}

if [ `sysctl -n hw.snd.verbose` -lt 2 ]; then
  echo "Please set sysctl 'hw.snd.verbose' to something that is >= 2"
  exit 1
fi

case "$#" in
  0)
    ;;
  1)
    apps="$1"
    ;;
  2)
    apps="$1"
    if [ "$2" = "pcm" -o "$2" = "rec" ]; then
      reqop="$2"
    else
      vol="$2"
    fi
    ;;
  3)
    apps="$1"
    if [ "$2" = "pcm" -o "$2" = "rec" ]; then
      reqop="$2"
    else
      usage
    fi
    vol="$3"
    ;;
  *)
    usage
    ;;
esac

t=1
awk '/ pid / {print $1,$10,$11}' < /dev/sndstat | while read dev pid proc ; do
  proc=${proc%)}
  proc=${proc#(}
  if [ "$apps" = "" -o "$apps" = "$proc" ]; then
    dev=${dev%]:}
    dev=${dev##*:}
    op="pcm"
    case "$dev" in
      *r[0-9]*)
        op="rec"
        ;;
    esac
    if [ "$reqop" = "" -o "$reqop" = "$op" ]; then
      if [ $t = 1 ]; then # XXX
        nl=""
      else
        nl=""
      fi
      printf "${nl}%s (%s):\n\t" $proc $dev
      if [ "$vol" = "" ]; then
        mixer -f $devdir/$dev
      else
        mixer -f $devdir/$dev $op $vol
      fi
    fi
    t=$(($t+1))
  fi
done
