#!/bin/sh
: ${PCT_FMT:="sym%"}
: ${PCT_OUT:="/tmp/pct/ct.$$"}
: ${PCT_OPT:=""}
pct="${PCT_OPT}o${PCT_OUT}"

usage () {
    echo  Usage:
    echo "    $0 [-v] PROGRAM ARGS..."
    echo  runs PROGRAM ARGS under the itimer-base PCT profiling system.
}

if [ $# -lt 1 ]; then
    usage 1>&2
    exit 1
fi

VERBOSE=0
case $1 in
    -v) VERBOSE=1
        shift 1  ;;
    -*) usage 1>&2
        exit 1 ;;
esac

if file $1 | grep -q static; then
    if nm $1 | grep -q '\<pct_init\>'; then
        :
    else
        echo $1 is statically linked 1>&2
        exit 1
    fi
fi

LD_PRELOAD=${LIB_SO:-"/usr/local/lib"}/libitimer.so
export LD_PRELOAD

if [ $VERBOSE -eq 1 ]; then
    echo profile: using PCT=v$pct 1>&2
    PCT="v$pct" "$@"  # Run program with PCT environ var set: verbose
else
    PCT="$pct"  "$@"  # Run program with PCT environ var set: quiet
fi

pct $PCT_FMT `find $PCT_OUT -type f -print` 1>&2
