#!/bin/bash

clean_containers()
{
  echo "\033[0;32m CLEANING ALL CONTAINERS\033[0;32m \033[0m"
  containers=$(docker ps -aq | xargs)
  [[ -n $containers ]] && docker stop $containers && docker rm $containers
  echo "\033[0;32m CLEANING ALL CONTAINERS COMPLETE\033[0;32m \033[0m"
}

COMPOSE_CMD='docker-compose -f docker-compose.tests.yaml'

clean_containers
export COMPOSE_INTERACTIVE_NO_CLI=1
export REVISION=$(git rev-parse --short=8 HEAD)
export BUILDTIME=$(date -u +"%Y%m%d%H%M%S")
export VERSION="build-${BUILDTIME}.${REVISION}"
${COMPOSE_CMD[@]} up -d postgres redis elasticsearch
${COMPOSE_CMD[@]} ps


# waiting for database container to up, before restoring and making migrations
NEXT_WAIT_TIME=0
until [ "`docker inspect -f {{.State.Health.Status}} db_test`" == "healthy" ] || [ $NEXT_WAIT_TIME -eq 4 ]; do
    sleep $(( NEXT_WAIT_TIME++ ))
done;

echo "\033[0;32m RESTORING DATABASE\033[0;32m \033[0m"

${COMPOSE_CMD[@]} exec -T postgres psql -U postgres -c "DROP DATABASE IF EXISTS postgres_test;"
${COMPOSE_CMD[@]} exec -T postgres psql -U postgres -c "CREATE DATABASE postgres_test;"
docker exec -i $(docker-compose ps -q postgres) psql -U postgres postgres_test < ./app/migrations/structure.sql

${COMPOSE_CMD[@]} build api

${COMPOSE_CMD[@]} run --workdir /app/app api /bin/sh -c "/venv/bin/python manage.py db upgrade"

echo "\033[0;32m RESTORING DATABASE COMPLETE \033[0m"

if [ $# -eq 0 ]
  then
    # If no argument was provided, set a default tests path
    tests_path=""
else
  # If an argument was provided, use it as the tests path
  tests_path="$1"
fi

${COMPOSE_CMD[@]} run api /bin/sh -c "echo -e '\e[31m[pytest] Report:\e[0m' && /venv/bin/pytest $tests_path --cov=app --cov-config=.coveragerc --disable-pytest-warnings --junitxml=test-reports/pytest-report.xml"
