#!/bin/bash
set -e
set -o xtrace

gdb=0
lldb=0
vlgrd=0

usage()
{
    echo "Usage: $0 [-g] [phpunit arguments]" 1>&2
    exit 1
}

while getopts "glm" o; do
    case "${o}" in
        g)
            gdb=1
            ;;
        l)
            lldb=1
            ;;
        m)
            vlgrd=1
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

EXTENSION=pux

PHP=php
PHPUNIT=phpunit

type php
type phpunit

if [[ -n `type php | grep phpenv` ]] ; then
    PHP=$(phpenv which php)
else
    PHP=$(command which php)
fi

if [[ -n `type phpunit | grep phpenv` ]] ; then
    PHPUNIT=$(phpenv which phpunit)
else
    PHPUNIT=$(command which phpunit)
fi

# add the json extension if it's not compiled in
ORIG_EXTENSION_DIR=`$PHP -i | grep extension_dir | awk '{ print $3 }'`
EXTRA=
if [[ -f "$ORIG_EXTENSION_DIR/json.so" ]] ; then
    EXTRA="$EXTRA -d extension=$ORIG_EXTENSION_DIR/json.so"
fi

if [[ $gdb == 1 ]] ; then
    # write .gdbinit, here is the template
    cat <<END > .gdbinit
# AUTO-GENERATED GDBINIT FILE FOR PHP
file $PHP
set args \\
    -c $PWD/php.ini \\
    -d "extension=$PWD/modules/$EXTENSION.so" \\
    -n $EXTRA $PHPUNIT $*
END
    for file in .gdbinit.* ; do
        echo "source $file" >> .gdbinit
    done

    # execute gdb
    gdb
elif [[ $lldb == 1 ]] ; then
    lldb -- $PHP \
        -c $PWD/php.ini \
        -d extension=$PWD/modules/$EXTENSION.so \
        -n $EXTRA $PHPUNIT $*
elif [[ $vlgrd == 1 ]] ; then
    valgrind --leak-check=full -- $PHP \
        -c $PWD/php.ini \
        -d extension=$PWD/modules/$EXTENSION.so \
        -n $EXTRA $PHPUNIT $*
else

    $PHP  \
        -c $PWD/php.ini \
        -d "extension=$PWD/modules/$EXTENSION.so" \
        -n $EXTRA $PHPUNIT $*

fi
