#!/usr/bin/env bash
set -euo pipefail

export "SONAR_TOKEN"="sqa_a38081f27f9e32376feed2e653b48ed5a0723565"

if [[ -z "${SONAR_HOST_URL:-}" ]]; then
  echo "SONAR_HOST_URL environment variable is required" >&2
  exit 1
fi

if [[ -z "${SONAR_TOKEN:-}" ]]; then
  echo "SONAR_TOKEN environment variable is required" >&2
  exit 1
fi

SONAR_PROJECT_KEY=${SONAR_PROJECT_KEY:-as400api}
SONAR_PROJECT_NAME=${SONAR_PROJECT_NAME:-AS400API}
BUILD_CONFIGURATION=${BUILD_CONFIGURATION:-Debug}
SOLUTION_FILE=${SOLUTION_FILE:-AS400API.sln}

FIND_TEST_PROJECT=$(find . -name '*Tests.csproj' -print -quit)

SONAR_BEGIN_ARGS=(
  "/k:${SONAR_PROJECT_KEY}"
  "/n:${SONAR_PROJECT_NAME}"
  "/d:sonar.host.url=${SONAR_HOST_URL}"
  "/d:sonar.login=${SONAR_TOKEN}"
  "/d:sonar.cs.opencover.reportsPaths=**/coverage.opencover.xml"
  "/d:sonar.exclusions=**/bin/**,**/obj/**"
)

if [[ -n "${SONAR_BRANCH_NAME:-}" ]]; then
  SONAR_BEGIN_ARGS+=("/d:sonar.branch.name=${SONAR_BRANCH_NAME}")
fi

if [[ -n "${SONAR_ORGANIZATION:-}" ]]; then
  SONAR_BEGIN_ARGS+=("/d:sonar.organization=${SONAR_ORGANIZATION}")
fi

if [[ -n "${SONAR_PULL_REQUEST_KEY:-}" && -n "${SONAR_PULL_REQUEST_BRANCH:-}" && -n "${SONAR_PULL_REQUEST_BASE:-}" ]]; then
  SONAR_BEGIN_ARGS+=(
    "/d:sonar.pullrequest.key=${SONAR_PULL_REQUEST_KEY}"
    "/d:sonar.pullrequest.branch=${SONAR_PULL_REQUEST_BRANCH}"
    "/d:sonar.pullrequest.base=${SONAR_PULL_REQUEST_BASE}"
  )
fi

begin_succeeded=0
cleanup() {
  local status=$?
  if [[ ${begin_succeeded} -eq 1 ]]; then
    if ! dotnet sonarscanner end "/d:sonar.login=${SONAR_TOKEN}"; then
      status=$?
    fi
  fi
  exit "${status}"
}
trap cleanup EXIT

dotnet sonarscanner begin "${SONAR_BEGIN_ARGS[@]}"
begin_succeeded=1

dotnet build "${SOLUTION_FILE}" -c "${BUILD_CONFIGURATION}"

if [[ -n "${FIND_TEST_PROJECT}" ]]; then
  dotnet test "${SOLUTION_FILE}" -c "${BUILD_CONFIGURATION}" --no-build \
    /p:CollectCoverage=true \
    /p:CoverletOutputFormat=opencover \
    /p:CoverletOutput=TestResults/
else
  echo "No *Tests.csproj projects found; skipping dotnet test." >&2
fi
