#!/bin/bash /usr/scripts/python.sh
# -*- coding: utf-8 -*-

"""Serveur sendmail d'arpwatch.
Permet de ne charger qu'une fois le module report (et donc lc_ldap
et cie)
Ceci écoute sur une socket unix les rapports arpwatch (via report.py)
"""

from __future__ import print_function
import SocketServer
import sys, os, pwd, grp
import common

class Handler(SocketServer.StreamRequestHandler):
    """Gestion d'une requête"""
    def handle(self):
        self.server.reporter.report(self.request.recv(1024))

class MyServer(SocketServer.UnixStreamServer):
    """Un server, avec une instance du module report"""
    reporter = None

def run():
    """Serveur permanent"""
    import report

    try:
        os.remove(common.SOCKET_FILE)
        print("Removed old socket", file=sys.stderr)
    except OSError:
        pass

    # La socket ne doit pas être accessible pour tous: on garde adm
    os.umask(007)
    os.setgid(grp.getgrnam(common.GROUP).gr_gid)

    serv = SocketServer.UnixStreamServer(common.SOCKET_FILE, Handler)
    serv.reporter = report

    serv.serve_forever()

# fork en arrière plan + pidfile
if __name__ == "__main__":
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # decouple from parent environment
    os.chdir("/")   #don't prevent unmounting....
    os.setsid()
    os.umask(0)

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            # exit from second parent, print eventual PID before
            #print "Daemon PID %d" % pid
            open(common.PIDFILE, 'w').write("%d" % pid)
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # start the daemon main loop
    run()

