#!/bin/sh

malloc_logger ()
{
    while IFS="" read line
    do
        logger -t malloc-preloader "Available malloc library: $line"
        echo "$line"
    done
}

malloc_find ()
{
    find "/usr/lib64/" -name "libtcmalloc.so.?.?.?"
}

malloc_filter ()
{
    sort -r | head -n1
}

malloc_select ()
{
    malloc_find | malloc_logger | malloc_filter
}

if [ "w$TCMALLOC_LIBRARY" = "w" ]; then
    TCMALLOC_LIBRARY=`malloc_select`
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 "$@"
