#!/bin/bash -eu

set -o pipefail

MYDIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
ROOT=$MYDIR/..

WORKSPACE_PATH="$ROOT/sandbox/ios/Sandbox.xcworkspace"
SCHEME="AstroTestHost"
TEST_DESTINATION="platform=iOS Simulator,name=iPhone 5s,OS=latest" # Use 5s as it's fastest to run because it's lowest resolution
FIXTURE_SERVER_PID=

# xcpretty makes output nicer
if [ ! "$(which xcpretty >/dev/null 2>&1)" ]; then
    XCPRETTY="xcpretty -s"
else
    XCPRETTY=cat
fi

shutdown() {
    echo "Shutting down..."

    # None of these command should cause this script to fail
    set +e

    echo "Killing fixture server..."
    pkill -P $FIXTURE_SERVER_PID
}

startFixtureServer() {
    # We need to turn off 'script abort on failure' so that our script doesn't 
    # abort if the fixture server is already running.
    set +e
    pushd "$ROOT" >/dev/null
        npm run fixture-server > /dev/null 2>&1 &
        FIXTURE_SERVER_PID=$!
    popd >/dev/null
    set -e
    echo "Started fixture server -> $FIXTURE_SERVER_PID"
    trap 'shutdown' EXIT
}

startFixtureServer

echo "Running iOS tests..."

xcodebuild \
    CODE_SIGNING_REQUIRED=NO \
    CODE_SIGN_IDENTITY= \
    PROVISIONING_PROFILE= \
    -workspace "$WORKSPACE_PATH" \
    -scheme "$SCHEME" \
    -destination "$TEST_DESTINATION" \
    -sdk iphonesimulator \
    -derivedDataPath "$ROOT/build" \
    -enableCodeCoverage YES \
    test 2>&1 | $XCPRETTY

