#!/bin/sh

unit=canteen-mdb
for u in canteen-mdb canteen-topup; do
    if systemctl is-enabled --quiet "$u" 2>/dev/null; then
        unit=$u
        break
    fi
done

if [ "$(systemctl is-active "$unit")" = active ]; then
    state=0
else
    state=2
fi
restarts=$(systemctl show -p NRestarts --value "$unit")
echo "$state \"Canteen client\" restarts=${restarts:-0} $unit $(systemctl is-active "$unit"), $(dpkg-query -W -f='${Version}' nuxbe-canteen-client 2>/dev/null), restarts ${restarts:-0}"

# Only a Pi has a power line to report; on a Pi without vcgencmd it is UNKNOWN.
if grep -qa Raspberry /proc/device-tree/model 2>/dev/null; then
    throttled=$(vcgencmd get_throttled 2>/dev/null | cut -d= -f2)
    if [ -z "$throttled" ]; then
        echo "3 \"Canteen power\" - vcgencmd get_throttled failed"
    else
        t=$((throttled))
        state=0
        text=""
        [ $((t & 0x8)) -ne 0 ] && state=1 && text="$text, soft temperature limit now"
        [ $((t & 0x2)) -ne 0 ] && state=1 && text="$text, frequency capped now"
        [ $((t & 0x10000)) -ne 0 ] && state=1 && text="$text, under-voltage since boot"
        [ $((t & 0x1)) -ne 0 ] && state=2 && text="$text, UNDER-VOLTAGE NOW"
        [ $((t & 0x4)) -ne 0 ] && state=2 && text="$text, THROTTLED NOW"
        oc=$(journalctl -k --since -15min -o cat 2>/dev/null | grep -c -i "over-current")
        [ "$oc" -gt 0 ] && state=2 && text="$text, USB over-current $oc in 15 min"
        echo "$state \"Canteen power\" usb_overcurrent=$oc throttled $throttled$text"
    fi
fi

if lsusb -d 9ac4: >/dev/null 2>&1; then
    errors=$(journalctl -u "$unit" --since -15min -o cat 2>/dev/null | grep -c -E "pm3 (exited|timed out|hung)")
    echo "P \"Canteen reader\" reader_errors=$errors;3;30 Proxmark3 on USB, $errors reader errors in 15 min"
else
    echo "2 \"Canteen reader\" reader_errors=0 Proxmark3 not on USB"
fi
