#!/bin/sh

# vmtest
# 
# Runs all SDK unit tests using a particular version of PHP and Splunk.
# 
# Requires Vagrant and VirtualBox.
# 
# If using the "host" Splunk version, the host OS must be running a
# Splunk server on port 8089 (the default) with an admin account whose
# password is "weak".
# 
# Examples:
#   ./vmtest 5.3.10 4.3.2
#   ./vmtest 5.2.11 host
# 
# For syntax, run this command with no arguments.

# (fail immediately upon subsequent errors)
set -o errexit

# Read arguments
PHP_VERSION=$1
SPLUNK_VERSION=$2
if [[ -z "$PHP_VERSION" || -z "$SPLUNK_VERSION" ]]; then
    echo 'syntax: vmtest.sh <php-version> <splunk-version OR "host">'
    exit 1
fi

# Bring VMs online (if not already)
vagrant up php-$PHP_VERSION
if [ "$SPLUNK_VERSION" != "host" ]; then
    vagrant up splunk-$SPLUNK_VERSION
fi

# Configure PHP VM to point to Splunk VM
if [ "$SPLUNK_VERSION" != "host" ]; then
    SPLUNK_IP_CMD="ruby -e 'require \"boxes.rb\"; print BOX_NAME_2_IP[\"splunk-$SPLUNK_VERSION\"]'"
    SPLUNK_IP=`sh -c "$SPLUNK_IP_CMD"`
else
    HOST_OS_IP=`ifconfig | grep 'inet ' | grep -v '127.0.0.1' | grep -v '192.168.50.' | awk '{ print $2 }'`
    if [ -z "$HOST_OS_IP" ]; then
        echo "Unable to determine IP of host OS."
        exit 1
    fi
    SPLUNK_IP=$HOST_OS_IP
fi
vagrant ssh php-$PHP_VERSION -c "sudo sed -i \"s/^.* splunk.vm.local$/$SPLUNK_IP splunk.vm.local/\" /etc/hosts"

# Run unit tests in PHP VM
echo
vagrant ssh php-$PHP_VERSION -c 'cd /vagrant_data; phpunit tests'
