#!/usr/local/bin/python

import os, sys, re, string

def main ():
    if len (sys.argv) != 4:
        print >> sys.stderr, "usage: adservers-conf dnscache-dir tinydns-ip web-ip"
        sys.exit (1)

    dnscache_dir, tinydns_ip, web_ip = sys.argv [1:]

    domain_pre = dnscache_dir + "/root/servers/"

    domains = {}

    # Clean away previous adblocker domains
    domain_files = os.listdir (domain_pre)
    for domain in domain_files:
        dnsfile = file (domain_pre + domain, "r");  first = dnsfile.readline ();  del dnsfile
        if first == "# ADBLOCKER GENERATED":
            os.remove (domain_pre + domain)

    # Build domains from registry dump
    domain_re = re.compile (r'\\Zones\\([\w\.\-]+)')

    f = file ('adblocker.reg')
    for line in f.readlines ():
        line = line.translate (string.maketrans ('', ''), '\0')  # strip unicode nulls
        m = domain_re.search (line)
        if m: domains [m.group (1)] = 1

    # .. from append
    if os.path.exists ('append'):
        f = open ('append')
        for line in f.readlines ():
            domains [line.rstrip ()] = 1

    # .. from remove
    if os.path.exists ('remove'):
        f = open ('remove')
        for line in f.readlines ():
            key = line.rstrip ()
            if key in domains: del domains [key]

    # Generate domain files
    sorted = domains.keys ();  sorted.sort ()
    for domain in sorted:
        dnsfile = file (dnscache_dir + "/root/servers/" + domain, "w")
        print >> dnsfile, "# ADBLOCKER GENERATED"
        print >> dnsfile, tinydns_ip
        del dnsfile

        print ".%s:%s:"   % (domain, tinydns_ip)
        print "+%s:%s:"   % (domain, web_ip)
        print "+*.%s:%s:" % (domain, web_ip)
    

main ()
