#!/bin/sh

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

set -ex

log_file_path="amc_unit_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")


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"

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

if [ -f db.sqlite3 ]; then
    rm -f db.sqlite3
    echo "old db.sqlite3 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 unit

coverage html -d public/test_coverage/ 