#!/usr/bin/python2
# rpkg - a script to manage spec enriched Git repositories
#
# Copyright (C) 2018 Red Hat Inc.
# Author(s): clime <clime@redhat.com>
#
# Original work by:
# Copyright (C) 2011 Red Hat Inc.
# Author(s): Jesse Keating <jkeating@redhat.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version. See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.

import pyrpkg.utils
import os
import sys
import logging
import configparser
import argparse
import git

from rpkglib.cli import rpkgClient

# Setup an argparser and parse the known commands to get the config file
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-C', '--config', help='Specify a config file to be used. '
                    'If not specified, /etc/rpkg.conf, ~/.config/rpkg.conf, '
                    '<gitroot>/rpkg.conf and ./rpkg.conf are read '
                    'in this order. Files not present are skipped. '
                    '<gitroot> is the root directory of the '
                    'current working Git tree if we are in one.')
(args, other) = parser.parse_known_args()

# Setup a configuration object and read config file data
config = configparser.ConfigParser()

if args.config:
    config.read([args.config])
else:
    glob_conf = '/etc/rpkg.conf'
    user_conf = os.path.expanduser('~/.config/rpkg.conf')
    cwd_conf = './rpkg.conf'
    try:
        repo = git.Repo(search_parent_directories=True)
        repo_conf = os.path.join(repo.working_dir, 'rpkg.conf')
        config.read([glob_conf, user_conf, repo_conf, cwd_conf])
    except:
        config.read([glob_conf, user_conf, cwd_conf])

client = rpkgClient(config)
client.do_imports('rpkglib')
client.parse_cmdline()

if not client.args.path:
    try:
        client.args.path = pyrpkg.utils.getcwd()
    except:
        print('Could not get current path, have you deleted it?')
        sys.exit(1)

# setup the logger -- This logger will take things of INFO or DEBUG and
# log it to stdout.  Anything above that (WARN, ERROR, CRITICAL) will go
# to stderr.  Normal operation will show anything INFO and above.
# Quiet hides INFO, while Verbose exposes DEBUG.  In all cases WARN or
# higher are exposed (via stderr).
log = pyrpkg.log
client.setupLogging(log)

if client.args.v:
    log.setLevel(logging.DEBUG)
elif client.args.q:
    log.setLevel(logging.WARNING)
else:
    log.setLevel(logging.INFO)

try:
    client.args.command()
except Exception as e:
    if client.args.v:
        raise
    else:
        log.error(str(e))
except KeyboardInterrupt:
    pass
