#!/usr/bin/env bash

# Should exit if docker is not installed on system
if ! hash docker 2>/dev/null; then
    echo "You must have docker installed to run these tests"
    exit 1
else
    POSTGRES_CONTAINER=`docker ps -q -f status=running -f name=postgres-slave`
    if [ -z "$POSTGRES_CONTAINER" ]; then
        POSTGRES_CONTAINER=`docker ps -q -f status=exited -f status=created -f name=postgres-slave`
        if [ -z "$POSTGRES_CONTAINER" ]; then
            POSTGRES_CONTAINER=`docker run --name postgres-slave -e POSTGRES_USER=apps -e POSTGRES_PASSWORD=apps -e POSTGRES_DB=apps_consumer -p 5432:5432 -d trinitymirror/apps-consumer-slave`
        else
            docker start postgres-slave
        fi
    fi
    POSTGRES_IP=`docker inspect --format='{{.NetworkSettings.IPAddress}}' $POSTGRES_CONTAINER`
    # Wait for the postgres port to be available
    while ! timeout 1 bash -c "echo > /dev/tcp/$POSTGRES_IP/5432";
    do
        echo "Waiting for postgres container..."
        sleep 2
    done
    echo "Database is ready..."

    npm run db:sync:force && npm prune && npm install

    npm test
    testExitCode=$?

    # Tear down docker container
    docker stop postgres-slave
    docker rm postgres-slave

    # Exit with test exit code
    echo "Destroyed database"
    exit $testExitCode
fi

