#!/usr/bin/python -W ignore::DeprecationWarning
import os
import pwd
import sys
import lap
import time
import grp

#from supay import Daemon
from glob import glob as ls

def run(daemon):
    daemon.start()
    while True:

        # 1 -> Run check-mk based plugins
        plugin_dir = "/usr/share/locaweb-plugins/check-mk/"
        for plugin in ls(os.path.join(plugin_dir, "*")):
            lap.execute_plugin_local(plugin)

        # 2 -> Run local forced plugins
        plugin_dir = "/usr/share/locaweb-plugins/local/"
        for plugin in ls(os.path.join(plugin_dir, "*")):
            lap.execute_plugin_local(plugin)

        # 3 -> Run local based on yaml plugins
        for check in lap.load_plugins():
            lap.execute_plugin(check)

        time.sleep(30)

if __name__ == '__main__':
    try:
        os.setgid(grp.getgrnam("_readproc").gr_gid)
    except:
        pass
    try:
        os.setuid(pwd.getpwnam("check-mk").pw_uid)
    except:
        print "Cannot find user check-mk and i dont like r00t"
        sys.exit(1)
    else:
        script = sys.argv[0].split("/")[-1]
        daemon = Daemon(name=script, pid_dir="/var/run/locaweb-plugins", catch_all_log="/var/log/locaweb-plugins/%s.log" % script)
    
        if sys.argv[1] == 'start':
            run(daemon)
        elif sys.argv[1] == 'stop':
            daemon.stop()
        elif sys.argv[1] == 'status':
            daemon.status()
