#!/bin/bash
# GK-APP-HEALTH-WAECHTER (cron */10): haelt /opt/galaktikus-ai dauerhaft stabil
# (Patron-Gesetz 22.11.: "nicht jeden Tag abstuerzen, nicht alle 3h aendern").
# - service tot -> restart
# - healthz keine 200 -> restart; immer noch schlecht -> GOLDEN-Restore + restart
# - md5(live) != md5(golden) -> Golden wiederherstellen (Deploy nur via gk_deploy.sh!)
# Stillschweigend (L9): Exit 0 ohne Output, NUR bei Ereignis gibt es eine Zeile.
set -u
LOG=~/.hermes/profiles/galaktikus/logs/gk_app_health.log
GOLD=~/.gk_golden
BASE=/opt/galaktikus-ai
mkdir -p ~/.hermes/profiles/galaktikus/logs
exec 9>/tmp/gk_app_health.lock || exit 0
flock -n 9 || exit 0

log(){ echo "$(date -u +%FT%TZ) $1" >> "$LOG"; }

EVENT=0
for i in 1 2 3; do
  code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 8 https://galaktikus.org/healthz || echo 000)
  [ "$code" = "200" ] && break
  sleep 3
done
if [ "$code" != "200" ]; then
  log "EVENT healthz=$code -> restart galaktikus-ai"
  sudo -n systemctl restart galaktikus-ai
  sleep 6
  code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 8 https://galaktikus.org/healthz || echo 000)
  if [ "$code" != "200" ]; then
    log "NOCH KRANK nach restart -> GOLDEN-Restore + restart"
    [ -f "$GOLD/app.py" ] && { sudo -n cp -p "$GOLD/app.py" "$BASE/app.py"; }
    [ -f "$GOLD/mini_app.html" ] && { sudo -n cp -p "$GOLD/mini_app.html" "$BASE/mini_app.html"; }
    sudo -n systemctl restart galaktikus-ai
    sleep 6
    code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 8 https://galaktikus.org/healthz || echo 000)
    log "nach Restore healthz=$code"
  fi
  EVENT=1
fi

if [ -d "$GOLD" ]; then
  for pair in "mini_app.html" "app.py"; do
    if [ -f "$GOLD/$pair" ] && ! cmp -s "$GOLD/$pair" "$BASE/$pair" 2>/dev/null; then
      log "EVENT drift: $pair weicht von golden ab -> Restore"
      sudo -n cp -p "$GOLD/$pair" "$BASE/$pair"
      case "$pair" in app.py) sudo -n systemctl restart galaktikus-ai;; esac
      sleep 4
      h=$(curl -s -o /dev/null -w '%{http_code}' --max-time 8 https://galaktikus.org/healthz || echo 000)
      log "nach drift-Restore ($pair) healthz=$h"
      EVENT=1
    fi
  done
fi

[ "$EVENT" = "0" ] && exit 0
echo "GK-APP-HEALTH: siehe Log $LOG (tail unten)"
tail -6 "$LOG"