#!/bin/bash

. /etc/rc.conf
. /etc/rc.d/functions

terminateapps() {
    # Thanks to the Gentoo ebuild/start script for the following
    # http://bugs.gentoo.org/show_bug.cgi?id=184123
    # http://bugs.gentoo.org/attachment.cgi?id=153689
    devs=`perl -e '{while (<>) {m/^(\S*)/; print "/dev/$1\n"}}' \
		< /proc/opensound/devfiles`
    fuser -k ${devs}  >/dev/null 2>/dev/null
}

case "$1" in
  start)
    stat_busy "Starting OSS/Open source driver"
    # start
    /usr/sbin/soundon
    if [ $? -gt 0 ]; then
      stat_fail
    else
      grep '^softoss' /proc/modules >/dev/null 2>/dev/null
      if [ $? -eq 0 ]; then
        stat_busy "Replacing old \"softoss\" module with \"vmix\""
        rmmod softoss
        modprobe vmix
        sed -i 's/^softoss.*$/vmix/' /usr/lib/oss/etc/installed_drivers
      fi
      add_daemon oss-linux-free
      stat_done
    fi
    ;;
  stop)
    stat_busy "Saving OSS mixer"
    /usr/sbin/savemixer
    if [ $? -gt 0 ]; then
      stat_fail
    else
      stat_done
    fi
    grep '^"cuckoo"' /proc/modules >/dev/null 2>/dev/null
    if [ $? -eq 0 ]; then
      stat_busy "Removing \"cuckoo\" module"
      rmmod cuckoo
    fi
    stat_busy "Killing processes using OSS"
    terminateapps
    stat_done
    # It doesn't matter if it didnt kill anything!
    stat_busy "Stopping OSS/Open source driver"
    /usr/sbin/soundoff
    if [ $? -gt 0 ]; then
      stat_fail
    else
      rm_daemon oss-linux-free
      stat_done
    fi
    ;;
  restart)
    $0 stop
    sleep 1
    $0 start
    ;;
  terminateapps)
    stat_busy "Killing processes using OSS"
    terminateapps
    stat_done
    # It doesn't matter if it didnt kill anything!
  ;;
  *)
    echo "usage: $0 {start|stop|restart|terminateapps}"
esac