#!/usr/bin/env python
"""Register with a facilitator using the HTTP method."""

import argparse
import flashproxy
import sys
import urllib2

from flashproxy.util import format_addr, parse_addr_spec, safe_format_addr
from flashproxy.reg import DEFAULT_FACILITATOR_URL, DEFAULT_REMOTE, DEFAULT_TRANSPORT, build_reg

parser = argparse.ArgumentParser(
    usage="%(prog)s [OPTIONS] [REMOTE][:PORT]",
    description="Register with a flash proxy facilitator using an HTTP POST. "
    "If only the external port is given, the remote server guesses our "
    "external address.")
flashproxy.util.add_module_opts(parser)
parser.add_argument("--transport", metavar="TRANSPORT",
    help="register using the given transport, default %(default)s.",
    default=DEFAULT_TRANSPORT)
parser.add_argument("remote_addr", metavar="ADDR:PORT",
    help="external addr+port to register, default %s" %
    format_addr(DEFAULT_REMOTE), default="", nargs="?",
    type=lambda x: parse_addr_spec(x, *DEFAULT_REMOTE))
parser.add_argument("-f", "--facilitator", metavar="URL",
    help="register with the given facilitator, default %(default)s.",
    default=DEFAULT_FACILITATOR_URL)

options = parser.parse_args(sys.argv[1:])
flashproxy.util.enforce_address_family(options.address_family)

body = build_reg(options.remote_addr, options.transport)
try:
    http = urllib2.urlopen(options.facilitator, body, 10)
except urllib2.HTTPError, e:
    print >> sys.stderr, "Status code was %d, not 200" % e.code
    sys.exit(1)
except urllib2.URLError, e:
    print >> sys.stderr, "Failed to register: %s" % str(e.reason)
    sys.exit(1)
except Exception, e:
    print >> sys.stderr, "Failed to register: %s" % str(e)
    sys.exit(1)
http.close()

print "Registered \"%s\" with %s." % (safe_format_addr(options.remote_addr), options.facilitator)
