#!/bin/bash

realpath() {
 local p=$1
 if [ "$(echo $p | sed 's/^\(.\).*$/\1/')" != "/" ]; then
   p="`pwd`/$p"
 fi
 echo $p | sed 's#/[^/]\+/\.\.##g';
}

RESIDING_IN="$(realpath $(dirname $0))"
CALLED_AS="$(basename $0)"

ENVOY_BINARY_PATH="$(realpath ${RESIDING_IN}/../libexec/envoy/)"
if uname -a | grep -q "x86_64"; then
  ENVOY_LIB_PATH="$(realpath ${RESIDING_IN}/../lib64/envoy/)"
else
  ENVOY_LIB_PATH="$(realpath ${RESIDING_IN}/../lib/envoy/)"
fi

export LD_LIBRARY_PATH=${ENVOY_LIB_PATH}
export QT_PLUGIN_PATH=${ENVOY_LIB_PATH}
# only enable core dumps for those processes started as root (most likely envoyserver and envoyrobot)
if [[ "$(whoami)" == "root" ]]; then
  # enable core dumps
  ulimit -c unlimited
  # set core dump name pattern to core-<executable name>-pid-<pid>-sig-<signal which killed process>-time-<unix timestamp of death>-host-<hostname> and store core dumps in /tmp
  sysctl -w kernel.core_pattern="/tmp/core-%e-pid-%p-sig-%s-time-%t-host-%h"
fi
${ENVOY_BINARY_PATH}/${CALLED_AS} "$@"

