#!/bin/bash
set -e

export JAVA_HOME=/usr/bin/sonar-scanner/jre

python3 -m venv build_venv
source build_venv/bin/activate
python3 -m pip install --upgrade pip

echo "dev setup for unit test and coverage"

pip install -e incl/pyinfra
pip install -r incl/pyinfra/requirements.txt

pip install -e incl/pdf2image
pip install -r incl/pdf2image/requirements.txt

pip install -e .
pip install -r requirements.txt


echo "DVC pull step"
dvc pull

echo "coverage calculation"
coverage run -m pytest
echo "coverage report generation"
coverage report -m
coverage xml

SERVICE_NAME=$1

echo "dependency-check:aggregate"
mkdir -p reports
dependency-check --enableExperimental -f JSON -f HTML -f XML \
  --disableAssembly -s . -o reports --project $SERVICE_NAME --exclude ".git/**" --exclude "venv/**" \
  --exclude "build_venv/**" --exclude "**/__pycache__/**"

if [[ -z "${bamboo_repository_pr_key}" ]]
then
    echo "Sonar Scan for branch: ${bamboo_planRepository_1_branch}"
    /usr/bin/sonar-scanner/bin/sonar-scanner -X\
      -Dsonar.projectKey=RED_$SERVICE_NAME \
      -Dsonar.sources=src,cv_analysis \
      -Dsonar.host.url=https://sonarqube.iqser.com \
      -Dsonar.login=${bamboo_sonarqube_api_token_secret} \
      -Dsonar.branch.name=${bamboo_planRepository_1_branch} \
      -Dsonar.dependencyCheck.jsonReportPath=reports/dependency-check-report.json \
      -Dsonar.dependencyCheck.xmlReportPath=reports/dependency-check-report.xml \
      -Dsonar.dependencyCheck.htmlReportPath=reports/dependency-check-report.html \
      -Dsonar.python.coverage.reportPaths=reports/coverage.xml

else
    echo "Sonar Scan for PR with key1: ${bamboo_repository_pr_key}"
    /usr/bin/sonar-scanner/bin/sonar-scanner \
      -Dsonar.projectKey=RED_$SERVICE_NAME \
      -Dsonar.sources=src,cv_analysis \
      -Dsonar.host.url=https://sonarqube.iqser.com \
      -Dsonar.login=${bamboo_sonarqube_api_token_secret} \
      -Dsonar.pullrequest.key=${bamboo_repository_pr_key} \
      -Dsonar.pullrequest.branch=${bamboo_repository_pr_sourceBranch} \
      -Dsonar.pullrequest.base=${bamboo_repository_pr_targetBranch} \
      -Dsonar.dependencyCheck.jsonReportPath=reports/dependency-check-report.json \
      -Dsonar.dependencyCheck.xmlReportPath=reports/dependency-check-report.xml \
      -Dsonar.dependencyCheck.htmlReportPath=reports/dependency-check-report.html \
      -Dsonar.python.coverage.reportPaths=reports/coverage.xml
fi
