#!/usr/bin/env python3

from requests import get
from sys import argv, exit

meshviewer_url = argv[1]
node_id = argv[2]
node = None

try:
    for n in get(meshviewer_url).json()['nodes']:
        if node_id == n['node_id']:
            node = n
            break

    if not node:
        print('CRITICAL: Node {} not found in {}'.format(
            node_id,
            meshviewer_url,
        ))
        exit(2)

    if not node['is_online']:
        print('CRITICAL: Node "{}" is offline!'.format(
            node['hostname'],
        ))
        exit(2)

    crit = set()
    warn = set()
    if node['loadavg'] > 1:
        warn.add('has high load: {}'.format(
            node['loadavg'],
        ))

    if node['rootfs_usage'] > 0.9:
        crit.add('rootfs usage is {}%'.format(
            int(node['rootfs_usage']*100)
        ))
    elif node['rootfs_usage'] > 0.8:
        warn.add('rootfs usage is {}%'.format(
            int(node['rootfs_usage']*100)
        ))

    if node['memory_usage'] > 0.9:
        crit.add('ram usage is {}%'.format(
            int(node['memory_usage']*100)
        ))
    elif node['memory_usage'] > 0.8:
        warn.add('ram usage is {}%'.format(
            int(node['memory_usage']*100)
        ))


    for line in sorted(crit):
        print('CRITICAL: Node "{}" {}'.format(
            node['hostname'],
            line,
        ))

    for line in sorted(warn):
        print('WARNING: Node "{}" {}'.format(
            node['hostname'],
            line,
        ))

    if crit:
        exit(2)
    elif warn:
        exit(1)
    else:
        print('Node "{}" reports no errors'.format(
            node['hostname'],
        ))
        exit(0)
except Exception as e:
    print(repr(e))
    exit(3)