#!/bin/sh
# Copy read-only provisioning, then write Telegram contact point with chatid
# as a quoted string. Grafana file $VAR expansion turns numeric chat IDs into
# JSON numbers and crash-loops the container (502 on /monitoring/).
set -e

SRC="${GRAFANA_PROVISIONING_SRC:-/provisioning-ro}"
DST="${GF_PATHS_PROVISIONING:-/etc/grafana/provisioning}"

mkdir -p "$DST"
# Refresh from image mount (datasources, dashboards, alert rules)
rm -rf "$DST/datasources" "$DST/dashboards" "$DST/alerting" "$DST/plugins" "$DST/notifiers" 2>/dev/null || true
cp -a "$SRC/." "$DST/"

ALERT_DIR="$DST/alerting"
mkdir -p "$ALERT_DIR"
# Do not use static contactpoints from the image mount (if any)
rm -f "$ALERT_DIR/contactpoints.yml" "$ALERT_DIR/policies.yml"

TOKEN="${TELEGRAM_BOT_TOKEN:-}"
CHAT="${TELEGRAM_CHAT_ID:-}"

if [ -n "$TOKEN" ] && [ -n "$CHAT" ]; then
  # Force YAML strings via double quotes (handles negative group chat ids)
  cat > "$ALERT_DIR/contactpoints.yml" <<EOF
apiVersion: 1

contactPoints:
  - orgId: 1
    name: telegram
    receivers:
      - uid: kedebah_telegram
        type: telegram
        settings:
          bottoken: "${TOKEN}"
          chatid: "${CHAT}"
          disable_notification: false
          protect_content: false
        disableResolveMessage: false
EOF

  cat > "$ALERT_DIR/policies.yml" <<EOF
apiVersion: 1

policies:
  - orgId: 1
    receiver: telegram
    group_by:
      - grafana_folder
      - alertname
    group_wait: 30s
    group_interval: 5m
    repeat_interval: 4h
EOF
  echo "[grafana-entrypoint] Telegram contact point provisioned."
else
  cat > "$ALERT_DIR/contactpoints.yml" <<EOF
apiVersion: 1
contactPoints: []
EOF
  cat > "$ALERT_DIR/policies.yml" <<EOF
apiVersion: 1
policies: []
EOF
  echo "[grafana-entrypoint] TELEGRAM_* unset — Grafana starts without Telegram."
fi

exec /run.sh
