#!/bin/sh
#
#  Run an application with libmonitor.so and callback functions linked
#  dynamically with LD_PRELOAD.
#
#  Usage: monitor-run [options] command arg ...
#
#     -d, --debug
#     -h, --help
#     -i, --insert  <file.so>
#
#  where <file.so> is a shared object file containing definitions of
#  the callback functions (may be used multiple times).
#
#  A monitor client should provide a script for wrapping an application
#  with its own callback functions via LD_PRELOAD, possibly using this
#  script as a starting point.
#
#  This script is in the public domain.
#
#  $Id$
#

prefix="/usr"
exec_prefix="/usr"
libdir="/usr/lib64"
libmonitor="${libdir}/libmonitor.so"

# Colon-separated list of extra path names for LD_PRELOAD.
preload_files=

die()
{
    echo "$0: error: $*" 1>&2
    exit 1
}

usage()
{
    cat <<EOF
Usage: $0 [options] command arg ...

   -d, --debug
   -h, --help
   -i, --insert  <file.so>

where <file.so> is a shared object file containing definitions of
the callback functions (may be used multiple times).

EOF
    exit 0
}

#
# Our options come first.
#
while test "x$1" != x
do
    case "$1" in
	-d | --debug )
	    export MONITOR_DEBUG
	    MONITOR_DEBUG=1
	    shift
	    ;;

	-h | --help )
	    usage
	    ;;

	-i | --insert )
	    # LD_PRELOAD prefers absolute path.
	    test "x$2" != x || die "missing argument: $*"
	    case "$2" in
		/* )  file="$2" ;;
		* )   file="`pwd`/$2" ;;
	    esac
	    test -f "$file" || die "unable to find: $file"
	    preload_files="${preload_files}:${file}"
	    shift ; shift
	    ;;

	-- )
	    shift
	    break
	    ;;

	-* )
	    die "unknown option: $1"
	    ;;

	* )
	    break
	    ;;
    esac
done

#
# Must have at least a command name.
#
test "x$1" != x || usage

test -f "$libmonitor" || die "unable to find: $libmonitor"
LD_PRELOAD="${preload_files}:${libmonitor}:${LD_PRELOAD}"
export LD_PRELOAD

exec "$@"
