#!/bin/sh
# POSIX shell only - NINA Warnmeldungen fuer eine Stadt pruefen
# Stadt wird per IP ermittelt oder per -c uebergeben.

API="https://warnung.bund.de/api31"
RS_URL="https://www.xrepository.de/api/xrepository/urn:de:bund:destatis:bevoelkerungsstatistik:schluessel:rs_2021-07-31/download/Regionalschl_ssel_2021-07-31.json"

echo_err() { echo "$@" >&2; }

usage() {
    echo_err "usage: $0 [-c CITY] [-t curl|wget]"
    exit 1
}

# HTTP-Abruf, Werkzeug per -t oder HTTP_TOOL umschaltbar
TOOL="${HTTP_TOOL:-}"
if [ -z "$TOOL" ]; then
    if command -v curl >/dev/null 2>&1; then TOOL=curl; else TOOL=wget; fi
fi
case "$TOOL" in
    curl|wget) ;;
    *) echo_err "error: unbekanntes HTTP-Tool '$TOOL' (erwartet: curl|wget)"; exit 1 ;;
esac
command -v "$TOOL" >/dev/null 2>&1 || { echo_err "error: '$TOOL' ist nicht installiert"; exit 1; }

fetch() {
    case "$TOOL" in
        wget) wget -qO- "$1" ;;
        *)    curl -sS "$1" ;;
    esac
}

download() {
    case "$TOOL" in
        wget) wget -qO "$2" "$1" ;;
        *)    curl -sS "$1" -o "$2" ;;
    esac
}

# erster String-Wert eines JSON-Schluessels (POSIX awk)
json_value() {
    awk -v k="\"$1\":\"" 'match($0, k "[^\"]*") {print substr($0, RSTART + length(k), RLENGTH - length(k)); exit}'
}

CITY=""
while getopts "c:t:h" opt; do
    case "$opt" in
        c) CITY="$OPTARG" ;;
        t) TOOL="$OPTARG" ;;
        *) usage ;;
    esac
done
shift $((OPTIND - 1))

case "$TOOL" in
    curl|wget) ;;
    *) echo_err "error: unbekanntes HTTP-Tool '$TOOL' (erwartet: curl|wget)"; exit 1 ;;
esac
command -v "$TOOL" >/dev/null 2>&1 || { echo_err "error: '$TOOL' ist nicht installiert"; exit 1; }

# ---- Stadt aus IP ermitteln, falls nicht angegeben -----------------------
if [ -z "$CITY" ]; then
    GEO=$(fetch "http://ip-api.com/json/?lang=de") || {
        echo_err "error: Geolokalisierung fehlgeschlagen"
        exit 1
    }
    [ -z "$GEO" ] && { echo_err "error: Geolokalisierung fehlgeschlagen"; exit 1; }
    STATUS=$(printf '%s' "$GEO" | sed -n 's/.*"status":"\([^"]*\)".*/\1/p')
    COUNTRY=$(printf '%s' "$GEO" | sed -n 's/.*"countryCode":"\([^"]*\)".*/\1/p')
    CITY=$(printf '%s' "$GEO" | sed -n 's/.*"city":"\([^"]*\)".*/\1/p')
    if [ "$STATUS" != "success" ] || [ "$COUNTRY" != "DE" ] || [ -z "$CITY" ]; then
        echo_err "error: Standort konnte nicht nach Deutschland aufgeloest werden. Bitte -c CITY angeben."
        exit 1
    fi
    echo "Standort per IP ermittelt: $CITY"
fi

# ---- ARS fuer die Stadt ermitteln ----------------------------------------
RS_FILE="${TMPDIR:-/tmp}/opencode-regionalschluessel.json"
if [ ! -s "$RS_FILE" ]; then
    download "$RS_URL" "$RS_FILE" || { echo_err "error: Regionalschluessel-Download fehlgeschlagen"; exit 1; }
fi

# Datei ist einzeilig; Zeilen der Form ["ARS","Name",...] via RS trennen
ROW=$(awk -v city="$CITY" 'BEGIN{RS="],\\["} tolower($0) ~ tolower(city) {print; exit}' "$RS_FILE")
if [ -z "$ROW" ]; then
    echo_err "error: Stadt '$CITY' nicht im Regionalschluessel-Verzeichnis gefunden"
    exit 1
