import info
nameservers = set()
import os

try:
    import winreg

    module = 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters'

    for name in ('NameServer','DhcpNameServer'):
        a = _winreg.QueryValue(module,name)
        if a:
            nameservers.update(a.split())

    def setResolver(resolver):
        _winreg.SetValue(module,'NameServer',winreg.REG_SZ,resolver)

except ImportError: 
    # everyone else...
    with open("/etc/resolv.conf") as inp:
        for line in inp:
            if line.startswith("nameserver "):
                ns = line[len("nameserver "):].rstrip().split(' ')
                nameservers.update(ns)

    marker = '# generated by specialDNS DO NOT DELETE THIS LINE'
    def setResolver(resolver):
        lines = []
        with open('/etc/resolv.conf') as inp:
            for line in inp:
                if line.rstrip()==marker:
                    lines = []
                else:
                    lines.append(line)
        with open("/etc/resolv.conf+","w") as out:
            out.write("# generated by specialDNS thingy\n")
            out.write("domain localhost\nsearch localhost\n")
            out.write("nameserver "+resolver+"\n")
            out.write(marker+"\n")
            for line in lines:
                out.write(line)        
        os.unlink("/etc/resolv.conf")
        os.rename("/etc/resolv.conf+","/etc/resolv.conf")

saved = os.path.join(os.path.expanduser("~"),".config","dns")
if not os.path.exists(saved):
    os.makedirs(saved)

def recoverLast():
    global nameservers
    # This is a last ditch effort that recovers previously known name servers
    # (As they're most often static anyway)
    if len(nameservers)==0:
        try:
            with open(os.path.join(saved,"lastServers")) as inp:
                nameservers.update((l.strip() for l in inp.readlines()))
        except IOError: pass
    else:
        try:
            with open(os.path.join(saved,"lastServers"),"w") as out:
                for server in nameservers:
                    out.write(server+os.linesep)
        except IOError,e: 
            print e
    print "arg",nameservers
                                   

