#!/bin/bash
set -e  # Exit on non-zero status
set -u  # Treat unset variables as an error

# First install docker-compose (right version of it)
if [ -x $(command -v docker-compose) ]
then
    echo "Overwriting existing docker-compose."
    docker-compose -v
else
    echo "Installing docker-compose ${DOCKER_COMPOSE_VERSION}."
fi
mkdir -p downloads
DOCKER_COMPOSE_FILE=downloads/docker-compose-${DOCKER_COMPOSE_VERSION}
if [ ! -f $DOCKER_COMPOSE_FILE ]
then
    wget -q --waitretry=1 --retry-connrefused -T 10 \
        -O downloads/docker-compose-${DOCKER_COMPOSE_VERSION} \
        https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m`
fi
chmod +x $DOCKER_COMPOSE_FILE
sudo cp $DOCKER_COMPOSE_FILE /usr/local/bin/docker-compose


# Now build the Docker container

VERSION=latest make build-base

# This "make build-kuma" step is done here only to test that the kuma docker
# image can be built without error, not because it's needed by docker-compose.
VERSION=latest make build-kuma

docker-compose --version
docker-compose up -d

# Hang tight until MySQL appears to be working
docker-compose exec -T web urlwait mysql://root:kuma@mysql:3306/developer_mozilla_org 30
# Hang tight until Elasticsearch appears to be working
docker-compose exec -T web urlwait http://elasticsearch:9200 30
docker-compose exec -T web make clean
# Needed for Django's check_for_language
docker-compose exec -T web make localecompile
docker-compose exec -T web make build-static
# Chicken-and-egg problem. The `docker-compose up` above won't be able to start
# the `ssr` service because `kuma/javascript/dist/ssr.js` does not exist *until*
# you run the `build-static` command which is part of the `web` service.
# So, now that that's been done, let's give the `ssr` service another chance.
docker-compose restart ssr

docker-compose exec -T web ./manage.py migrate
# This checks that running `./manage.py makemigrations` wasn't forgotten
docker-compose exec -T web ./manage.py makemigrations --check --dry-run


# The idea here is that coverage analysis on the pytest tests is
# pretty slow. Around 1 minute slower than without.
# So can it be skipped if there were no .py changes in the PR.
is_pullrequest_build() {
  [[ ${TRAVIS_PULL_REQUEST-default} != "false" ]]
}
has_python_changes() {
    git diff --name-only $TRAVIS_COMMIT_RANGE | grep '\.py'
}
if is_pullrequest_build && has_python_changes; then
    echo "IS PR and has Python changes!"
    docker-compose exec -T web make coveragetest
else
    echo "Regular build, no coverage needed"
    docker-compose exec -T web make test
fi
