#!/bin/bash

usage() {
	echo "Usage: $0 -[t12x] [-p <libdlock.so lib>] [-l <log file>] [-e <action to take>] PROGRAM [ARGS]"
	printf "\t-p path\t\tpath to libdlock.so\n"
	printf "\t-t\t\trecord lock timings\n"
	printf "\t-1\t\tdump a trace upon SIGUSR1\n"
	printf "\t-2\t\tdump a trace upon SIGUSR2\n"
	printf "\t-x\t\tdump a trace when the program exits\n"
	printf "\t-l file\t\tdump to file instead of stderr\n"
	printf "\t-e value\tbehaviour on bad locking:\n"
	printf "\t\t\t 0: the error is simply ignored\n"
	printf "\t\t\t 1: call abort()\n"
	printf "\t\t\t 2: call exit()\n"
	printf "\t\t\t 3: issue a dump\n"
}
#
# Arg parsing stuff
#
DLOCK_FLAGS=0
while getopts 12txep:l:h name
do
	case $name in
		p)
			DLOCK_LIB="$OPTARG";;
		t)
			DLOCK_FLAGS=$(($DLOCK_FLAGS | (1 << 0)));;
		1)
			DLOCK_FLAGS=$(($DLOCK_FLAGS | (1 << 1)));;
		2)
			DLOCK_FLAGS=$(($DLOCK_FLAGS | (1 << 2)));;
		x)
			DLOCK_FLAGS=$(($DLOCK_FLAGS | (1 << 3)));;
		l)
			DLOCK_FLAGS=$(($DLOCK_FLAGS | (1 << 4)))
			DLOCK_LOG_FILE="$OPTARG";;
		e)
			DLOCK_ON_ERROR="OPTARG";;
		h|?)
			usage
			exit 2;;
	esac
done
shift $(($OPTIND - 1))

#
# Little trick to find the path of libdlock.so in our system
# this is needed to LD_PRELOAD dlock (see the end of file)
#
if [ -z "$DLOCK_LIB" ]
then
	#Use which to find the library
	WHICH_BIN=$(which which)
	LIBS_PATH=$LD_LIBRARY_PATH:/lib:/usr/lib
	DLOCK_LIB=$(bash -c "PATH=$LIBS_PATH $WHICH_BIN libdlock.so")

	# Not found still, die
	if [ -z "$DLOCK_LIB" ]
	then
		echo "Cannot find libdlock.so in ($LIBS_PATH)"
		exit -1
	fi
fi

DLOCK_FLAGS=$DLOCK_FLAGS DLOCK_LOG_FILE=$DLOCK_LOG_FILE LD_PRELOAD=$DLOCK_LIB "$@"
