#!/usr/bin/python

import os, sys, traceback
import GeoIP

ALLOW = 0
DENY = 1

when_error = ALLOW
exitcode = when_error


def rule(code):
    if code == "IT": return ALLOW
    if code == None: return ALLOW
    return DENY

def append_address(value, filename):
    host = str(value)
    logfile = open(filename, 'a+')
    try:
        for line in logfile:
            if line.strip() == host:
                return

        # Move to the end of the file:
        logfile.seek(0, 2)
        logfile.write(host + "\n")

    finally:
        logfile.close()

try:
    log = os.popen("logger -t geoip/check -p daemon.notice", "w")
    sys.stdout = log
    sys.stderr = log

    if len(sys.argv) < 2:
        sys.stderr.write("Usage: %s ipaddress\n" % sys.argv[0])
        sys.exit(0)
    addr = sys.argv[1]
    if len(sys.argv) == 3:
        allowed_ip_file = sys.argv[2]

    datafile = os.path.join(os.path.dirname(__file__), "GeoIP.dat")

    g = GeoIP.open(datafile, GeoIP.GEOIP_STANDARD)
    if not g:
        sys.exit(0)
    code = g.country_code_by_addr(addr)
    exitcode = rule(code)
    print "%s %s %s" % (addr, code, exitcode and "deny" or "allow")
    if (exitcode==0 and allowed_ip_file):
        try:
            #open(allowed_ip_file,"a").write(addr)
            append_address(str(addr), allowed_ip_file)
        except:
            print "could not append '%s' to '%s'" % (addr, allowed_ip_file)
except SystemExit:
    pass
except:
    traceback.print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)

sys.exit(exitcode)

