#!/bin/bash

if [ $# -le 1 ]; then
  echo "Usage: $0 <device> <command> <channel> <value>"
  echo "   command ::= get set inc dec"
  echo "   channel ::= master bass treble wave speaker linein microphone"
  echo "               cd recording linein1 linein2 linein3"
  exit -1
fi

MINBIN=/usr/local/minerva/bin
LOGSTUB=/var/log/minerva/mixer

MIXER=/usr/bin/aumix
CMD=$2
CHANNEL=$3
VALUE=$4

# Reference usage for finddev...
#
# We've sent (and presumably rcv'd) a request from the finddev call
# Therefore:
# 1. DEVICE is actually the output from that command, which we might
#    need and so reflect to the calling command.
# 2. We exit now with a code of '0'. All Bearskin commands must check
#    for 0. If they receive it, they must also exit immediately.

DEVICE=`$MINBIN/finddev mixer $*`
if [ $? == 0 ]; then
  echo $DEVICE
  exit 0;
fi

# Do general purpose commands (without channel designations)
case "$CMD" in
  init)
     touch $LOGSTUB.lst 
     echo 0 >$LOGSTUB.mut
     $MIXER -f $LOGSTUB.mix -S
     chgrp minerva $LOGSTUB.lst $LOGSTUB.mix $LOGSTUB.mut
     chmod ug+rw   $LOGSTUB.lst $LOGSTUB.mix $LOGSTUB.mut
     exit 0
     ;;

  mute)
     $MIXER -f $LOGSTUB.mix -S
     $MIXER -v 0
     echo 1 >$LOGSTUB.mut
     exit 0
     ;;
  unmute)
     $MIXER -f $LOGSTUB.mix -L >/dev/null
     echo 0 >$LOGSTUB.mut
     exit 0
     ;;
  ismute)
     cat $LOGSTUB.mut
     exit 0
     ;;
  toggle)
     if [ "`$MINBIN/mixer default ismute`" == "1" ]; then
        $MINBIN/mixer default unmute
     else
        $MINBIN/mixer default mute
     fi
     exit 0
     ;;
esac

# Patch device to matchthe devices
# (currently, we assume one mixer)
if [ "$DEVICE" == "default" ]; then
   DEVICE=
fi

# Anything left must be a channel command, so this will
# fail if no channel is specified
case "$CHANNEL" in
  master)
    CHN=v
    ;; 
  bass)
    CHN=b
    ;; 
  treble)
    CHN=t
    ;; 
  wave)
    CHN=w
    ;; 
  speaker)
    CHN=p
    ;; 
  linein)
    CHN=l
    ;; 
  microphone)
    CHN=m
    ;; 
  cd)
    CHN=c
    ;; 
  recording)
    CHN=r
    ;; 
  linein1)
    CHN=1
    ;; 
  linein2)
    CHN=1
    ;; 
  linein3)
    CHN=1
    ;; 
  *)
    echo 0
    exit 0
    ;;
esac


case "$CMD" in
  get)
     $MIXER -$CHN q $DEVICE | sed 's/\,.*//' |  sed 's/[^0-9]\+//'
    ;;
  set)
     $MIXER -$CHN $VALUE $DEVICE
    ;;
  inc)
     $MIXER -$CHN +$VALUE $DEVICE
    ;;
  dec)
     $MIXER -$CHN -$VALUE $DEVICE
    ;;

  *)
    ;;
esac


echo $CMD $CHN $VALUE >$LOGSTUB.lst


