#!/bin/bash
#
# alsasound     This shell script takes care of starting and stopping
#               ALSA sound driver.
#
# Copyright (c) by Jaroslav Kysela <perex@jcu.cz> 
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# For RedHat 5.0:
# chkconfig: 2345 87 14
# description: ALSA driver
#

maxcards=8
maxmixers=2

function start() {
  #
  # insert all sound modules
  #
  cat /etc/conf.modules | \
    grep -E "^alias.+snd-card-[[:digit:]]" | \
    awk '{print $3}' | \
    while read line; do \
      echo -n "Starting sound driver: $line "; \
      /sbin/modprobe $line; \
      echo "done"; \
    done
  #
  # restore mixer settings
  #
  idx=0
  while [ $idx -lt $maxcards ]; do
    if [ -d /etc/sound/$idx ] && [ -d /proc/sound/$idx ]; then
      idx1=0
      while [ $idx1 -lt $maxmixers ]; do
        if [ -r /etc/sound/$idx/mixer$idx1 ] && [ -w /proc/sound/$idx/mixer$idx1 ]; then
          cat /etc/sound/$idx/mixer$idx1 > /proc/sound/$idx/mixer$idx1
        fi
        idx1=$[$idx1+1]
      done
    fi
    idx=$[$idx+1]
  done
}

function stop() {
  #
  # save mixer settings
  #
  idx=0
  while [ $idx -lt $maxcards ]; do
    if [ -d /proc/sound/$idx ]; then
      idx1=0
      while [ $idx1 -lt $maxmixers ]; do
        if [ -r /proc/sound/$idx/mixer$idx1 ]; then
          mkdir -p /etc/sound/$idx
          cat /proc/sound/$idx/mixer$idx1 > /etc/sound/$idx/mixer$idx1
        fi
        idx1=$[$idx1+1]
      done
    fi
    idx=$[$idx+1]
  done
  #
  # remove all sound modules
  #
  /sbin/lsmod | grep -E "^snd" | while read line; do \
     /sbin/rmmod `echo $line | cut -d ' ' -f 1`; \
  done
}

# See how we were called.
case "$1" in
  start)
        # Start driver.
	if [ ! -d /proc/sound ]; then
	  start
	  if [ -d /proc/sound ] && [ -d /var/lock/subsys ]; then
	    touch /var/lock/subsys/alsasound
	  fi
	else
	  echo "ALSA driver is already running."
	fi
        ;;
  stop)
        # Stop daemons.
	if [ -d /proc/sound ]; then
          echo -n "Shutting down sound driver: "
	  stop
	  if [ -d /var/lock/subsys ]; then
	    rm -f /var/lock/subsys/alsasound
	  fi
 	  echo "done"
	else
	  echo "ALSA driver isn't running."
	fi
        ;;
  restart)
	$0 stop
	$0 start
	;;
  *)
        echo "Usage: alsasound {start|stop|restart}"
        exit 1
esac

exit 0
