#!/bin/bash

set -x
set -e

while getopts ":pdstyc" opt; do
  case $opt in
    p)
      # pep8 only
      PEP8=true
      ;;
    d)
      # lava_dispatcher only
      DISPATCH=true
      ;;
    s)
      # lava_server only
      SERVER=true
      ;;
    t)
      # template tests only
      TEMPLATE=true
      ;;
    y)
      # pytest-3 only
      PYTEST=true
      ;;
    c)
      # clean only
      CLEAN=true
      ;;
    ?)
      echo "Usage:"
      echo "-c - clean targets only"
      echo "-p - clean and pep8 only"
      echo "-d - clean, pep8 and dispatcher only"
      echo "-s - clean, pep8 and server only"
      echo "-t - clean, pep8 and templates only"
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

shift $((OPTIND -1))

if [ -n "${SUDO_USER}" ]; then
    echo "./ci-run should NOT be run using ``sudo``"
    # root is ok but only if root did the git clone
    exit 3
fi

echo "Removing old .pyc files and cache"
echo
find . -name '*.pyc' -delete
rm -rf ./.cache/
rm -rf ./__init__.py
rm -rf lava.egg-info/
rm -rf .pytest_cache/
find . -name __pycache__ -exec rmdir "{}" \; 2>/dev/null || true
find . -name precious -type d -exec rm -rf "{}" \; 2>/dev/null || true

if [ -n "${CLEAN}" ]
then
    exit 0
fi

pep8 --ignore E501,E203,W503,W504 --exclude migrations .

if [ -n "${PEP8}" ]
then
    exit 0
fi

echo "Starting unit tests"
echo
if [ -z "${DISPATCH}"  -a -z "${TEMPLATE}" -a -z "${PYTEST}" ]
then
    echo "If it exists, a broken test database will be deleted without prompting."
    # lava_rest_app is pytest only
    python3 ./lava_server/manage.py test --noinput -v 2 lava_scheduler_app linaro_django_xmlrpc.tests lava_results_app
    if [ -n "${SERVER}" ]
    then
        exit
    fi
    python3 -m unittest discover -v lava_dispatcher/tests
    exit
fi


if [ -n "${DISPATCH}" -a  -z "${TEMPLATE}" -a -z "${PYTEST}" ]
then
    python3 -m unittest discover -v lava_dispatcher/tests
fi

if [ -z "${DISPATCH}" -a  -n "${TEMPLATE}" -a -z "${PYTEST}" ]
then
    python3 -m unittest -vcf lava_scheduler_app.tests.test_base_templates
    python3 -m unittest -vcf lava_scheduler_app.tests.test_templates
    python3 -m unittest -vcf lava_scheduler_app.tests.test_uboot_templates
    python3 -m unittest -vcf lava_scheduler_app.tests.test_fastboot_templates
    python3 -m unittest -vcf lava_scheduler_app.tests.test_grub_templates
    python3 -m unittest -vcf lava_scheduler_app.tests.test_qemu_templates
fi


if [ -z "${DISPATCH}" -a -z "${TEMPLATE}" -a -n "${PYTEST}" ]
then
    PYTHONPATH=. pytest-3 --cache-clear --ds lava_server.settings.development -v \
        lava_scheduler_app/tests lava_results_app/tests linaro_django_xmlrpc/tests.py lava_rest_app/tests.py
    PYTHONPATH=. pytest-3 --cache-clear -v lava_dispatcher/tests
    PYTHONPATH=. pytest-3 --cache-clear -v lava_common/tests
fi
