#!/usr/bin/python
import sys
sys.path.append('pydhcplib/')
import pydhcplib
import pydhcplib.dhcp_network
from pydhcplib.dhcp_packet import *
from pydhcplib.type_hw_addr import hwmac
from pydhcplib.type_ipv4 import ipv4
from pydhcplib.type_strlist import strlist

import event_logger
if '__main__' == __name__:
    event_logger.init("stdout", 'DEBUG', {})
from event_logger import Log

import sipb_xen_database

dhcp_options = {'subnet_mask': '255.255.0.0',
                'router': '18.181.0.1',
                'domain_name_server': '18.70.0.160,18.71.0.151,18.72.0.3',
                'domain_name': 'mit.edu'}
    

class DhcpBackend:
    def __init__(self, database=None):
        if database is not None:
            sipb_xen_database.connect(database)
    def findIP(self, mac):
        value = sipb_xen_database.NIC.get_by(mac_addr=mac)
        if value is None:
            return None
        ip = value.ip
        if ip is None:  #Deactivated?
            return None
        return ip
    def getParameters(self):
        options = {}
        for parameter, value in dhcp_options.iteritems():
            option_type = DhcpOptionsTypes[DhcpOptions[parameter]]

            if option_type == "ipv4" :
                # this is a single ip address
                options[parameter] = map(int,value.split("."))
            elif option_type == "ipv4+" :
                # this is multiple ip address
                iplist = value.split(",")
                opt = []
                for single in iplist :
                    opt.append(ipv4(single).list())
                options[parameter] = opt
            elif option_type == "32-bits" :
                # This is probably a number...
                digit = int(value)
                options[parameter] = [digit>>24&0xFF,(digit>>16)&0xFF,(digit>>8)&0xFF,digit&0xFF]
            elif option_type == "16-bits" :
                digit = int(value)
                options[parameter] = [(digit>>8)&0xFF,digit&0xFF]

            elif option_type == "char" :
                digit = int(value)
                options[parameter] = [digit&0xFF]

            elif option_type == "bool" :
                if value=="False" or value=="false" or value==0 :
                    options[parameter] = [0]
                else : options[parameter] = [1]
                    
            elif option_type == "string" :
                options[parameter] = strlist(value).list()
                
            else :
                options[parameter] = strlist(value).list()
        return options

    def Discover(self, packet):
        Log.Output(Log.debug,"dhcp_backend : Discover ")
        chaddr = hwmac(packet.GetHardwareAddress())
        ip = self.findIP(str(chaddr))
        if ip is not None:
            ip = ipv4(ip)
            Log.Output(Log.debug,"dhcp_backend : Discover result = "+str(ip))
            packet_parameters = self.getParameters()

            # FIXME: Other offer parameters go here
            packet_parameters["yiaddr"] = ip.list()
            
            packet.SetMultipleOptions(packet_parameters)
            return True
        return False
        
    def Request(self, packet):
        Log.Output(Log.debug, "dhcp_backend : Request")
        
        discover = self.Discover(packet)
        
        chaddr = hwmac(packet.GetHardwareAddress())
        request = packet.GetOption("request_ip_address")
        yiaddr = packet.GetOption("yiaddr")

        if not discover:
            Log.Output(Log.info,"Unknown MAC address: "+str(chaddr))
            return False
        
        if yiaddr!="0.0.0.0" and yiaddr == request :
            Log.Output(Log.info,"Ack ip "+str(yiaddr)+" for "+str(chaddr))
            return True
        else:
            Log.Output(Log.info,"Requested ip "+str(request)+" not available for "+str(chaddr))
        return False

    def Decline(self, packet):
        pass
    def Release(self, packet):
        pass
    

class DhcpServer(pydhcplib.dhcp_network.DhcpServer):
    def __init__(self, backend, options = {'client_listenport':68,'server_listenport':67}):
        pydhcplib.dhcp_network.DhcpServer.__init__(self,"0.0.0.0",options["client_listen_port"],options["server_listen_port"],)
        self.backend = backend
        Log.Output(Log.debug, "__init__ DhcpServer")

    def SendPacket(self, packet):
        """Encode and send the packet."""
        
        giaddr = packet.GetOption('giaddr')

        # in all case, if giaddr is set, send packet to relay_agent
        # network address defines by giaddr
        if giaddr!=[0,0,0,0] :
            agent_ip = ".".join(map(str,giaddr))
            self.SendDhcpPacketTo(agent_ip,packet)
            Log.Output(Log.debug, "SendPacket to agent : "+agent_ip)

        # FIXME: This shouldn't broadcast if it has an IP address to send
        # it to instead. See RFC2131 part 4.1 for full details
        else :
            Log.Output(Log.debug, "No agent, broadcast packet.")
            self.SendDhcpPacketTo("255.255.255.255",packet)
            

    def HandleDhcpDiscover(self, packet):
        """Build and send DHCPOFFER packet in response to DHCPDISCOVER
        packet."""

        logmsg = "Get DHCPDISCOVER packet from " + hwmac(packet.GetHardwareAddress()).str()

        Log.Output(Log.info, logmsg)
        offer = DhcpPacket()
        offer.CreateDhcpOfferPacketFrom(packet)
        
        if self.backend.Discover(offer):
            self.SendPacket(offer)
        # FIXME : what if false ?


    def HandleDhcpRequest(self, packet):
        """Build and send DHCPACK or DHCPNACK packet in response to
        DHCPREQUEST packet. 4 types of DHCPREQUEST exists."""

        ip = packet.GetOption("request_ip_address")
        sid = packet.GetOption("server_identifier")
        ciaddr = packet.GetOption("ciaddr")

        if sid != [0,0,0,0] and ciaddr == [0,0,0,0] :
            Log.Output(Log.info, "Get DHCPREQUEST_SELECTING_STATE packet")

        elif sid == [0,0,0,0] and ciaddr == [0,0,0,0] and ip :
            Log.Output(Log.info, "Get DHCPREQUEST_INITREBOOT_STATE packet")

        elif sid == [0,0,0,0] and ciaddr != [0,0,0,0] and not ip :
            Log.Output(Log.info,"Get DHCPREQUEST_INITREBOOT_STATE packet")

        else : Log.Output(Log.info,"Get DHCPREQUEST_UNKNOWN_STATE packet : not implemented")

        if self.backend.Request(packet) : packet.TransformToDhcpAckPacket()
        else : packet.TransformToDhcpNackPacket()

        self.SendPacket(packet)



    # FIXME: These are not yet implemented.
    def HandleDhcpDecline(self, packet):
        Log.Output(Log.info, "Get DHCPDECLINE packet")
        self.backend.Decline(packet)
        
    def HandleDhcpRelease(self, packet):
        Log.Output(Log.info,"Get DHCPRELEASE packet")
        self.backend.Release(packet)
        
    def HandleDhcpInform(self, packet):
        Log.Output(Log.info, "Get DHCPINFORM packet")

        if self.backend.Request(packet) :
            packet.TransformToDhcpAckPacket()
            # FIXME : Remove lease_time from options
            self.SendPacket(packet)

        # FIXME : what if false ?

if '__main__' == __name__:
    options = { "server_listen_port":67,
                "client_listen_port":68,
                "listen_address":"0.0.0.0"}
    backend = DhcpBackend('postgres://sipb-xen@sipb-xen-dev/sipb_xen')
    server = DhcpServer(backend, options)

    while True : server.GetNextDhcpPacket()
