#!/bin/bash
export PID=$$
mkdir data-$PID

self=$0
if test -f "${self}.js"; then 
    export SCRIPT=${self}.js
else
    export SCRIPT=$1
    shift
fi

if test -n "$ORIGINAL_PATH"; then
# running in cygwin...
    PS='\'
    export EXT=".exe"
else
    export EXT=""
    PS='/'
fi;

export PORT=`expr 1024 + $RANDOM`
declare -a ARGS
export VG=''
export VXML=''
for i in "$@"; do
    # no valgrind on cygwin, don't care.
    if test "$i" == valgrind; then
      export VG='/usr/bin/valgrind --log-file=/tmp/valgrindlog.%p'
    elif test "$i" == valgrindxml; then
      export VG='/usr/bin/valgrind --xml=yes --xml-file=valgrind_testrunner'
      export VXML="valgrind=\"${VG}\""
      export VG=${VG}'.xml '
    else
      ARGS+=(--javascript.script-parameter)
      ARGS+=("$i")
    fi
done
mkdir out
echo Database has its data in out${PS}data-$PID
echo Logfile is in out${PS}log-$PID
$VG bin/arangod \
    --configuration none \
    --cluster.agent-path bin${PS}etcd-arango${EXT} \
    --cluster.arangod-path bin${PS}arangod \
    --cluster.coordinator-config etc${PS}relative${PS}arangod-coordinator.conf \
    --cluster.dbserver-config etc${PS}relative${PS}arangod-dbserver.conf \
    --cluster.disable-dispatcher-frontend false \
    --cluster.disable-dispatcher-kickstarter false \
    --cluster.data-path cluster \
    --cluster.log-path cluster \
    --database.directory out${PS}data-$PID \
    --log.file out${PS}log-$PID \
    --server.endpoint tcp://127.0.0.1:$PORT \
    --javascript.startup-directory js \
    --javascript.app-path js${PS}apps \
    --javascript.script $SCRIPT \
    --no-server \
    --temp-path ${PS}var${PS}tmp \
    "${ARGS[@]}" \
    $VXML

if test $? -eq 0; then
  echo removing out${PS}log-$PID out${PS}data-$PID
  rm -rf out${PS}log-$PID out${PS}data-$PID
else
  echo "failed - don't remove out${PS}log-$PID out${PS}data-$PID - heres the logfile:"
  cat out${PS}log-$PID
fi

echo Server has terminated.
