#!/bin/bash

# Find the directory containing this script.  This code is intended to be
# equivalent to $(dirname "$(readlink -f "$0")"), but it works on platforms
# that lack readlink -f, such as BSD/OSX.  It still needs readlink if $0 is a
# symlink.
scriptDir() {
    path=$0
    while test -L "$path"; do
        cd "$(dirname "$path")" || exit 1
        path=$(readlink "$(basename "$path")")
    done
    cd "$(dirname "$path")" && pwd
}

bin_dir="$(scriptDir)"
export BTRACE_LOG="$PWD/btrace.log"

# This code copies fakeroot's behavior by adding the library to the front of the
# LD_PRELOAD variable.
#
# TODO: It should follow fakeroot more closely by setting LD_LIBRARY_PATH to
# include both a 32-bit and (on appropriate hosts) a 64-bit library directory.
# It could then provide just the library basename to LD_PRELOAD, and the
# dynamic linker would pick an architecture-appropriate library, instead of
# warning about an incompatible library, as it currently does.

system=$(uname -s)
if test "$system" = "FreeBSD" -o "$system" = "Linux"; then
    # FreeBSD's ld.so man page states that LD_PRELOAD is either colon or
    # whitespace delimited.  Linux's ld.so man page states that LD_PRELOAD is
    # whitespace delimited, but Linux appears to accept either delimiter.
    ln -sf "$bin_dir/../tools/install/lib/libsw-btrace.so" /tmp/libsw-btrace.so
    export LD_PRELOAD="$LD_PRELOAD:/tmp/libsw-btrace.so"
else
    echo "Unsupported operating system: $system"
    exit 1
fi

"$@"
