#!/bin/sh
# -*- Mode: shell-script -*-

[ -e /etc/sysconfig/apmd ] && . /etc/sysconfig/apmd

if [ "$RESTORESOUND" = "yes" -o "$RESTORESOUNDPROGS" = "yes" ]; then
    # Find all programs using sound and kill them...
    rm -rf /var/run/apm-soundprogs
    if [ -c /dev/sndstat ]; then
	for n in `cat /dev/sndstat 2>/dev/null|grep Open\ by|awk {'print $3'}|uniq`; do
	    SOUNDPROG=`echo $n|awk -F / {'print $2'}`
	    SOUNDPID=`echo $n|awk -F / {'print $1'}`
	    SOUNDUSER=`ls -ld /proc/$SOUNDPID |awk {'print $3'}`
	    SOUNDDISPLAY=`perl -e 's/\000/\n/g;' -p /proc/$SOUNDPID/environ|grep ^DISPLAY=|cut -d= -f2-`

    	    # Make sure nobody is playing foul tricks on us
	    SOUNDPROG=`echo $SOUNDPROG |sed -e "s/|.*//`

	    kill $SOUNDPID
	    ps "$SOUNDPID" &>/dev/null && kill -9 $SOUNDPID
	    echo "$SOUNDPROG|$SOUNDPID|$SOUNDUSER|$SOUNDDISPLAY" >>/var/run/apm-soundprogs
	    logger "apmscript: Program $SOUNDPROG ($SOUNDPID) of user $SOUNDUSER on display $SOUNDDISPLAY terminated."
	done
    fi
    for n in `lsof |grep /dev|grep ' 14,'|sed -e 's/ \+/|/g'|cut '-d|' -f1-3`; do
	SOUNDPROG=`echo $n |cut '-d|' -f1`
	SOUNDPID=`echo $n |cut '-d|' -f2`
	SOUNDUSER=`echo $n |cut '-d|' -f3`
	SOUNDDISPLAY=`perl -e 's/\000/\n/g;' -p /proc/$SOUNDPID/environ|grep ^DISPLAY=|cut -d= -f2-`

			# Make sure nobody is playing foul tricks on us
	SOUNDPROG=`echo $SOUNDPROG |sed -e "s/|.*//`

	kill $SOUNDPID
	ps "$SOUNDPID" &>/dev/null && kill -9 $SOUNDPID
	echo "$SOUNDPROG|$SOUNDPID|$SOUNDUSER|$SOUNDDISPLAY" >>/var/run/apm-soundprogs
	logger "apmscript: Program $SOUNDPROG ($SOUNDPID) of user $SOUNDUSER on display $SOUNDDISPLAY terminated."
    done
    # We unload the modules later to give the driver some time
    # to spin down.
fi
