#!/usr/bin/env python


from __future__ import print_function


from sys import stdin
from os import environ
from socket import gethostname
from traceback import format_exc
from xmlrpclib import ServerProxy
from optparse import OptionParser


USAGE = "%prog [options] target message"


def parse_options():
    parser = OptionParser(USAGE)

    parser.add_option(
        "-u", "--url",
        action="store", default="http://localhost:9000/xml-rpc/", dest="url",
        help="Specify url to send message to (XML-RPC)"
    )

    opts, args = parser.parse_args()

    if len(args) < 2:
        parser.print_help()
        raise SystemExit, 1

    return opts, args


def rpc(url, method, *args):
    try:
        server = ServerProxy(url, allow_none=True)
        return getattr(server, method)(*args)
    except Exception, error:
        return "ERROR: {0:s}\n{1:s}".format(error, format_exc())


def main():
    opts, args = parse_options()

    url = opts.url
    target = args[0]

    if args[1] == "-":
        message = stdin.read()
    else:
        message = " ".join(args[1:])

    user = environ["USER"]
    hostname = gethostname()
    source = "{0:s}@{1:s}".format(user, hostname)
    print(rpc(url, "rpc.message", source, target, message))


if __name__ == "__main__":
    main()
