import re
from socket import gethostbyname
from netaddr import IPAddress

class CheckRBL(object):

    def __init__(self, client):
        self.client = client

    def check(self, ip):
        ipobj = IPAddress(ip)
        splitip = re.split("\.in-addr", ipobj.reverse_dns)
        reversedip = splitip[0]

        efnetaddr = "{}.rbl.efnetrbl.org".format(reversedip)
        spamhausaddr = "{}.zen.spamhaus.org".format(reversedip)
        sorbsaddr = "{}.safe.dnsbl.sorbs.net".format(reversedip)

        # EFNet RBL
        try:
            returncode = gethostbyname(efnetaddr)
        except:
            pass
        else:
            self.client.sendtochannel("{} is in the EFNet RBL".format(ip))
            return

        # Spamhaus
        try:
            returncode = gethostbyname(spamhausaddr)
        except:
            pass
        else:
            if returncode == "127.0.0.2":
                self.client.sendtochannel("{} is in the SBL".format(ip))
            elif returncode == "127.0.0.3":
                self.client.sendtochannel("{} is in the SBL CSS".format(ip))
            elif returncode == "127.0.0.4":
                self.client.sendtochannel("{} is in the XBL".format(ip))
            return

        # Sorbs
        try:
            returncode = gethostbyname(sorbsaddr)
        except:
            pass
        else:
            if returncode == "127.0.0.2":
                self.client.sendtochannel("{} is an HTTP proxy".format(ip))
            elif returncode == "127.0.0.3":
                self.client.sendtochannel("{} is a SOCKS proxy".format(ip))
            elif returncode == "127.0.0.4":
                self.client.sendtochannel("{} is some sort of proxy".format(ip))
            elif returncode == "127.0.0.5":
                self.client.sendtochannel("{} is an open relay".format(ip))
            elif returncode == "127.0.0.6":
                self.client.sendtochannel("{} is a spam server".format(ip))
            elif returncode == "127.0.0.7" or returncode == "127.0.0.9":
                self.client.sendtochannel("{} is a pwned server".format(ip))
            elif returncode == "127.0.0.8":
                self.client.sendtochannel(
                    "{} is a server that is scared to face Sorbs".format(ip))
            return

        self.client.sendtochannel("{} is not on any RBL".format(ip))
