#!/bin/bash

set -e

# defaults if not set
: "${SKIP_LINT:=0}"
: "${COV_REPORT:=term}"
: "${COV_PORT:=8000}"

# convert to all lowercase
COV_REPORT=$(echo $COV_REPORT | tr '[:upper:]' '[:lower:]')

# run linting of python and yaml files
if [ "$SKIP_LINT" -ne 1 ]; then
    echo 'Running linting...'
    yamllint -s -d "{extends: relaxed, rules: {line-length: {max: 100}}}"  docker-compose.yaml
    flake8 payments_generate/ tests/
else
    echo 'Skipping linting...'
fi

# set flags for pytest-cov
COVERAGE_ARGS=""
if [ "$COV_REPORT" != "off" ]; then
    COVERAGE_ARGS="--cov-report $COV_REPORT --cov=payments_generate"
fi


if [ "$RUN_INTEGRATION" -ne 1 ]; then
    # run pytest with args set
    echo 'Running tests...'
    python -m pytest $TEST_ARGS --ignore=tests/integration/ tests/ $COVERAGE_ARGS
else
    echo 'Running delete_payment_group_payment_foreign_keys.py...'
 	python tests/integration/utils/delete_payment_group_payment_foreign_keys.py

    echo 'Running create_fixutre_entries.py...'
    python tests/integration/utils/create_fixture_entries.py

    echo 'Running integration tests...'
    python -m pytest tests/integration -s \
        --html=report.html \
        --self-contained-html \
        --cov-report xml \
        --junitxml=pyunit.xml \
        --jira
fi

# serve out html coverage report
if [ "$COV_REPORT" = "html" ]; then
    echo "Serving out coverage report on port $COV_PORT..."
    python -m http.server --directory htmlcov $COV_PORT
fi

echo 'Done!'
