#!/usr/bin/env python

###############################################################################
# (c) Copyright 2016 CERN                                                     #
#                                                                             #
# This software is distributed under the terms of the GNU General Public      #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".   #
#                                                                             #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization  #
# or submit itself to any jurisdiction.                                       #
###############################################################################
'''
Command line client that interfaces to the Installer class

:author: Stefan-Gabriel CHITIC
'''
from __future__ import print_function
import logging
import optparse
import os
import sys

from lbciagent.LbCIAgent import LbCIAgent


class lbciagentOptionParser(optparse.OptionParser):
    """ Custom OptionParser to intercept the errors and rethrow
    them as lbciagentExceptions """

    def error(self, msg):
        """
        Arguments parsing error message exception handler

        :param msg: the message of the exception
        :return: Raises lbciagentException with the
         exception message
        """
        raise Exception("Error parsing arguments: " + str(msg))

    def exit(self, status=0, msg=None):
        """
        Arguments parsing error message exception handler

        :param status: the status of the application
        :param msg: the message of the exception
        :return: Raises lbciagentException with the
        exception message
        """
        raise Exception("Error parsing arguments: " + str(msg))


class lbciagentClient(object):
    """ Main class for the tool """

    def __init__(self, arguments=None, prog="lbciagent"):
        """ Common setup for both clients """
        self.log = logging.getLogger(__name__)
        self.arguments = arguments
        self.prog = prog
        self.test = False
        parser = lbciagentOptionParser(usage=usage(self.prog))
        parser.disable_interspersed_args()
        parser.add_option('-d', '--debug',
                          dest="debug",
                          default=False,
                          action="store_true",
                          help="Show debug information")

        self.parser = parser

    def main(self):
        """ Main method for the ancestor:
        call parse and run in sequence

        :returns: the return code of the call
        """

        rc = 0
        try:
            opts, args = self.parser.parse_args(self.arguments)
            if opts.debug:
                logging.getLogger().setLevel(logging.DEBUG)

            self.run(opts, args)
        except Exception as lie:
            print("ERROR: " + str(lie), file=sys.stderr)
            self.parser.print_help()
            rc = 1
        return rc

    def run(self, opts, args):
        """ Main method for the command

        :param opts: The option list
        :param args: The arguments list
        """
        # Parsing first argument to check the mode
        manager = LbCIAgent()
        # Now executing the command
        manager.start()


# Usage for the script
###############################################################################
def usage(cmd):
    """ Prints out how to use the script...

    :param cmd: the command executed
    """
    cmd = os.path.basename(cmd)
    return """\n%(cmd)s - runs CVMFS lbciagent for nightlies messages""" % {
        "cmd": cmd}


def lbciagent(prog="lbciagent"):
    """
    Default caller for command line lbciagent client
    :param prog: the name of the executable
    """
    logging.basicConfig(format="%(levelname)-8s: %(message)s")
    logging.getLogger().setLevel(logging.WARNING)
    sys.exit(lbciagentClient(prog=prog).main())

# Main just chooses the client and starts it
if __name__ == "__main__":
    lbciagent()
