#!/bin/bash

trap 'p=$(jobs -p); if [ "$p" != "" ]; then kill -s 9 $p; fi; rm_fd' EXIT

set -x

log_file_path="amc_integ_tests.log"

exec 3> >(tee -a $log_file_path)
exec 1>&3
exec 2>&3


rm_fd() {
  exec 1>&-
  exec 2>&-
  exec 3>&-
  wait
}

CUR_FILE_PATH=$(dirname "$0")
CUR_FILE_PATH=$(cd "$CUR_FILE_PATH" && pwd)
PRJ_ROOT_PATH=$(dirname "$CUR_FILE_PATH")

timeout=10


function check { 
    if [ "$1" == "$timeout" ]; then
        echo "timeout. connection to $2 failed"
        exit 1
    else 
        echo "connection to $2 established"
    fi
}

. $CUR_FILE_PATH/up_license_client.sh

check $client_counter "license_client"

response=0
counter=0

while [ "$response" != 200 ] && [ "$counter" != "$timeout" ]; do
    response=$(curl -s -o /dev/null -w "%{http_code}" -u elastic:changeme -X GET http://elasticsearch:9200/)
    sleep 5s
    counter=$(( $counter + 1 ))
done

check $counter "elasticsearch"


response=0
counter=0
re=^.*PONG.*$

while ! [[ $response =~ ${re} ]] && [ "$counter" != "$timeout" ]; do
    response=$(echo "PING" | nc -w 2 redis 6379)
    sleep 5s
    counter=$(( $counter + 1 ))
done

check $counter "redis"


set -ex

# if [ -d test_env ]; then
#     rm -rf test_env
#     echo "old env was removed"
# fi

#python3 -m virtualenv test_env 

#source test_env/bin/activate 

pip install --upgrade pip 

pip install -r requirements_test.txt 

DJANGO_SETTINGS_MODULE=console.settings.test python manage.py makemigrations 

DJANGO_SETTINGS_MODULE=console.settings.test python manage.py migrate 

DJANGO_SETTINGS_MODULE=console.settings.test coverage run -m pytest --disable-warnings -m integration 

coverage html -d public/test_coverage/ 
