#!/usr/bin/env python
"""A hacky wrapper around the koji cli script"""

# Copyright (C) 2015  Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
# USA

# Authors:
#       Pavol Babincak <pbabinca@redhat.com>


import imp
import sys

import koji

try:
    from distutils.spawn import find_executable
except ImportError:
    # Hard code usual paths
    koji_exe_path = '/usr/bin/koji'
else:
    koji_exe_path = find_executable('koji')

fo = file(koji_exe_path, 'U')
try:
    clikoji = imp.load_module('clikoji', fo, fo.name, ('.py', 'U', 1))
finally:
    fo.close()

from koji_containerbuild import cli as containerbuild_cli

# koji_containerbuild expects koji module here
containerbuild_cli.clikoji = clikoji

if __name__ == "__main__":
    clikoji.handle_container_build = containerbuild_cli.handle_container_build
    options, command, args = clikoji.get_options()
    # work around a bug in older koji versions
    if options.topdir:
        koji.BASEDIR = options.topdir
        koji.pathinfo.topdir = options.topdir

    clikoji.options = options
    session_opts = {}
    for k in ('user', 'password', 'debug_xmlrpc', 'debug'):
        session_opts[k] = getattr(options,k)
    session = koji.ClientSession(options.server,session_opts)
    rv = 0
    try:
        rv = vars(clikoji)[command].__call__(options, session, args)
        if not rv:
            rv = 0
    except KeyboardInterrupt:
        pass
    except SystemExit:
        rv = 1
    except:
        if options.debug:
            raise
        else:
            exctype, value = sys.exc_info()[:2]
            rv = 1
            print "%s: %s" % (exctype.__name__, value)
    try:
        session.logout()
    except:
        pass
    sys.exit(rv)
