#!/usr/bin/env python

from __future__ import print_function

import os
import signal
import subprocess
import sys
import time
from datetime import datetime

WORKER = "/usr/local/bin/log2db-worker"
SOURCES = ("firewall", "messages", "suricata", "squid", "urlfilter")
INTERVAL = 60
MAINTENANCE_INTERVAL = 300
LOG_FILE = "/var/log/log2db/log2db.log"

running = True
workers = {}


def log(message):
    try:
        log_dir = os.path.dirname(LOG_FILE)
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        with open(LOG_FILE, "a") as log_file:
            log_file.write("[%s] [INFO] %s\n" % (
                datetime.now().strftime("%Y-%m-%d %H:%M:%S"), message))
    except IOError:
        pass


def stop(signum, frame):
    global running
    running = False
    for process in workers.values():
        if process.poll() is None:
            process.terminate()


def run_group(maintenance=False):
    global workers
    workers = {}
    try:
        cpu_count = os.cpu_count() if hasattr(os, "cpu_count") else 1
        threads = max(1, (cpu_count // 2) // len(SOURCES))
        environment = os.environ.copy()
        environment["LOG2DB_THREADS"] = str(threads)

        for source in SOURCES:
            command = [WORKER, source]
            if maintenance:
                command.append("--maintenance")
            workers[source] = subprocess.Popen(command, env=environment)

        while running and any(process.poll() is None for process in workers.values()):
            time.sleep(1)

        for source, process in workers.items():
            returncode = process.wait()
            if running and returncode != 0:
                operation = "maintenance" if maintenance else "ingestion"
                log("%s %s worker exited with status %d." % (
                    source.capitalize(), operation, returncode))
    except Exception as error:
        log("Unable to execute log2db workers: %s" % error)
    finally:
        for process in workers.values():
            if process.poll() is None:
                process.wait()
        workers = {}


signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)

log("log2db daemon started; independent ingestion every %d seconds and maintenance every %d seconds." % (
    INTERVAL, MAINTENANCE_INTERVAL))
last_maintenance = 0

while running:
    started = time.time()
    run_group(maintenance=False)

    if running and started - last_maintenance >= MAINTENANCE_INTERVAL:
        run_group(maintenance=True)
        last_maintenance = time.time()

    remaining = INTERVAL - (time.time() - started)
    while running and remaining > 0:
        time.sleep(min(1, remaining))
        remaining = INTERVAL - (time.time() - started)

log("log2db daemon stopped.")
sys.exit(0)
