#!/bin/sh

set -eu

errexit() {
  echo "$@" >&2
  exit "${2:-1}"
}

command -v curl >/dev/null || errexit "curl nicht installiert"
command -v jq >/dev/null || errexit "jq nicht installiert"

SONAR_CONFIGURATION_FILE="/opt/homebrew/etc/sonar-scanner.properties"
[ -f "$SONAR_CONFIGURATION_FILE" ] || errexit "Keine globale sonarcube Konfiguration gefunden!"

PROJECT_FILE=$(find . -maxdepth 1 -name "sonar-project*.properties" -print -quit)
[ -n "$PROJECT_FILE" ] || errexit "Keine sonar-project*.properties Datei gefunden!"

SONAR_TOKEN=$(awk -F= '/^sonar.token=/ {gsub(/^[ \t]+|[ \t]+$/,"",$2); print $2}' "$SONAR_CONFIGURATION_FILE")
[ -n "$SONAR_TOKEN" ] || errexit "Kein 'sonar.token' in $SONAR_CONFIGURATION_FILE vorhanden"

SONAR_HOST_URL=$(awk -F= '/^sonar.host.url=/ {gsub(/^[ \t]+|[ \t]+$/,"",$2); print $2}' "$SONAR_CONFIGURATION_FILE")
[ -n "$SONAR_HOST_URL" ] || errexit "Kein 'sonar.host.url' in $SONAR_CONFIGURATION_FILE vorhanden"

PROJECT_KEY=$(awk -F= '/^sonar.projectKey=/ {gsub(/^[ \t]+|[ \t]+$/,"",$2); print $2}' "$PROJECT_FILE")
[ -n "$PROJECT_KEY" ] || errexit "Kein 'sonar.projectKey' in $PROJECT_FILE vorhanden"

curl -s \
  -u "$SONAR_TOKEN:" \
  "$SONAR_HOST_URL/api/issues/search?componentKeys=$PROJECT_KEY&statuses=OPEN&ps=500" |
  jq -r '.issues[] | "\(.component | sub("^[^:]+:"; "")):\(.line // 1): [\(.severity)] \(.message | gsub("\n"; " ")) (\(.author))"'

