#!/usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFW UTM Community - ntopng service manager

import os
import sys
import subprocess
import time

CONF = "/etc/ntopng/ntopng.conf"
SETTINGS = "/var/efw/ntopng/settings"
MONIT_DIR = "/etc/monit.d"
MONIT_FILE = os.path.join(MONIT_DIR, "ntopng.conf")
FIREWALL_FILE = "/etc/firewall/inputfw/ntopng.conf"
CRON_FILE = "/etc/cron.d/ntopng"

CRON_CONTENT = """# /etc/cron.d/ntopng: crontab fragment for ntopng
# This is used to handle software updates.

# Check for updates or upgrade if requested (every minute)
* * * * * root /usr/bin/ntopng-utils-manage-updates -a handle-on-demand-requests

# Check for updates (every 24h at 6am)
0 6 * * * root /usr/bin/ntopng-utils-manage-updates -a check-updates
"""

REDIS_MONIT_FILE = os.path.join(MONIT_DIR, "redis.conf")


def run(command):
    """Run a shell command and return its exit code."""
    return subprocess.call(command, shell=True)


def monitor_service(service):
    """Wait until monit confirms that monitoring is enabled."""
    for _ in range(60):
        run("monit monitor %s 2>/dev/null" % service)
        process = subprocess.Popen(
            ["monit", "status", service],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT
        )
        status = process.communicate()[0]
        states = [" ".join(line.split()) for line in status.splitlines()]
        if ("monitoring status monitored" in states or
                "monitoring status initializing" in states):
            return
        time.sleep(1)
    print >> sys.stderr, "Unable to enable monit monitoring for %s" % service


def read_settings(path):
    """Read key=value pairs from the ntopng settings file."""
    settings = {}
    if not os.path.exists(path):
        return settings
    with open(path, "r") as handle:
        for raw_line in handle:
            line = raw_line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, value = line.split("=", 1)
            settings[key.strip()] = value.strip().strip("\"'")
    return settings








def configure_monit_redis(mode):
    """Enable or disable redis monitoring in monit."""
    run("monit unmonitor redis 2>/dev/null")

    if mode == "disable":
        if os.path.exists(REDIS_MONIT_FILE):
            os.remove(REDIS_MONIT_FILE)
        run("monit reload")
        return

    content = """check process redis with pidfile /var/run/redis.pid
   start program = "/etc/init.d/redis start"
   stop program  = "/etc/init.d/redis stop"
   if failed host 127.0.0.1 port 6379 then restart
   if 5 restarts within 5 cycles then timeout
"""
    with open(REDIS_MONIT_FILE, "w") as handle:
        handle.write(content)

    run("monit reload")


def configure_monit_ntopng(mode):
    """Enable or disable ntopng monitoring in monit."""
    print "Configuring monit for ntopng..."
    run("monit unmonitor ntopng 2>/dev/null")

    if mode == "disable":
        if os.path.exists(MONIT_FILE):
            os.remove(MONIT_FILE)
        run("monit reload")
        return

    content = """check process ntopng with pidfile /var/run/ntopng/ntopng.pid
   start program = "/etc/init.d/ntopng start"
   stop program  = "/etc/init.d/ntopng stop"
   if failed port 3000 protocol http then restart
   if 5 restarts within 5 cycles then timeout
"""
    with open(MONIT_FILE, "w") as handle:
        handle.write(content)

    run("monit reload")


def configure_cron(mode):
    """Enable or disable the ntopng cron fragment and restart fcron."""
    if mode == "disable":
        if os.path.exists(CRON_FILE):
            os.remove(CRON_FILE)
    else:
        with open(CRON_FILE, "w") as handle:
            handle.write(CRON_CONTENT)

    run("/etc/init.d/fcron restart >/dev/null 2>&1")



def redis_running():
    """Check whether the redis service is currently running."""
    pidfile = '/var/run/redis.pid'
    if not os.path.exists(pidfile):
        return False
    try:
        with open(pidfile, 'r') as handle:
            pid = int(handle.read().strip())
    except (ValueError, IOError):
        return False
    if pid <= 0:
        return False
    return os.path.exists('/proc/%d' % pid)


def main():
    if not os.path.exists(SETTINGS):
        print >> sys.stderr, "Settings file not found: %s" % SETTINGS
        sys.exit(1)

    os.makedirs("/var/run/ntopng", 0755) if not os.path.exists("/var/run/ntopng") else None
    os.makedirs("/etc/firewall/inputfw", 0755) if not os.path.exists("/etc/firewall/inputfw") else None

    settings = read_settings(SETTINGS)
    ntopng_enable = settings.get("NTOPNG_ENABLE", "off")

    if ntopng_enable != "on":
        print "NtopNG service is disabled. The service will not be started."
        sys.stdout.flush()

    if ntopng_enable == "on":
        configure_monit_redis("enable")
        if not redis_running():
            run("/etc/init.d/redis start")
        for _ in range(5):
            if redis_running():
                break
            time.sleep(1)
            if not redis_running():
                run("/etc/init.d/redis start")

        configure_monit_ntopng("enable")
        monitor_service("redis")
        monitor_service("ntopng")

        # Allow access to the ntopng web interface
        with open(FIREWALL_FILE, "w") as handle:
            handle.write("tcp,,3000,on,,GREEN,off,Acess NTOP-NG,ACCEPT,,\n")
        run("/usr/local/bin/setxtaccess")

        configure_cron("enable")
    else:
        configure_monit_redis("disable")
        configure_monit_ntopng("disable")
        run("/etc/init.d/ntopng stop 2>/dev/null")

        # Remove firewall access if present
        if os.path.exists(FIREWALL_FILE):
            os.remove(FIREWALL_FILE)
        run("/usr/local/bin/setxtaccess")

        run("/etc/init.d/redis stop 2>/dev/null")
        configure_cron("disable")
        sys.exit(0)

    # Generate ntopng configuration
    interfaces = [item.strip() for item in settings.get("INTERFACES", "").split(",")]

    with open(CONF, "w") as handle:
        handle.write("-G=/var/run/ntopng/ntopng.pid\n")
        handle.write("-d=/var/lib/ntopng\n")

        for interface in interfaces:
            if interface:
                handle.write("-i=%s\n" % interface)

        handle.write("-m=10.0.0.0/8,192.168.0.0/16,172.16.0.0/12\n")
        handle.write("-n=1\n")
        handle.write("--redis=127.0.0.1:6379\n")
        handle.write("--max-num-flows=500000\n")
        handle.write("--max-num-hosts=200000\n")
        handle.write("-w=3000\n")

    # Restart ntopng service
    if run("/etc/init.d/ntopng restart >/dev/null 2>&1") != 0:
        print >> sys.stderr, "Error restarting ntopng!"
        sys.exit(1)


if __name__ == "__main__":
    main()
