#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

#   Copyright Fumail Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


# This tool is used to run fuglu health checks for connectors from the command line

import sys
import argparse
import logging
import time

from fuglu.connectors.check import check_fuglu_netcat, check_fuglu_smtp, check_fuglu_asmilter


def _fail(*args, **kwargs):
    return 1


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--connector", default="smtp", help="Connector to check",
                        choices=["smtp", "netcat", "asmilter"], required=True)
    parser.add_argument("--host", default="localhost", help="host where fuglu daemon is running")
    parser.add_argument("-p", "--port", type=int, default=10125, help="port on which the netcat connector is listening")
    parser.add_argument("-t", "--timeout", default=5, help="Socket timeout for check", type=int)
    parser.add_argument("-z", "--zabbix", default=False, help="Zabbix check mode", action="store_true")
    parser.add_argument("-l", "--level", default="INFO", help="Log level", choices=["INFO", "DEBUG", "CRITICAL", "ERROR"])

    opt = parser.parse_args()

    if opt.zabbix:
        logging.basicConfig(level=logging.CRITICAL)
    else:
        if opt.level == "DEBUG":
            logging.basicConfig(level=logging.DEBUG)
        elif opt.level == "ERROR":
            logging.basicConfig(level=logging.ERROR)
        elif opt.level == "CRITICAL":
            logging.basicConfig(level=logging.CRITICAL)
        else:
            logging.basicConfig(level=logging.INFO)

    logger = logging.getLogger()
    logger.debug(f"Health check ({opt.connector}, {opt.timeout}s) -> {opt.host}:{opt.port}")

    tests = {
        "smtp": check_fuglu_smtp,
        "netcat": check_fuglu_netcat,
        "asmilter": check_fuglu_asmilter
    }
    ts = time.time()
    returnval = tests.get(opt.connector, _fail)(host=opt.host, port=opt.port, timeout=opt.timeout)
    te = time.time()
    dt = te - ts

    logger.info(f"Health check ({opt.connector}, {opt.timeout}s) -> {opt.host}:{opt.port} "
                f"-> return: {returnval} in {dt:.2f}s")

    if opt.zabbix:
        # zabbix -> output return value as string
        print(returnval)
        sys.exit(0)
    else:
        sys.exit(returnval)
