#!/bin/bash

# WARNING: Please, DO NOT edit this file! It is maintained in the Repository Template (https://github.com/nhs-england-tools/repository-template). Raise a PR instead.

set -euo pipefail

# Script to perform static analysis of the repository content and upload the
# report to SonarCloud.
#
# Usage:
#   $ [options] ./perform-static-analysis.sh
#
# Expects:
#   BRANCH_NAME=branch-name         # Branch to report on
#   SONAR_ORGANISATION_KEY=org-key  # SonarCloud organisation key
#   SONAR_PROJECT_KEY=project-key   # SonarCloud project key
#   SONAR_TOKEN=token               # SonarCloud token
#
# Options:
#   FORCE_USE_DOCKER=true # If set to true the command is run in a Docker container, default is 'false'
#   VERBOSE=true          # Show all the executed commands, default is 'false'

# ==============================================================================

function main() {

  cd "$(git rev-parse --show-toplevel)"

  if command -v sonar-scanner > /dev/null 2>&1 && ! is-arg-true "${FORCE_USE_DOCKER:-false}"; then
    run-sonar-scanner-natively
  else
    run-sonar-scanner-in-docker
  fi
}

function run-sonar-scanner-natively() {

  sonar-scanner \
    -Dproject.settings="$PWD/scripts/config/sonar-scanner.properties" \
    -Dsonar.branch.name="${BRANCH_NAME:-$(git rev-parse --abbrev-ref HEAD)}" \
    -Dsonar.organization="$SONAR_ORGANISATION_KEY" \
    -Dsonar.projectKey="$SONAR_PROJECT_KEY" \
    -Dsonar.token="$SONAR_TOKEN"
}

function run-sonar-scanner-in-docker() {

  # shellcheck disable=SC1091
  source ./scripts/docker/docker.lib.sh

  # shellcheck disable=SC2155
  local image=$(name=sonarsource/sonar-scanner-cli docker-get-image-version-and-pull)
  docker run --rm --platform linux/amd64 \
    --volume "$PWD":/usr/src \
    "$image" \
      -Dproject.settings=/usr/src/scripts/config/sonar-scanner.properties \
      -Dsonar.branch.name="${BRANCH_NAME:-$(git rev-parse --abbrev-ref HEAD)}" \
      -Dsonar.organization="$SONAR_ORGANISATION_KEY" \
      -Dsonar.projectKey="$SONAR_PROJECT_KEY" \
      -Dsonar.token="$SONAR_TOKEN"
}

# ==============================================================================

function is-arg-true() {

  if [[ "$1" =~ ^(true|yes|y|on|1|TRUE|YES|Y|ON)$ ]]; then
    return 0
  else
    return 1
  fi
}

# ==============================================================================

is-arg-true "${VERBOSE:-false}" && set -x

main "$@"

exit 0
