#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import os
#   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
import subprocess
import requests

try:
    from fuglu.connectors.check import check_fuglu_netcat, check_fuglu_smtp, check_fuglu_asmilter
    from fuglu.stringencode import force_uString
except Exception:
    pass


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("-w", "--wtimeout", default=4.0, help="Workerlist timeout for check", type=float)
    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"])
    parser.add_argument("-m", "--matrix", default=False, help="Send workerlist to matrix on error", action="store_true")
    parser.add_argument("--feature-env-key-skip", default=None, help="feature environment key - if enabled skip healthcheck")

    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)

    try:
        if opt.feature_env_key_skip and opt.feature_env_key_skip != "none":
            res = requests.get(url="https://features.seppmail.io/api/v1/flags/", headers={"x-environment-key": opt.feature_env_key_skip}, timeout=1)
            data = res.json()
            if data[0]["enabled"]:
                if opt.zabbix:
                    # zabbix -> output return value as string
                    print(0)
                    sys.exit(0)
                else:
                    print("Skip healthcheck on feature env request...")
                    sys.exit(0)
    except Exception:
        pass

    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

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

    logger.info(msg)

    cmdout = "No workerlist extracted..."
    if returnval:
        # try to get workerlist
        try:
            process = subprocess.Popen(['/fuglu/tools/fuglu_control', ' workerlist'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            outputraw = process.communicate(timeout=opt.timeout)
            process.stdout.close()
            process.wait()

            cmdout = force_uString(outputraw[0])
        except Exception as e:
            typestring = str(type(e)).replace("<", "").replace(">", "")
            cmdout = f"Got exception: ({typestring}) {str(e)}"

        # send to matrix
        if opt.matrix and os.path.exists("/tmp/fuglu_control.sock"):
            # create matrix msg
            node = os.getenv("SWARM_NODE")
            if not node:
                node = os.getenv("Node_Hostname")
            if not node:
                node = os.getenv("Hostname")

            msg_plain = f"Fuglu Healthcheck({node}):\n{msg}\n"
            msg_html = f"<b>Fuglu Healthcheck({node}):</b><br>{msg}<br>" \

            msg_plain += cmdout
            msg_html += f"<pre><code>{cmdout}</code></pre>"

            if returnval:
                level = "error"
            else:
                level = "info"

            body = {
                "level": level,
                "plain": msg_plain,
                "html": msg_html
            }
            res = requests.post(url="http://zabbix.seppmail.io:8571/general/%21zKkqRoPCUrApRjEfhA%3Aseppmail.io",
                                json=body,
                                verify=False,
                                )
            if res.status_code != 200:
                print(f"Error posting success message to matrix: {res.status_code}\n{res.json()}")


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