#! /bin/sh

#
# Shell script to run another process with its
# sound device talking to a gdam server.
#

usage='
usage: '$0' [--server-path=path] program arg1 arg2 ...

gdamdsp runs a program with its sound output redirected
to a gdam server.

Options:
  --server-path=path         specify the path to the unix-domain socket
                             the server is listening on
  --so-file=sofile           specify alternate .so file to preload'

# How it works:
#  We LD_PRELOAD the gdamdsp.so library which overrides
#  the write(), open(), close(), and ioctl() calls.
found_location=""

while (test "$1" != "") do
  was_option=0
  case "$1" in
    --help | -h)
      echo "$usage"
      exit 1
      ;;
    --server-path)
      shift
      was_option=1
      gdamdsp_socket="$1";
      ;;
    --server-path=*)
      was_option=1
      gdamdsp_socket=`echo $1 | sed -e 's/--server-path=//'`
      ;;
    --so-file)
      shift
      found_location="$1"
      was_option=1
      ;;
  esac
  if test "$was_option" = "0"; then
    break
  fi
  shift
done

if test "$found_location" = ""; then
  for location in     /usr/local/lib/gdamdsppreload.so \
                      /usr/local/lib/gdam/gdamdsppreload.so \
                      /usr/lib/gdamdsppreload.so \
                      /usr/lib/gdam/gdamdsppreload.so \
                      /lib/gdamdsppreload.so \
                      /lib/gdam/gdamdsppreload.so \
		      ./gdamdsppreload.so \
		      .libs/gdamdsppreload.so                 ;          do
    if test -e $location; then
      found_location="$location"
      break
    fi
  done
fi

if test "$found_location" = ""; then
  echo "gdamdsp.so could not be found... sorry" 1>&2
  exit 1
fi

LD_PRELOAD="$found_location"
export LD_PRELOAD

GDAMDSP_SOCKET="$gdamdsp_socket"
export GDAMDSP_SOCKET
exec $*
