#!/usr/bin/env python
"""
nagios-helper - Reads a nagios.cmd fifo for external check commands and sends them to a remote NSCA daemon

Author: Lars Larsson <lars@lars.la>
"""

import multiprocessing
import os
import time
import daemonize
import ConfigParser
import sys
import pwd
import setproctitle

from readthread import ReadThread
from sendthread import SendThread

Config = ConfigParser.ConfigParser()
parsed = Config.read(['/etc/nagios-helper.cfg', os.path.expanduser('~/.nagios-helper.cfg')])

if not parsed:
    print "Could not parse config file"
    exit(-1)

logfile = str(Config.get('nagios-helper', 'logfile'))
pidfile = str(Config.get('nagios-helper', 'pidfile'))
fifoname = str(Config.get('nagios-helper', 'fifoname'))
user = str(Config.get('nagios-helper', 'user'))
group = str(Config.get('nagios-helper', 'group'))
debug = bool(int(Config.get('nagios-helper', 'debug')))

nsca_host = str(Config.get('nsca', 'host'))
nsca_port = int(Config.get('nsca', 'port'))
nsca_crypt = int(Config.get('nsca', 'crypt'))
nsca_password = str(Config.get('nsca', 'password'))

MAXTHREADS = int(Config.get('nagios-helper', 'max_threads'))

threads = []

class MyLog(object):
    def write(self, line):
        daemonize.logging.debug(line.strip('\n'))

    def flush(self):
        pass

def create_fifo(fifoname):
    os.mkfifo(fifoname)

def run():
    # Redirect output
    sys.stdout = MyLog()
    sys.stderr = MyLog()

    # Initialize queue
    queue = multiprocessing.Queue()

    try:
        # Start the read thread
        threads.append(ReadThread(0, fifoname, queue, debug=debug))
        threads[0].start()

        # Start our send threads
        for i in range(1, MAXTHREADS):
            threads.append(SendThread(i, queue, nsca_host, nsca_port=nsca_port, nsca_crypt=nsca_crypt, password=nsca_password, debug=debug))
            threads[i].start()

        while 1:
            time.sleep(10)
    except KeyboardInterrupt:
        print "Got KeyboardInterrupt"
        for i in range(0, MAXTHREADS):
            threads[i].terminate()

if __name__=="__main__":
    if os.getuid() != 0:
        print "Don't you want to run this as root?"
        print "Some things might not work!"
    else:
        # Get uid and gid
        p = pwd.getpwnam(user)
        uid = p[2]
        gid = p[3]

        # Make sure the fifo file exists
        if not os.path.exists(fifoname):
            os.mkfifo(fifoname)
            os.chown(fifoname, uid, gid)
            os.chmod(fifoname, 0770)

        # Make sure the log file exists
        if not os.path.exists(logfile):
            open(logfile, 'w').close()
            os.chown(logfile, uid, gid)
            os.chmod(logfile, 0644)

        # Make sure the pid file exists
        if not os.path.exists(pidfile):
            open(pidfile, 'w').close()
            os.chown(pidfile, uid, gid)
            os.chmod(pidfile, 0644)

        # Change user
        os.setgid(gid)
        os.setuid(uid)

    setproctitle.setproctitle("nagios-helper")
    daemonize.start(run, pidfile, logfile, debug=True)