#!/usr/bin/python3
#
# Copyright (c) 2013--2016 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.
#

import os
import sys

import gettext
t = gettext.translation('spacewalk-abrt', fallback=True)

if sys.version_info[0] == 3:
    _ = t.gettext
else:
    _ = t.ugettext

from optparse import OptionGroup
from up2date_client import rhncli
from up2date_client import up2dateAuth
import spacewalk_abrt.abrt

class AbrtCli(rhncli.RhnCli):
    def __init__(self):
        super(AbrtCli, self).__init__()

        group = OptionGroup(self.optparser, "Commands", "Specify one of the commands below")
        group.add_option("--report", action="store",
            help=_("Upload content of the specified problem directory")),
        group.add_option("--update-count", action="store",
            help=_("Update crash count for the specified problem directory")),
        group.add_option("--sync", action="store_true",
            help=_("Synchronize missing problem directories")),
        self.optparser.add_option_group(group)

    def check_problem_dir(self, path):
        if not os.path.exists(path):
            sys.stderr.write(rhncli.utf8_encode(_("Error: specified problem directory [%s] does not exist.\n" % path)))
            sys.exit(1)

    def main(self):
        if not (self.options.report or self.options.update_count or self.options.sync):
            print(_("No command specified. Use --help for more information on the usage."))
            sys.exit(1)

        commands = 0
        for command in [self.options.report, self.options.update_count, self.options.sync]:
            if command:
                commands += 1

        if commands > 1:
            print(_("More than one command specified. Use --help for more information on the usage."))

        if not up2dateAuth.getSystemId():
            print(_("This system does not seem to be registered, use `rhn_register` before using this command."))
            sys.exit(0)

        if self.options.report:
            self.check_problem_dir(self.options.report)
            spacewalk_abrt.abrt.report(self.options.report)

        if self.options.update_count:
            self.check_problem_dir(self.options.update_count)
            spacewalk_abrt.abrt.update_count(self.options.update_count)

        if self.options.sync:
            spacewalk_abrt.abrt.sync()

        sys.exit(0)


if __name__ == '__main__':
    cli = AbrtCli()
    cli.run()
