#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export PYTHONPATH=$DIR/../src/main/python:$DIR/../lib/python:$PYTHONPATH

if [ -n "$GPU" ]; then
    if [[ "$GPU" == gpu* ]]; then
        echo "Requesting a specific GPU: $GPU"
        gpu_name="$GPU"
    else
        gpu_name="gpu"
    fi
    export THEANO_FLAGS='device='"$gpu_name"',floatX=float32'
fi

if [ -n "$PROFILER" ]; then
    # Run the profiler instead of ordinary python
    # Allows you to profile any script by just putting:
    #  PROFILER=1
    # in front of the command
    profile_out=$DIR/../working/profile
    echo "Profiling, output to $profile_out" >&2
    if [ "$1" == "-m" ]; then
        shift
        # Try to convert to filename
        echo "Cannot run profiler on module name: trying to convert to script name"
        script_name="$DIR/../src/main/python/${1//.//}.py"
        echo "  Trying $script_name"
        # Replace arg 1
        set -- $script_name "${@:2}"
    fi
    /usr/bin/env python $PYARGS -m cProfile -o $DIR/../working/profile $*
elif [ -n "$MEMPROFILER" ]; then
    # Similar, does memory profiling
    echo "Memory profiling"
    /usr/bin/env python -m memory_profiler $*
elif [ -n "$GDB" ]; then
    echo "Running Python from gdb"
    gdb -ex r --args python $*
else
    /usr/bin/env python $*
fi
