#!/bin/sh
# "/bin/sh" is used intentionally instead of /bin/bash to make sure
# that the script works well on Busybox-based systems.

# Get directory of the script
origin=`dirname "$0"`
origin=`cd "$origin" && pwd`

if [ "`basename "$origin"`" = "bin64" ]; then
    this_arch="64"
    that_arch="32"
    that_arch_short="32"
elif [ "`basename "$origin"`" = "bin32" ]; then
    this_arch="32"
    that_arch="64"
    that_arch_short="64"
elif [ "`basename "$origin"`" = "ia32" ]; then
    origin=`dirname "$origin"`
    this_arch="/ia32"
    that_arch="/intel64"
    that_arch_short="64"
elif [ "`basename "$origin"`" = "intel64" ]; then
    origin=`dirname "$origin"`
    this_arch="/intel64"
    that_arch="/ia32"
    that_arch_short="32"
else
    echo Bad directory structure for $origin
    exit 1
fi

origin=`dirname "$origin"`

# Libraries are found relative to origin
lib_base="$origin"
cpp_libs="$lib_base/lib$this_arch/pinruntime:$lib_base/lib$that_arch/pinruntime"
glibc_libs="$lib_base/lib$this_arch/pinruntime/glibc:$lib_base/lib$that_arch/pinruntime/glibc"
# vm/tool need cpp and glibc libs
export PIN_VM_LD_LIBRARY_PATH=$cpp_libs:$glibc_libs:$LD_LIBRARY_PATH

# If variables we are going to modify are set, save the value. They will be restored 
# after the injector starts
export PIN_LD_RESTORE_REQUIRED=t
if [ -n "${LD_LIBRARY_PATH+x}" ]
then
    export PIN_APP_LD_LIBRARY_PATH=$LD_LIBRARY_PATH
fi
if [ -n "${LD_ASSUME_KERNEL+x}" ]
then
    export PIN_APP_LD_ASSUME_KERNEL=$LD_ASSUME_KERNEL
fi
unset LD_ASSUME_KERNEL

if [ -n "${LD_BIND_NOW+x}" ]
then
    export PIN_APP_LD_BIND_NOW=$LD_BIND_NOW
fi

if [ -n "${LD_PRELOAD+x}" ]
then
    export PIN_APP_LD_PRELOAD=$LD_PRELOAD
fi
unset LD_PRELOAD

# injector just needs cpp libs, it cannot use glibc lib
export LD_LIBRARY_PATH=$cpp_libs:$LD_LIBRARY_PATH

exec "$origin"/bin$this_arch/pinbin -p$that_arch_short "$origin"/bin$that_arch/pinbin "${@}"
