#!/usr/bin/python
"""
Check that it's possible to establish a http connection against
ubuntu.com
"""
from subprocess import call
from optparse import OptionParser, Option
import httplib
import urllib2
import sys


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

    return True

def main():
    """
    Check HTTP and connection
    """
    usage = 'Usage %prog [OPTIONS]'
    parser = OptionParser(usage)
    parser.add_option('-a', '--auto',
                        action='store_true',
                        default=False,
                        help='Runs in Automated mode, with no visible output')
    
    (options,args) = parser.parse_args()

    url = { "http": "http://cdimage.ubuntu.com/daily/current/" }

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

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

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

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

    if not options.auto:
        try:
            call(command)
        except OSError:
            print("Zenity missing; unable to report test result:\n %s" % message)
   
    if any(results.itervalues()):
        return 0
    else:
        return 1

if __name__ == "__main__":
    sys.exit(main())
