#!/bin/sh

# When one sets the environment variable P4VHOST, its value will be prepended
# on the command running the executable.
# This will allow customers or support to run the executable in the environment
# provided by this script from 'ldd', 'gdb', 'strace' etc .....
# example:
#	bash$ P4VHOST=ldd ./p4v

getrealfullprogname()
{
    # If possible, handle the case that someone has created a symlink in
    # /usr/local/bin back to this script in its original unpacked
    # distribution directory.
    thisfile=`{ readlink -f "$1" \
                || { ls -ld "$1" | sed -n -e 's/.* -> //p'; }
              } 2> /dev/null`
    case $thisfile in
        '' ) thisfile=$1 ;;
    esac

    echo "$thisfile"
}

topdir()
{
    progdir=`dirname "$1"`
    case $progdir in
        . | '' | "$1" ) progdir=`pwd` ;;
    esac

    case $progdir in
        */bin ) topdir=`dirname "$progdir"` ;;
        *     ) topdir=$progdir ;;
    esac

    echo "$topdir"
}

main()
{
    realfullprogname=`getrealfullprogname "$0"`
            progname=`basename "$realfullprogname"`
              prefix=`topdir   "$realfullprogname"`

    # check for symbolic links for libssl.so and libcrypto.so
    if [ ! -f $prefix/lib/libssl.so ]; then
        p4vlibssl=$( find $prefix/lib/libssl.so.* )
        ln -s $p4vlibssl $prefix/lib/libssl.so;
        p4vlibcrypto=$( find $prefix/lib/libcrypto.so.* )
        ln -s $p4vlibcrypto $prefix/lib/libcrypto.so;
    fi

    XDG_SESSION_TYPE=
    QT_QPA_PLATFORM=xcb
    P4VRES=$prefix/lib/P4VResources
    LD_LIBRARY_PATH=$prefix/lib${LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}
    QT_PLUGIN_PATH=$prefix/lib/plugins
    PATH=$prefix/bin:$PATH
    export XDG_SESSION_TYPE QT_QPA_PLATFORM P4VRES LD_LIBRARY_PATH PATH QT_PLUGIN_PATH

    exec $P4VHOST "$prefix/bin/$progname.bin" "$@" || exit $?
}

main "$@"

# eof
