#!/bin/bash
# Every minute (mirrordash-app-watch.timer). The app: four failed rounds in a row, so an app restarting for
# an update (minutes on a Pi 3) isn't taken for a hung one. The screen: two rounds of a page silent for over
# 150 s (it says "alive" every minute), about 3 minutes; a crashed renderer doesn't wait for this, the screen exits
# at once (mirrordash-screen, screen-kiosk.service). The counts live in /run (RAM), like the Wi-Fi watch's.
set -u
STATE=${MIRRORDASH_WATCH_STATE:-/run/mirrordash-app-watch}  # overridable for tests/test_configure_image.py
mkdir -p "$STATE"

# Counts up the failure $1 and says yes on every $2-th round in a row. The log ($4) is saved the first
# time only, so a fault that stays doesn't push the other saved logs out (save-log keeps 5).
act() {
    local failed_rounds=$(( $(cat "$STATE/$1" 2>/dev/null || echo 0) + 1 ))
    echo "$failed_rounds" > "$STATE/$1"
    [ $(( failed_rounds % $2 )) -eq 0 ] || return 1
    logger -t mirrordash-app-watch "$3"
    if [ "$failed_rounds" -eq "$2" ]; then /usr/local/lib/mirrordash/save-log "$4" -b -n 2000 >/dev/null || true; fi
}

if ! health=$(curl -fsS -m 10 http://127.0.0.1:8000/health); then
    act app 4 "The app hasn't answered for four rounds; restarting it" app-hung && systemctl restart mirrordash.service
    exit 0
fi
rm -f "$STATE/app"

# Seconds since the mirror's own screen showed it's alive; null while the screen is off
seen=$(sed -n 's/.*"screen_seen_seconds_ago":\([0-9]*\).*/\1/p' <<< "$health")
if [ -n "$seen" ] && [ "$seen" -gt 150 ]; then
    act screen 2 "The screen's page has been silent for ${seen}s; restarting the kiosk" screen-lost && systemctl restart screen-kiosk.service
else
    rm -f "$STATE/screen"
fi
exit 0
