#!/bin/sh
# (c) MandrakeSoft, Chmouel Boudjnah <chmouel@mandrakesoft.com>
# 	$Id: sound,v 1.4 2001/02/13 21:05:03 chmouel Exp $
#
# sound:   This shell script launch the sound on your system.
#
# chkconfig: 2345 9 97
# description: This shell script launch the sound on your system.
# halt: yes

if [ -f /etc/modules.conf ];then
    conf_file=/etc/modules.conf
elif [ -f /etc/conf.modules ];then
    conf_file=/etc/conf.modules
else
    exit 0
fi

. /etc/rc.d/init.d/functions

PKLVL=`sed 's/^\(.\).*/\1/' < /proc/sys/kernel/printk`
sysctl -w kernel.printk=0

function module () {
    opt=""
    phrase=$1
    alias=$2
    [ -n "$3" ] && opt="-r"
    module=`egrep -s "^alias( |\t)+"$alias"( |\t)+" $conf_file | awk '{ print $3 }'`
    if [ -n "$module" ] && [ "$module" != "off" ];then
	action "$phrase ($module)" modprobe "$opt" $module
	return $?
    fi
}

function load_alsa () {
    grep '^alias[ \t].*[ \t]snd-card-.*' $conf_file|awk '{print $3}' |\
  while read line;do L=1 ; action "Starte ALSA Sound-Treiber $line" /sbin/modprobe $line;done
  if [ -d /proc/asound ];then
      retval=0 start_mixer
  fi
}

function start_alsa () {
    load_alsa
    [ -d /proc/asound ] &&  return 0
    return 1
}

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

function start_mixer () {
    if egrep -q '(sparcaudio|sound)' /proc/devices 2>/dev/null && \
	[ "$retval" -eq 0 ] && [ -r /etc/.aumixrc ] && [ -x /usr/bin/aumix ];then
	action "Lade Mixer-Einstellungen" /usr/bin/aumix -f /etc/.aumixrc -L
    fi
}

function stop_mixer () {
   if egrep -q '(sparcaudio|sound)' /proc/devices 2>/dev/null && [ -x /usr/bin/aumix ];then
	action "Speichere Mixer-Einstellungen" /usr/bin/aumix -f /etc/.aumixrc -S
    fi    
}

case $1 in
    start)
    # if there is alsa driver in $conf_file load it and exit.
    start_alsa && exit
    retval=0
    module "Lade Sound-Modul" sound || retval=1
    module "Lade Sound-Module" sound-slot-0 || retval=1
    module "Lade MIDI-Modul" midi
    start_mixer;
    touch /var/lock/subsys/sound
   ;;
    stop)
    if [ -d /proc/asound ];then
	unload_alsa
	exit 0;
    fi
    stop_mixer;
    module "Entferne Sound-Modul" sound REMOVE
    module "Entferne Sound-Modul" sound-slot-0 REMOVE
    module "Entferne MIDI-Modul" midi REMOVE
    rm -f /var/lock/subsys/sound
    ;;
    status)
    if egrep -q '(sparcaudio|sound)' /proc/devices;then
	echo "Sound geladen"
    fi
    ;;
    reload)
    ;;
    restart)
    $0 stop
    $0 start
    ;;
    *)
    echo "Benutzung: $(basename $0) start|stop|restart|status"
    exit 0
esac

sysctl -w kernel.printk=$PKLVL
exit 0
