#!/usr/bin/python
"""
Check that it's possible to establish http and ftp connections against
ubuntu.com
"""
from subprocess import call
import urllib2

def main():
    """
    Check HTTP and FTP connections
    """
    url = {"http": "http://cdimage.ubuntu.com/daily/current/",
           "ftp": "ftp://cdimage.ubuntu.com/cdimage/daily/current/",}

    results = {}
    for protocol, value in url.iteritems():
        results[protocol] = check_url(url[protocol])

    bool2str = {True: 'Success', False: 'Failed'}
    message = ("HTTP connection: %(http)s\n"
               "FTP connection: %(ftp)s\n"
               % dict([(protocol, bool2str[value])
                       for protocol, value in results.iteritems()]))

    command = ["zenity", "--title=Network",
               "--text=%s" % message]

    if all(results.values()):
        command.append("--info")
    else:
        command.append("--error")

    call(command)


def check_url(url):
    """
    Open URL and return True if no exceptions were raised
    """
    try:
        urllib2.urlopen(url)
    except urllib2.URLError:
        return False

    return True


if __name__ == "__main__":
    main()
