#!/bin/sh
# setting-up jackd sound server
# 
# (c) 2006, Eko M. Budi for Vector Linux
# License: GNU GPL

JACK_OPTIONS=${JACK_OPTIONS}
if [ -z $JACK_DEVICE ]; then
  if [ -d /proc/asound ]; then
    JACK_DEVICE=alsa
  else
    DEVICE=oss
  fi
fi
ALSA_OPTIONS=${ALSA_OPTIONS:-"-s -r 44100"}
OSS_OPTIONS=${OSS_OPTIONS:-"-r 44100"}

if [ -x /etc/sysconfig/jackd ]; then
   . /etc/sysconfig/jackd
fi

function alsa_set_jack() {
cat<< EOF
# set alsa default to jackd
# if you dont want jack as the default,
# change the pcm.default section below to pcm.jackplug
# then on your applications, set "jackplug" as the alsa channel
pcm.!default {
    type plug
    slave { pcm "jack" }
}

pcm.jack {
    type jack
    playback_ports {
        0 alsa_pcm:playback_1
        1 alsa_pcm:playback_2
    }
    capture_ports {
        0 alsa_pcm:capture_1
        1 alsa_pcm:capture_2
    }
}

EOF

}

if [ "$JACK_DEVICE" = "alsa" ]; then
  if startsound-alsa ; then
    # copy jackd settings
    if which jackd &>/dev/null; then
       if [ "`/sbin/modprobe --list realtime`" ]; then
          echo Starting jackd using realtime-lsm
          jackd -R -d alsa $ALSA_OPTIONS &
          PID=$!
       elif which set_rlimits &>/dev/null ; then
          echo Starting jackd using set_rlimits
          set_rlimits jackd -R -d alsa $ALSA_OPTIONS &
          PID=$!
       else
          echo Starting jackd without realtime capability
          jackd -d alsa $ALSA_OPTIONS &
          PID=$!
       fi
       echo "Jackd started pid=$PID"
       if [ "$PID" ]; then
	  # give time for jackd
	  sleep 3
	  echo "Setting up alsa jackd"
          rm -f $HOME/.asoundrc
	  if [ ! -f $HOME/.asoundrc.jack ]; then
	    set_jack > $HOME/.asoundrc.jack
	  fi
	  (cd $HOME; ln -sf .asoundrc.jack .asoundrc)
	  echo "Redirecting oss to jackd"
	  exec oss2jack
	  # if oss2jack was failed, must wait
	  wait $PID
	  exit 0
       fi
    fi
    
    # cannot setup jackd, use dmix
    echo "ERROR: cannot run jackd"
    echo "Setting up alsa dmix"
    if [ ! -f $HOME/.asoundrc.dmix ]; then
      set_dmix > $HOME/.asoundrc.dmix
    fi
    (cd $HOME; ln -sf .asoundrc.dmix .asoundrc)
  fi
elif [ "$JACK_DEVICE" = "oss" ]; then
  if [ "`/sbin/modprobe --list realtime`" ]; then
    echo Starting jackd using realtime-lsm
    jackd -R -d oss $OSS_OPTIONS &
  elif which set_rlimits &>/dev/null ; then
    echo Starting jackd using set_rlimits
    set_rlimits jackd -R -d oss $OSS_OPTIONS &
  else
    echo Starting jackd without realtime capability
    jackd -d oss $OSS_OPTIONS &
  fi
else
  echo "ERROR: jackd cannot run without alsa/oss"
  exit 1
fi