fi

ARS=$(printf '%s' "$ROW" | sed -n 's/^"\([0-9]*\)","\([^"]*\)".*/\1/p')
NAME=$(printf '%s' "$ROW" | sed -n 's/^"\([0-9]*\)","\([^"]*\)".*/\2/p')
DISTRICT=$(printf '%s' "$ARS" | cut -c1-5)0000000

echo ""
echo "Stadt : $NAME ($ARS)"
echo "Kreis : $DISTRICT"
echo ""

# ---- 1) Dashboard (aktuelle Warnungen fuer den Kreis) ---------------------
echo "=== Dashboard Kreis ($DISTRICT) ==="
DASH=$(fetch "$API/dashboard/$DISTRICT.json")
DASH_N=$(printf '%s' "$DASH" | awk 'BEGIN{RS="\"payload\""} {n++} END{print n-1}')
if [ "$DASH_N" -eq 0 ]; then
    echo "  keine aktuellen Meldungen"
else
    printf '%s' "$DASH" | awk 'BEGIN{RS="},{"} {print}' | while IFS= read -r entry; do
        id=$(printf '%s' "$entry" | sed -n 's/.*"id":"\([^"]*\)".*/\1/p')
        [ -z "$id" ] && continue
        title=$(printf '%s' "$entry" | sed -n 's/.*"de":"\([^"]*\)".*/\1/p')
        sent=$(printf '%s' "$entry" | sed -n 's/.*"sent":"\([^"]*\)".*/\1/p')
        echo "  $id  |  $title  |  sent: $sent"
    done
fi

# ---- 2) RSS-Feed (MoWaS) --------------------------------------------------
echo ""
echo "=== RSS-Feed ($DISTRICT.rss) ==="
RSS=$(fetch "$API/mowas/rss/$DISTRICT.rss")
RSS_N=$(printf '%s' "$RSS" | awk 'BEGIN{RS="<item>"} {n++} END{print n-1}')
if [ "$RSS_N" -eq 0 ]; then
    echo "  keine aktuellen Meldungen"
else
    printf '%s' "$RSS" | awk 'BEGIN{RS="</item>"} /<item>/{t=$0; sub(/^.*<title>/,"",t); sub(/<\/title>.*/,"",t); d=$0; sub(/^.*<pubDate>/,"",d); sub(/<\/pubDate>.*/,"",d); print "  " t "  |  " d}'
fi

# ---- 3) Alle Warnquellen nach Stadtname filtern ----------------------------
echo ""
echo "=== Alle Warnquellen (mowas/katwarn/biwapp/dwd/lhp/police) ==="
FOUND=0
for s in mowas katwarn biwapp dwd lhp police; do
    LIST=$(fetch "$API/$s/mapData.json")
    [ -z "$LIST" ] && continue
    IDS=$(printf '%s' "$LIST" | awk 'BEGIN{RS="\"id\":\""} NR>1{split($0,a,"\""); print a[1]}')
    for id in $IDS; do
        WARN=$(fetch "$API/warnings/$id.json")
        printf '%s' "$WARN" | grep -qi "$CITY" || continue
        FOUND=$((FOUND + 1))
        echo ""
        echo "  [$s] $id"
        echo "  Headline : $(printf '%s' "$WARN" | json_value headline)"
        echo "  Event    : $(printf '%s' "$WARN" | json_value event)"
        echo "  Severity : $(printf '%s' "$WARN" | json_value severity)"
        echo "  Sender   : $(printf '%s' "$WARN" | awk 'match($0, /"valueName":"sender_langname","value":"[^"]*"/) {s=substr($0, RSTART, RLENGTH); sub(/.*"value":"/,"",s); sub(/"$/,"",s); print s; exit}')"
        echo "  Sent     : $(printf '%s' "$WARN" | json_value sent)"
    done
done

echo ""
echo "=== Ergebnis ==="
TOTAL=$((FOUND + DASH_N))
if [ "$TOTAL" -eq 0 ]; then
    echo "  Keine aktuellen Warnmeldungen fuer '$CITY' gefunden."
else
    echo "  $TOTAL Warnmeldung(en) fuer '$CITY' gefunden."
fi
