#!/bin/bash
# apmcontinue
# (C) Flav 14/08/2000
# created start/stop sound

#
# DO NOT EDIT THIS SCRIPT, CREATE AND EDIT APMCONTINUE IN THIS DIRECTORY; you
# can put your stuff into apmcontinue for every link you create to apmscript;
# for a start and definitely enough for most laptops we have two links and
# according subroutines defined here: suspend and resume; all other links
# will be redirected directly to apmcontinue which you can create; also
# suspend and resume call apmscript, so you can also do other things (like
# reinitialising some PCMCIA-Card) there; apmcontinue will get the name
# as which it was called as $1; for debugging see the logfiles
#

PROG="$1"
MYRESTORESOUND="yes"
MYRESTORESOUNDPROGS="yes"
MYSOUNDMODULES="/etc/rc.d/init.d/alsasound"

case "$PROG" in
    suspend)
	# nothing to do
	logger "nothing to do..."
	sync
	;;
    resume)
	if [ "$MYRESTORESOUND" = "yes" ]; then
	    # then we have to find all programs that use sound, because
	    # we have to stop them in order to restart the
	    # sound-system-driver
	    logger "apmcontinue: Restoring sound devices. Stopping programs:"
	    MYSOUNDPROGS=""
	    for n in `lsof |grep /dev|grep ' 14,'|sed -e 's/ \+/|/g'|cut '-d|' -f1-3`; do
	      MYSOUNDPROG=`echo $n|cut '-d|' -f1`
	      MYSOUNDPID=`echo $n|cut '-d|' -f2`
	      MYSOUNDUSER=`echo $n|cut '-d|' -f3`
	      MYSOUNDDISPLAY=`perl -e 's/\000/\n/g;' -p /proc/$MYSOUNDPID/environ|grep DISPLAY=|cut -d= -f2`
	      MYSOUNDPROGS="$n|$MYSOUNDDISPLAY $MYSOUNDPROGS"
	      kill "$MYSOUNDPID"
	      ps -ax "$MYSOUNDPID" &>/dev/null
	      [ "$?" = "0" ] && kill -9 "$MYSOUNDPID"
	      logger "apmcontinue: Program $MYSOUNDPROG ($MYSOUNDPID) of user $MYSOUNDUSER on display $MYSOUNDDISPLAY terminated."
	    done
	    # let's restart the sound-system-driver now
	    for m in $MYSOUNDMODULES; do
	      $m stop
	    done
	    for m in $MYSOUNDMODULES; do
	      $m start
	    done
	  fi
	  if [ "$MYRESTORESOUNDPROGS" = "yes" ]; then
	    # at least we can start the soundprograms again using
	    # the right display
	    for n in $MYSOUNDPROGS; do
	      MYSOUNDPROG=`echo $n|cut '-d|' -f1`
	      MYSOUNDPID=`echo $n|cut '-d|' -f2`
	      MYSOUNDUSER=`echo $n|cut '-d|' -f3`
	      MYSOUNDDISPLAY=`echo $n|cut '-d|' -f4`
	      su - "$MYSOUNDUSER" -c "source /etc/profile;[ -f ~/.bashrc ] && source ~/.bashrc;[ -f ~/.bash_profile ] && source ~/.bash_profile;export DISPLAY="$MYSOUNDDISPLAY";$MYSOUNDPROG &"
	      logger "apmcontinue: Program $MYSOUNDPROG started as user $MYSOUNDUSER on display $MYSOUNDDISPLAY."
	    done
	  fi
	  sync
          ;;
    *)
	  logger "FAIL: Wrong parameter \"$PROG\" in apmcontinue!"
	  exit 1
	  ;;
esac
