#!/usr/bin/python3 -d
"""
This file is part of Linspector (https://linspector.org/)
Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import argparse
import logging
import logging.handlers
import os
import sys

from linspector.core.configuration import Configuration
from linspector.core.environment import Environment
from linspector.core.linspector import Linspector
from linspector.core.monitors import Monitors

__version__ = '0.19.11.dev1'
__author__ = 'Johannes Findeisen <you@hanez.org>'

logger = logging.getLogger('linspector')


def parse_args():
    parser = argparse.ArgumentParser(
        description='linspector is a infrastructure monitoring daemon and toolchain.',
        epilog='author: ' + __author__,
        prog='linspector')

    parser.add_argument('configuration_path', metavar='CONFIGURATION_PATH',
                        help='the configuration path to use')

    parser.add_argument('-d', '--daemon', default=False, dest='daemon', action='store_true',
                        help='run linspector as native daemon (default: false)')

    parser.add_argument('-k', '--kill', default=False, dest='kill', action='store_true',
                        help='kill the daemon if it is running (default: false)')

    parser.add_argument('-r', '--restart', default=False, dest='restart', action='store_true',
                        help='restart the daemon if it is running(default: false)')

    parser.add_argument('-s', '--stdout', default=False, dest='stdout', action='store_true',
                        help='log to stdout')

    parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + str(__version__))

    return parser.parse_args()


def main():
    args = parse_args()
    environment = Environment()
    monitors = None
    notifications = {}
    plugins = {}
    scheduler = {}
    services = {}
    tasks = {}

    if args.stdout:
        # setting pre initialization default log level to INFO. this changes after initialization
        # of the configuration. maybe there are better solutions...?
        logger.setLevel(logging.INFO)
        stdout_formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s')
        stdout_handler = logging.StreamHandler(sys.stdout)
        stdout_handler.setFormatter(stdout_formatter)
        logger.addHandler(stdout_handler)

    try:
        configuration = Configuration(args.configuration_path, environment)
        #configuration.dump_to_ini()
    except Exception as err:
        logger.critical('[linspector] configuration error: {0}'.format(err))
        sys.exit(1)

    if configuration.get_option('linspector', 'log_file'):
        log_file = os.path.expanduser(configuration.get_option('linspector', 'log_file'))
        if not os.path.exists(os.path.dirname(log_file)):
            os.makedirs(os.path.dirname(log_file))

        log_file_formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
        log_file_handler = logging.handlers.RotatingFileHandler(log_file,
                                                                maxBytes=int(
                                                                    configuration.get_option(
                                                                        'linspector', 'log_size')),
                                                                backupCount=int(
                                                                    configuration.get_option(
                                                                        'linspector', 'log_count')))
        log_file_handler.setFormatter(log_file_formatter)
        logger.addHandler(log_file_handler)

    # critical errors will always show up even when no log_level is set. this is most silent.
    logger.setLevel(logging.CRITICAL)
    log_level = configuration.get_option('linspector', 'log_level')
    if log_level == "error":
        logger.setLevel(logging.ERROR)
    elif log_level == "warning":
        logger.setLevel(logging.WARNING)
    elif log_level == "info":
        logger.setLevel(logging.INFO)
    elif log_level == "debug":
        logger.setLevel(logging.DEBUG)

    try:
        monitors = Monitors(configuration, environment, notifications, services, tasks)
    except Exception as err:
        logger.warning('[linspector] monitor initialization error: {0}'.format(err))

    try:
        linspector = Linspector(configuration, environment, monitors, plugins, scheduler)
        #linspector.print_debug()
    except Exception as err:
        logger.critical('[linspector] core initialization error: {0}'.format(err))
        sys.exit(1)

    # daemon initialization
    if args.daemon:
        try:
            from linspector.core.linspectord import Linspectord
            linspectord = Linspectord(configuration, environment, linspector)
            # do handling of restart, start and stop commands but for now "start" is enough... ;)
            if args.kill:
                linspectord.stop()
            elif args.restart:
                linspectord.restart()
            else:
                linspectord.start()
        except Exception as err:
            logger.critical('[linspector] daemon error: {0}'.format(err))
            sys.exit(1)


if __name__ == '__main__':
    main()
