#!/usr/bin/python3
#
# Copyright (C) 2020  Cercel Valentin-Adrian
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# mailcow-dockerized postfix stats
# please adjust librenms_poller_interval according to your LibreNMS setup - default to 5 minutes
# requirements: mailcow-dockerized and pflogsumm
#
# Note to users that struggle with the setup: Make sure, that your SNMP Daemon can use the docker command
# So please make sure, that the e.G. Debian-snmp user is added to the docker group!
#

import json
import re
import subprocess

# LibreNMS poller interval
librenms_poller_interval = 300


def libre_to_mcd_postfix(libre_seconds):
    return str(int(libre_seconds / 60))


def cli_get_docker_container():
    return (
        subprocess.check_output("docker ps -qf name=postfix-mailcow", shell=True)
        .decode("utf8")
        .strip()
    )


def cli_command():
    cli_part = (
        "docker logs --since "
        + libre_to_mcd_postfix(librenms_poller_interval)
        + "m "
        + cli_get_docker_container()
        + "| pflogsumm --smtpd-stats 2>&1 | grep -v 'Use of uninitialized value'"
    )
    return cli_part


def get_output():
    return subprocess.check_output(cli_command(), shell=True).decode("utf8")


def output_cleaning(input):
    output = re.split("\n", input)
    return list(filter(None, output))


def entry_generator(input):
    entry = re.sub("  +", ":", input.strip().lstrip())
    return entry.split(":")


# limit our needed output
mcd_postfix_data = get_output().split("messages")
data = mcd_postfix_data[1].split("smtpd")

# postfix stats only
mcd_postfix_info = data[0]
# smtpd stats only
mcd_smtpd_info = data[1].split("Per-Hour Traffic Summary")[0]

# postfix stats export
mcd_postfix = output_cleaning(mcd_postfix_info)

points_data = []
points_label = []
for entry in mcd_postfix:
    data_labels = entry_generator(entry)

    if data_labels[0].find("k") == -1:
        points_data.append(data_labels[0])
    else:
        data_point = data_labels[0].replace("k", "", 1)
        data_point = int(data_point) * 1024
        points_data.append(data_point)

    points_label.append(re.sub("[^a-zA-Z]+", "", data_labels[1]))

entries = dict(zip(points_label, points_data))
export = {"data": entries, "error": "0", "errorString": "", "version": "1"}
data = re.sub(" ", "", json.dumps(export))
print(data)
