#!/usr/bin/env bash

set -e

# not all platforms support readlink -f
# SOURCE_PATH must be set, and treat it as absolute path
rlink=""
set +e
readlink -f /tmp >/dev/null 2>&1
if [ $? -eq 0 ]; then
  # do not support readlink -f, so need alternative
  rlink="readlink -f"
fi
set -e

if [[ -z "${SOURCE_PATH}" ]]; then
  if [ -z "$rlink" ]; then
    echo "ERROR: system does not support 'readlink -f' and SOURCE_PATH not set, exiting." >&2
    exit 1
  fi
  export SOURCE_PATH="$($rlink "$(dirname ${0})/..")"
else
  if [ -z "$rlink" ]; then
    echo "warning: system does not support 'readlink -f', treating SOURCE_PATH as absolute path with symlinks resolved." >&2
  else
    export SOURCE_PATH="$($rlink ${SOURCE_PATH})"
  fi
fi

cd "${SOURCE_PATH}"

tools="git yaml2json jq"
for t in $tools; do
  if ! which $t &>/dev/null; then
    echo "Tool $t not found in PATH"
    exit 1
  fi
done

pushd $SOURCE_PATH/charts/seed-monitoring/charts/core/charts/prometheus > /dev/null
cat <<EOF > $SOURCE_PATH/docs/monitoring/user_alerts.md
# User Alerts
|Alertname|Severity|Type|Description|
|---|---|---|---|
EOF
cat <<EOF > $SOURCE_PATH/docs/monitoring/operator_alerts.md
# Operator Alerts
|Alertname|Severity|Type|Description|
|---|---|---|---|
EOF
for file in rules/*.yaml; do
  cat $file | yaml2json | jq -r '.groups | .[].rules | map(select(.labels.visibility == "owner" or .labels.visibility == "all")) | map(select(has("alert"))) | .[] | "|" + .alert + "|" + .labels.severity + "|" + .labels.type + "|" + "`" + .annotations.description + "`" + "|"' >> $SOURCE_PATH/docs/monitoring/user_alerts.md
  cat $file | yaml2json | jq -r '.groups | .[].rules | map(select(.labels.visibility == "operator" or .labels.visibility == "all")) | map(select(has("alert"))) | .[] | "|" + .alert + "|" + .labels.severity + "|" + .labels.type + "|" + "`" + .annotations.description + "`" + "|"' >> $SOURCE_PATH/docs/monitoring/operator_alerts.md
done
popd > /dev/null

if [ -n "$(git status --porcelain)" ]; then
  git add $SOURCE_PATH/docs/monitoring/user_alerts.md
  git add $SOURCE_PATH/docs/monitoring/operator_alerts.md
  git commit -m "Update alert documentation"
else
  echo "no changes";
fi
