#!/bin/bash
# Every 3 minutes (mirrordash-app-watch.timer). Two failed rounds in a row, so an app restarting for an
# update isn't taken for a hung one. 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 second round in a row. The log ($3) 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 n=$(( $(cat "$STATE/$1" 2>/dev/null || echo 0) + 1 ))
    echo "$n" > "$STATE/$1"
    [ $(( n % 2 )) -eq 0 ] || return 1
    logger -t mirrordash-app-watch "$2"
    if [ "$n" -eq 2 ]; then /usr/local/lib/mirrordash/save-log "$3" -b -n 2000 >/dev/null || true; fi
}

if ! health=$(curl -fsS -m 10 http://127.0.0.1:8000/health); then
    act app "The app hasn't answered for two 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 300 ]; then
    act screen "The screen's page has been silent for ${seen}s; restarting the kiosk" screen-lost && systemctl restart cog-kiosk.service
else
    rm -f "$STATE/screen"
fi
exit 0
