#!/bin/sh

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

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

if lsusb -d 9ac4: >/dev/null 2>&1; then
    errors=$(journalctl -u canteen-mdb --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
