#!/bin/sh
# $Id: sound,v 1.11 2002/06/18 14:54:20 ldv Exp $
#
# sound:   This shell script launch the sound on your system.
#
# chkconfig: 2345 30 70
# description: This shell script launch the sound on your system.
# halt: yes

. /etc/init.d/functions

PKLVL=
SOUND_ALSA=

ChangePrintk()
{
	[ -n "$PKLVL" ] || PKLVL=`sed 's/^\(.\).*/\1/' < /proc/sys/kernel/printk`
	sysctl -w kernel.printk=0
}
	
ExitHandler()
{
	RETVAL=$?
	trap '' EXIT
	[ -n "$PKLVL" ] && sysctl -w "kernel.printk=$PKLVL"
	exit $RETVAL
}

trap ExitHandler SIGHUP SIGPIPE SIGINT SIGQUIT SIGTERM EXIT

LOCKFILE=/var/lock/subsys/sound

AUMIX=
[ -x /usr/bin/aumix ] && AUMIX=/usr/bin/aumix

function LookupDevices()
{
	egrep -qs '(sparcaudio|sound)' /proc/devices
}

function LoadModule()
{
	local phrase=$1 pattern=$2 m opt=
	[ -n "$3" ] && opt='-r'
	for m in `modprobe -c |egrep "^alias $pattern " |cut -d\  -f3 |sort -u`; do
		if [ -n "$m" ] && [ "$m" != off ]; then
			action "$phrase ($m):" modprobe "$opt" "$m"
			local rc=$?
			[ $rc -eq 0 ] || return $rc
		fi
	done
}

function load_alsa()
{
	modprobe -c |egrep '^alias [^ ]+ snd-card-' |cut -d\  -f3 |\
		while read line; do
			L=1
			action "Starting alsa sound driver $line:" modprobe $line
		done
	if [ -d /proc/asound ]; then
 		RETVAL=0 SOUND_ALSA=1 start_mixer
	fi
}

function start_alsa()
{
	[ -d /proc/asound ] || load_alsa
	[ -d /proc/asound ] && touch "$LOCKFILE"
}

function unload_alsa()
{
	RETVAL=0 stop_mixer;
	/sbin/lsmod |grep "^snd" |
		while read line; do
			/sbin/rmmod `echo $line |cut -d\  -f 1`
		done
	/sbin/rmmod soundcore 2>/dev/null
}

function start_mixer()
{
	if [ -n "$AUMIX" -a "$RETVAL" -eq 0 ] && LookupDevices; then
		if [ -s /etc/.aumixrc ]; then
			action "Loading mixer settings:" "$AUMIX" -f /etc/.aumixrc -L
		elif [ -n "$SOUND_ALSA" ]; then
			action "Loading mixer settings:" "$AUMIX" -v90 -w90
		fi
	fi
}

function stop_mixer()
{
	if [ -n "$AUMIX" ] && LookupDevices; then
		action "Saving mixer settings:" "$AUMIX" -f /etc/.aumixrc -S
	fi    
}

start()
{
	ChangePrintk
	# if there is alsa driver configured load it and exit.
	start_alsa && exit
	RETVAL=0
	LoadModule "Loading sound module" 'sound[^ ]*' || RETVAL=1
	LoadModule "Loading midi module" midi
	start_mixer
	touch "$LOCKFILE"
}

stop()
{
	ChangePrintk
	if [ -d /proc/asound ]; then
		unload_alsa
		rm -f "$LOCKFILE"
		exit 0
	fi
	stop_mixer
	LoadModule "Unloading midi module" midi REMOVE
	LoadModule "Unloading sound module" 'sound[^ ]*' REMOVE
	rm -f "$LOCKFILE"
}

case $1 in
	start|restart|reload)
		start
		;;
	stop)
		stop
		;;
	status)
		if lsmod |egrep -qs '^(sound|snd)'; then
			echo "Sound modules loaded"
		fi
		;;
	*)
		echo "Usage: ${0##*/} start|stop|restart|status"
		exit 1
esac
