#!/usr/bin/env python

""" calls the dyndns client to update the dns entry to our ip
"""

networkInterface = "ppp0"

import socket
import fcntl
import struct
import subprocess

def get_ip_address(ifname):
    """" return the ip of a given interface """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15]))[20:24])

def _call(args):
    """ this is a helper function which executes programs and
        throws a helpfull exception for the user if it didn't work
    """
    p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
    p.wait()
    if p.returncode < 0:
        raise IOError, "Child was terminated by signal %d - output: %s" % (0-p.returncode , p.stdout.read())
    elif p.returncode > 0:
        raise IOError, "Child returned %d - output: %s" % (p.returncode, p.stdout.read())
    
# Main program: parse command line and start processing
def main():
    _call(("/usr/sbin/ddclient", "-ip", get_ip_address(networkInterface)))
    
if __name__ == '__main__':
    main()
