#!/usr/bin/python
"""XMPP message sender"""
# Copyright (C) 2009-2010, Denis E. Klimov <zver@altlinux.org>
# Copyright (C) 2010, Vladimir V. Kamarzin <vvk@altlinux.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the <organization> nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import os
import sys
import getopt
import argparse
import textwrap
import xmpp
import time

# parse command line options
parser = argparse.ArgumentParser(
		description='Simple xmpp message sender',
		formatter_class=argparse.RawDescriptionHelpFormatter,
		epilog=textwrap.dedent('''\
			You may set default params in file $HOME/.sendxmppy with syntax on first line:
			<username>@<server>[:port] <password>\n
			Report bugs to https://bugzilla.altlinux.org/'''))
parser.add_argument('-d', '--debug', action='store_true',
		help='Print debug messages')
parser.add_argument('-f', '--file',
		help='Path to config file')
parser.add_argument('-m', '--message',
		help='Text of message. Also may be obtained from pipe')
parser.add_argument('-j', '--jid',
		help='Jabber id to use')
parser.add_argument('-p', '--password',
		help='Password for jid')
parser.add_argument('-o', '--port', type=int,
		help='Custom port to connect')
parser.add_argument('-r', '--resource', default=parser.prog,
		help='Jabber resource for message')
parser.add_argument('-c', '--chat', action='store_true',
		help='Send message with type=chat')
parser.add_argument('recipient', nargs='+',
		help='Space-separated recipients list')
args = parser.parse_args()

port = None

# determine config file to use
if args.file:
	file = args.file
else:
	env = os.environ
	if 'HOME' in env:
		file = env['HOME'] + '/.sendxmppy'
	else:
		file = '/etc/sendxmppy.conf'

# get default settings from config file
if os.path.isfile(file) and not args.jid:
	f = open(file, "r")
	line = f.readline().split()
	f.close()
	if len(line) == 2:
		jid_port, password = line
		if jid_port.find(':') == -1:
			jid = jid_port
		else:
			jid, port = jid_port.split(':')
	else:
		sys.stderr.write('Wrong syntax in %s\n', conf_file_path)
		sys.exit(1)
else:
	jid, password = args.jid, args.password

# use command-line specified port even if it defined in config
if args.port:
	port = args.port

# read message from stdin if "-m" wasn't passed
if not args.message:
	import codecs
	sys.stdin = codecs.getreader("utf-8")(sys.stdin)
	message = sys.stdin.read()
else:
	message = args.message

# create xmpp client
jid = xmpp.protocol.JID(jid)
server = jid.getDomain()
if args.debug:
	client = xmpp.Client(server)
else:
	client = xmpp.Client(server, debug=[])

# connect to server
if not port:
	con = client.connect()
else:
	con = client.connect((server, port), use_srv=False)
if not con:
	sys.stderr.write('Cannot connect to server. Try to run with -d and see why\n')
	sys.exit(1)

# perform authentication
auth = client.auth(jid.getNode(), password, resource=args.resource)
if not auth:
	sys.stderr.write('Cannot authenticate to server\n')
	sys.exit(1)

# send message
if args.chat:
	for tojid in args.recipient:
		id = client.send(xmpp.protocol.Message(tojid, message, 'chat'))
		time.sleep(1)
else:
	for tojid in args.recipient:
		id = client.send(xmpp.protocol.Message(tojid, message))
		time.sleep(1)

