#!/bin/sh

if [ "w$TCMALLOC_LIBRARY" = "w" ]; then
    TCMALLOC_LIBRARY="/usr/lib64/libtcmalloc_minimal.so.4.1.2"
fi

case "$MEMORY_ALLOCATOR" in
    "auto"|"")
        MEMORY_ALLOCATOR="$TCMALLOC_LIBRARY"
    ;;
    "system")
        MEMORY_ALLOCATOR=""
    ;;
esac

if [ "w$MEMORY_ALLOCATOR" != "w" ]; then
    if [ -e "$MEMORY_ALLOCATOR" ]; then
        logger -t malloc-preloader "Running $1 with $MEMORY_ALLOCATOR memory allocator..."
        export LD_PRELOAD="$MEMORY_ALLOCATOR"
    else
    	logger -t malloc-preloader "Unable to set $1 memory allocator to \"$MEMORY_ALLOCATOR\": file does not exist!"
    fi
else
    logger -t malloc-preloader "Running $1 with system default memory allocator..."
fi

exec "$@"
