#!/usr/bin/env python2
from os import environ
from subprocess import Popen, PIPE

hostname, username, password = environ.get('JOKER_DYNAMIC', '::').split(':')
ext_ip_cmd = 'wget -q -O - http://www.whatismyip.org/'
dns_ip_cmd = 'dig {0} +short'.format(hostname)
new_ip_cmd = 'wget -q -O - "http://svc.joker.com/nic/update?username={0}&password={1}&hostname={2}&myip={3}"'


pub_ip = Popen(ext_ip_cmd.split(), stdout=PIPE).communicate()[0].strip()
print 'public ip: {0}'.format(pub_ip)


dns_ip = Popen(dns_ip_cmd.split(), stdout=PIPE).communicate()[0].strip()
print 'dns ip:    {0}'.format(dns_ip)


if pub_ip != dns_ip:
    print 'updating...'
    cmd = new_ip_cmd.format(username, password, hostname, pub_ip)
    print Popen(cmd.split(), stdout=PIPE).communicate()[0]
else:
    print 'no change'
