#!/bin/sh
# Restarts the Jaw node if it stops answering (3 failed checks in a row, one check every 30 s).
# Skips the first 60 s after a (re)start so a slow start isn't mistaken for a hang.
state=/run/jaw-healthcheck.failures
systemctl is-active --quiet jaw || exit 0

# Seconds since the service became active (whole seconds; shell arithmetic, no awk).
since_us=$(systemctl show jaw -p ActiveEnterTimestampMonotonic --value)
now_s=$(cut -d. -f1 /proc/uptime)
if [ -n "$since_us" ] && [ "$since_us" -gt 0 ] && [ $((now_s - since_us / 1000000)) -lt 60 ]; then
    exit 0
fi

# The port the node listens on (jaw-setup can change it, #171).
port=$(sed -n 's/^ASPNETCORE_URLS=.*:\([0-9]*\).*/\1/p' /etc/jaw/jaw.env 2>/dev/null | tail -n 1)
if curl -sf --max-time 10 -o /dev/null "http://127.0.0.1:${port:-5070}/api/node"; then
    rm -f "$state"
    # A new version on trial (jaw-run, #61) that answers after its first minute is confirmed: no rollback from now on.
    if [ -f /var/lib/jaw/app/trial ]; then
        rm -f /var/lib/jaw/app/trial
        echo "Confirmed the new Jaw node version"
    fi
    exit 0
fi

n=$(( $(cat "$state" 2>/dev/null || echo 0) + 1 ))
echo "$n" > "$state"
echo "Jaw node didn't answer the health check ($n in a row)"
if [ "$n" -ge 3 ]; then
    echo "Restarting the Jaw node (not responding)"
    rm -f "$state"
    systemctl kill -s KILL jaw   # a hung process may ignore a polite stop
    systemctl restart jaw
fi
