#!/bin/python3
#
import argparse
import nagios
import subprocess

"""
Bit	Hex     Value Meaning
0	1	    Under-voltage detected
1	2	    ARM frequency has been caped
2	4	    Currently throttled
3	8	    Soft temperature limit is active
16	1000	Under-voltage has occurred
17	2000	ARM frequency capping has occurred
18	4000	Throttling has occurred
19	8000	Soft temperature limit has occurred

Bit16+ are resetted with a reboot (only)
"""

if __name__ == "__main__":
    throttled = subprocess.check_output(['vcgencmd', 'get_throttled']).decode('utf-8')
    try:
        tval = throttled[throttled.index('=')+1:]
        tval = int(tval, 16)
    except ValueError:
        tval = None
    else:
        tval &= 0x3fff  # remove the values which are only resetted with a reboot
    #
    n = nagios.Nagios()
    #
    if tval is None:
        status = n.UNKNOWN
    elif tval & 0x1 != 0:
        status = n.ERROR
    else:
        status = n.OK
    #
    n.exit(status, f"Undervoltage state ({throttled})")