#!/bin/bash /usr/scripts/python.sh

import time
import os
import sys
import SocketServer
import requests

import gestion.secrets_new
digicode_pass = gestion.secrets_new.get('digicode_pass')

PIDFILE = "/var/run/digicode.pid"
HOST, PORT = "zamok.adm.crans.org", 1200
INTRANET = os.getenv('DBG_INTRANET', 'intranet.crans.org')
DIGICODE_LINK = "https://%s/digicode/delete/" % INTRANET
CERTIFICATE = "/etc/ssl/certs/cacert.org.pem"

def log(message = "", logfile = "/var/log/crans/digicode.log"):
    """Log a message to the default logfile"""
    log = open(logfile, "a")
    if message:
        log.write("%s %s\n" % (time.strftime("%b %d %H:%M:%S"), message))
        log.flush()
    log.close()

def runme():
    #lpadmin
    os.setegid(108)
    #freerad
    os.seteuid(120)

    log("Starting server!")
    server = SocketServer.UDPServer((HOST, PORT), VigileHandler)
    server.serve_forever()


class VigileHandler(SocketServer.BaseRequestHandler):
    """Handler class for SocketServers, answering to door requests"""
    def handle(self):
        """Handle the request the door sent us"""
        data = self.request[0].lower()
        socket = self.request[1]
        log("%s wrote: %s" % (self.client_address[0], data))

        # if data starts with o, opened door validation, else should
        # be a code
        if not data.startswith("o"):
            try:
                int(data)
                response = requests.post(DIGICODE_LINK, data = {'password' : digicode_pass, 'code' : data}, verify = CERTIFICATE, timeout=0.5)
                if response.content == u'Code Successfully Deleted':
                    socket.sendto("passoir,o=1", self.client_address)
            except ValueError:
                log("Bad data from digicode")
            
            log("%s -- %s" % (data, response.content))

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(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
    runme()
