#!/usr/bin/python3
#
# Copyright (c) 2017 Red Hat, Inc.
#
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

from getpass import getpass
from optparse import Option, OptionParser
import io
import re
import sys

try:
    import xmlrpclib
except ImportError:
    import xmlrpc.client as xmlrpclib  # pylint: disable=F0401

def processCommandline(argv):
    optionsTable = [
        Option('--server', action='store', dest='server',
            help='URL of your Spacewalk server.'),
        Option('--user', action='store', dest='username',
            help='Name of user to log in.'),
        Option('--password', action='store', dest='password',
            help='If you do not specify this and unless --nologin is specified, you will be prompted for your password.'),
        Option('--login', action='store_true', dest='login', default=True,
            help='If we should log in or not. Default is to log in.'),
        Option('--nologin', action='store_false', dest='login',
            help='If we should log in or not. Default is to log in.'),
    ]
    optionParser = OptionParser(
        usage="Usage: %s --server=<server> [--login] [--user=<user>] [--password=<password>]" % sys.argv[0],
        option_list=optionsTable)

    options, unparsed = optionParser.parse_args(argv[1:])

    if not options.server:
        sys.stderr.write('Error: No server specified.\n')
        sys.exit(1)

    if not options.username and options.login:
        with io.TextIOWrapper(open('/dev/tty', 'r+b', buffering=0)) as tty:
            tty.write('Enter username: ')
            try:
                options.username = tty.readline()
            except KeyboardInterrupt:
                tty.write("\n")
                sys.exit(0)

    if not options.password and options.login:
        options.password = getpass('Enter your password: ')

    return options, unparsed

if __name__ == '__main__':
    options, unparsed = processCommandline(sys.argv)

    client = xmlrpclib.Server('http://%s/rpc/api' % options.server, verbose=0)
    session = ''
    if options.login:
        try:
            session = client.auth.login(options.username, options.password)
        except xmlrpclib.Fault:
            sys.stderr.write('Error: %s \n' % str(sys.exc_info()[1]))
            sys.exit(1)

    params = []
    for param in unparsed:
        if param == '%session%':
            param = session
        elif re.compile('%file:(.*)%').search(param):
            filename = re.compile('%file:(.*)%').search(param).groups()[0]
            with open(filename, 'r') as f:
                param = f.read()
        elif re.compile('%boolean:(.*)%').search(param):
                param = bool(re.compile('%boolean:(.*)%').search(param).groups()[0])
        elif re.compile('%integer:(.*)%').search(param):
                param = int(re.compile('%integer:(.*)%').search(param).groups()[0])
        elif re.compile('%string:(.*)%').search(param):
                param = re.compile('%string:(.*)%').search(param).groups()[0]
        params.append(param)

    try:
        result = getattr(client, params[0])(*params[1:])
        sys.stdout.write(str(result) + '\n')
    except xmlrpclib.Fault:
        sys.stderr.write('Fault returned from XML RPC Server: %s\n' % str(sys.exc_info()[1]))
        sys.exit(1)
    finally:
        if options.login:
            client.auth.logout(session)
