#!/bin/sh -ue

readonly LAUNCHER_LOGPATH='/var/log/kaspersky/kesl/kesl_launcher.log'
readonly KL_LOG_DIRECTORY='/var/log/kaspersky/'
readonly LOG_DIRECTORY='/var/log/kaspersky/kesl/'

if [ ! -d "${KL_LOG_DIRECTORY}" ] ; then
    mkdir "${KL_LOG_DIRECTORY}" -m 755 || true
fi

if [ ! -d "${LOG_DIRECTORY}" ] ; then
    mkdir "${LOG_DIRECTORY}" -m 700 || true
fi

touch "${LAUNCHER_LOGPATH}" || true
chmod 600 "${LAUNCHER_LOGPATH}" || true

launcherRedirectStatus=0
exec 2>>"${LAUNCHER_LOGPATH}" || launcherRedirectStatus=$?
if [ ${launcherRedirectStatus} -eq 0 ] ; then
    set -x
fi    

exec 1>&2 || true

echo "Running $0 ..."

export MALLOC_CONF=retain:false

if [ -f '/opt/kaspersky/kesl/lib64/libjemalloc.so' ]; then
    LD_PRELOAD='/opt/kaspersky/kesl/lib64/libjemalloc.so'":${LD_PRELOAD:-}"
fi

if lsmod | fgrep -q 'parsec'; then
    if [ ! -z "${LD_PRELOAD:-}" ]; then
        exec '/usr/sbin/execaps' -c 0x300 -- /bin/sh -c "LD_PRELOAD=$LD_PRELOAD /opt/kaspersky/kesl/libexec/kesl $*"
    else
        exec '/usr/sbin/execaps' -c 0x300 -- '/opt/kaspersky/kesl/libexec/kesl' "$@"
    fi
else
    if [ ! -z "${LD_PRELOAD:-}" ]; then
        export LD_PRELOAD
    fi
    exec '/opt/kaspersky/kesl/libexec/kesl' "$@"
fi
