#!/bin/bash

# Copyright (C) 2006  Thomas Sondergaard
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# on the rights to use, copy, modify, merge, publish, distribute, sub
# license, and/or sell copies of the Software, and to permit persons to whom
# the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
# IBM AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# Authors:
#    Thomas Sondergaard <ts@medical-insight.com>

usage="usage: $0 [ -hctev ] [-l LOGFILE] program [args...]\n\t-h\t\thelp (this text)\n\t-c\t\tlog gl calls\n\t-t\t\ttime stamp log entries\n\t-e\t\tcheck for and log errors. errors occurring between\n\t\t\tglBegin() and glEnd() are checked at glEnd()\n\t-v\t\tverbose. Shows configuration settings passed to\n\t\t\tgltrace.so\n\t-l LOGFILE\tlogfile. Default is stderr"

# Path to gltrace.so - must not be relative
#GLTRACE_SO=/home/ts/Mesa_gltrace/src/mesa/glapi/gltrace.so
# This seems to work:
GLTRACE_SO=./gltrace.so

# Set options from command line 

VERBOSE=0
GLTRACE_LOG_CALLS=0
GLTRACE_LOG_TIME=0
GLTRACE_CHECK_ERRORS=0
export GLTRACE_LOG_CALLS GLTRACE_LOG_TIME GLTRACE_CHECK_ERRORS

if [ $# -eq 0 ]; then
    echo -e $usage
    exit
fi

while getopts "hctevl:" options; do
    case $options in
	h) echo -e $usage
	    exit 1;;
	c) GLTRACE_LOG_CALLS=1;;
	t) GLTRACE_LOG_TIME=1;;
	e) GLTRACE_CHECK_ERRORS=1;;
	l) GLTRACE_LOGFILE=$OPTARG
	    export GLTRACE_LOGFILE;;
	v) VERBOSE=1;;
	*) echo -e $usage
	    exit 1;;
    esac
done

# Remove the parsed args
shift $(($OPTIND-1))

if [ ! -r $GLTRACE_SO ]; then
    echo "Error: The gltrace.so file '$GLTRACE_SO' is missing!"
    exit 1
fi

export LD_PRELOAD=$GLTRACE_SO

if [ $VERBOSE -eq 1 ]; then
 echo GLTRACE_LOG_CALLS=$GLTRACE_LOG_CALLS
 echo GLTRACE_LOG_TIME=$GLTRACE_LOG_TIME
 echo GLTRACE_CHECK_ERRORS=$GLTRACE_CHECK_ERRORS
 echo GLTRACE_LOGFILE=$GLTRACE_LOGFILE
 echo LD_PRELOAD=$LD_PRELOAD
 echo command=$*
fi

exec $*
