#!/usr/bin/env python
import urllib2
import ssl
from urllib import quote
from argparse import ArgumentParser


URI = "https://dyn.dns.he.net/nic/update?hostname={hostname}&password={key}"


parser = ArgumentParser(description='Update dns.he.net dynamic zone')
parser.add_argument('-K', '--key', dest='key', required=True, help='Key')
parser.add_argument('-H', '--hostname', dest='hostname', required=True, help='Hostname')
parser.add_argument('--ip', dest='ip', help='IP address')


def main(args):
    url = URI.format(hostname=quote(args.hostname), key=quote(args.key))
    if args.ip:
        url += "&myip={ip}".format(ip=args.ip)

    req = urllib2.Request(url)
    ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    return urllib2.urlopen(req, context=ssl_ctx).read()


if __name__ == '__main__':
    options = parser.parse_args()
    print(main(options))
    exit(0)
