#!/bin/sh
# This script runs redis server and webdis server and launches the test
# suite. It avoids race condition while obtaining a port to listen by
# binding to random available port. The port is then found via netstat -nlp
# using PID-file.

TMPDIR=`mktemp -d`

WEBDIS_PIDFILE=${TMPDIR}/webdis.pid
WEBDIS_CONFFILE=${TMPDIR}/webdis.json
WEBDIS_LOGFILE=${TMPDIR}/webdis.log

REDIS_CONFFILE=${TMPDIR}/redis.conf
REDIS_PIDFILE=${TMPDIR}/redis.pid
REDIS_SOCK=${TMPDIR}/redis.sock

if [ -n "$WEBDIS_BIN" ] ; then
    if [ ! -x "$WEBDIS_BIN" ] ; then
        echo "webdis binary $WEBDIS_BIN is not executable"
        exit 1
    fi
else
    WEBDIS_BIN="$PWD/webdis"
fi

set_up() {
    echo "Generating config files.."
    sed -e "s|REDIS_SOCK|${REDIS_SOCK}|" -e "s|WEBDIS_PIDFILE|${WEBDIS_PIDFILE}|" \
        -e "s|WEBDIS_LOGFILE|${WEBDIS_LOGFILE}|" \
        debian/webdis-test.json > ${WEBDIS_CONFFILE}
    sed -e "s|REDIS_PIDFILE|${REDIS_PIDFILE}|" -e "s|REDIS_SOCK|${REDIS_SOCK}|" \
        debian/redis-test.conf > ${REDIS_CONFFILE}

    echo "Starting redis-server.."
    /sbin/start-stop-daemon --start --verbose \
        --pidfile ${REDIS_PIDFILE} \
        --exec `which redis-server` -- ${REDIS_CONFFILE} || return 1

    echo "Starting webdis.."
    /sbin/start-stop-daemon --start --verbose \
        --pidfile ${WEBDIS_PIDFILE} \
        --exec $WEBDIS_BIN -- ${WEBDIS_CONFFILE} || return 2

    WEBDIS_PID=`cat $WEBDIS_PIDFILE`
    export WEBDIS_PORT=`grep -o 'listening on port.*$' ${WEBDIS_LOGFILE}| \
        tail -1|cut -d " " -f 4`
    [ "0$WEBDIS_PORT" -gt 0 ] || return 3
    echo webdis is listening on port "$WEBDIS_PORT"
}

tear_down() {
    echo "Shutting down webdis.."
    /sbin/start-stop-daemon --stop --verbose \
        --retry=TERM/1/KILL/1 \
        --pidfile ${WEBDIS_PIDFILE} \
        --name webdis
    echo "Shutting down redis-server.."
    /sbin/start-stop-daemon --stop --verbose \
        --retry=TERM/1/KILL/1 \
        --pidfile ${REDIS_PIDFILE} \
        --name redis-server
}

if ! set_up ; then
    echo "Setting up redis/webdis server FAILED."
    tear_down
    exit 1
fi

echo Running test commands: $*

$*
EXIT_CODE=$?

tear_down
rm -fR $TMPDIR

exit $EXIT_CODE
