#!/usr/bin/env python

import dns.zone
import dns.resolver
from urllib2 import urlopen

origin = 'roamingmonkey.org'
zonefile = './roamingmonkey.org.zone'

zone = dns.zone.from_file(zonefile, origin)

# Fetch our external IP address
url = urlopen('http://ipv4.rmky.org/ip.php')
ip4 = url.read().strip()
url.close()

banana_A = zone.find_rdataset('banana', 'A')
banana_TXT = zone.find_rdataset('banana', 'TXT')

for rdata in banana_A:
    # Don't do anything unless the the IPv4 address in the zone file is wrong
    if not rdata.address == ip4:
        rdata.address = ip4

        # Remove any existing TXT record(s) and replace with a new one
        # Method for adding gleaned from https://github.com/vimalloc/easyzone/blob/master/easyzone/easyzone.py
        for txtdata in banana_TXT:
            banana_TXT.remove(txtdata)
        txt = 'v=spf1 ip4:' + ip4 + ' -all'
        rd = dns.rdtypes.ANY.TXT.TXT(dns.rdataclass.IN, dns.rdatatype.TXT, txt)
        banana_TXT.add(rd)

        # Fetch the serial number that the world sees and leapfrog it.
        # The serial number we set here has to be higher than the DNSSEC signed
        # version so that ods-signer will recognize that it is a new version.
        # ods-signer will increment this serial once more when signing the zone.
        query = dns.resolver.query(origin, 'SOA')
        for (name, ttl, zrdata) in zone.iterate_rdatas('SOA'):
            for qrdata in query:
                zrdata.serial = qrdata.serial + 2

        zone.to_file(zonefile)
