# the inventory function

# Example output:
# Puppet_version: 5.5.21
# Environment: checkmk_1_6
# Resources_changed: 0
# Resources_failed: 0
# Run_time: 27.767
# Last_run: 57



factory_settings["puppet_status_default_levels"] = {
	"Resources_failed": 	(1,2),       # Warn at 1, Crit a 2+
	"Resources_changed": 	(100,500)  , # Warn at 100+ changes, Crit at 500+
	"Run_time": 	(60.0,500.0),          # Warn at 60 seconds, Crit a 500+ seconds
	"Last_run": 	(2100,3900),         # Warn at 2100 seconds, Crit a 3900+
}

def parse_puppet(info):
	parsed = {};        
	for field, value in info:
		parsed[field.rstrip(':')]=value.lstrip()

	return parsed


def inventory_puppet(parsed):
# What do we want to track, if anything specific?  What indicates good data?
    if parsed.get("Puppet_version") and parsed.get("Last_run"):
	return  [(None, {})]
    else:
	return []


# the check function
def check_puppet(item, params, parsed):

    status = 0
    perfdata = []
    message = "Version: %s, Environment: %s," % (str(parsed["Puppet_version"]), str(parsed["Environment"]))

    for field in [
	"Resources_changed",
	"Resources_failed",
	"Last_run",
	"Run_time", ]:
		warn, crit = params[field]
		if field in parsed.keys():
			try:
				value = savefloat(parsed[field])
			except:
				value = saveint(parsed[field])

			if crit != None and value >= crit:
				message += " CRIT %s: %d," % (field, value)
				status = max(2, status)
			elif warn != None and value >= warn:
				message += " WARN %s: %d," % (field, value)
				status = max(1, status)
			else:
				message += " %s: %d," % (field, value)

# Syntax for perfdata:   valuename value warn_lower warn_upper crit_lower crit_upper
			if isinstance(value, int):
				perfdata.append((field, "%d" % value, warn, crit))
			else:
				perfdata.append((field, "%f" % value, warn, crit))
		else:
			message += " UNKNOWN %s missing/malformed in puppet status," % field
			status = max(3, status)

    return (status, message.rstrip(','), perfdata)


# declare the check to Check_MK

check_info["puppet_status"] = {
    'parse_function': parse_puppet,
    'check_function': check_puppet,
    'inventory_function': inventory_puppet,
    'service_description': 'Puppet Status',
    'default_levels_variable': 'puppet_status_default_levels',
    'has_perfdata': True,
}

