#!/usr/bin/env python

"""
Copyright (C) 2016-2019 Cumulus Networks, inc.

All Rights reserved.

This software is subject to the Cumulus Networks End User License Agreement available
at the following locations:

Internet: https://cumulusnetworks.com/downloads/eula/latest/view/

Cumulus Linux systems: /usr/share/cumulus/EULA.txt
"""

from daemon import DaemonContext
from nclu import WORKING_DIRECTORY, WORKING_DIRECTORY_PERMISSIONS
from nclu.NetDaemon import NetDaemon
import argparse
import logging
import os
import signal


def logger_init_syslog(log_debug):
    # Set the log level for the root logger.
    if log_debug:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    syslog_h = logging.handlers.SysLogHandler(address="/dev/log")
    formatter = logging.Formatter("netd: %(levelname)7s:  %(message)s")
    syslog_h.setFormatter(formatter)
    logging.getLogger().addHandler(syslog_h)

    # network_docopt DEBUG level is very chatty.  Hardcode it to INFO.
    network_docopt_logger = logging.getLogger("network_docopt")
    network_docopt_logger.setLevel(logging.INFO)
    network_docopt_logger.addHandler(syslog_h)


def logger_init_local(log_debug):
    if log_debug:
        logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)7s: %(message)s")
    else:
        logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)7s: %(message)s")

    # network_docopt DEBUG level is very chatty.  Hardcode it to INFO.
    logging.getLogger("network_docopt").setLevel(logging.INFO)

    # Color the errors and warnings in red.
    logging.addLevelName(logging.ERROR, "\033[91m  {0}\033[0m".format(logging.getLevelName(logging.ERROR)))
    logging.addLevelName(logging.WARNING, "\033[91m{0}\033[0m".format(logging.getLevelName(logging.WARNING)))


if os.path.isdir(WORKING_DIRECTORY):
    # The working directory already exists, but somebody could
    # have changed its permissions. Run chmod to be sure.
    os.chmod(WORKING_DIRECTORY, WORKING_DIRECTORY_PERMISSIONS)
else:
    try:
        os.makedirs(WORKING_DIRECTORY, mode=WORKING_DIRECTORY_PERMISSIONS)
    except OSError as e:
        exit(str(e))

parser = argparse.ArgumentParser(description="netd: daemon that listens to instances of \"net\"")
parser.add_argument("-d", "--daemon", help="run as a daemon", action="store_true")
parser.add_argument("--debug", help="log DEBUG messages", action="store_true")
parser_args = parser.parse_args()

try:
    # Initialize the root logger.
    if parser_args.daemon:
        logger_init_syslog(parser_args.debug)
    else:
        logger_init_local(parser_args.debug)
except Exception as e:
    # TODO - Catch specific exceptions.
    exit("Unable to set up logging:\n{0}\n".format(e))

netd = NetDaemon()

if parser_args.daemon:
    # Run netd in the background.
    # https://pypi.python.org/pypi/python-daemon/
    context = DaemonContext(
        working_directory=WORKING_DIRECTORY,
        signal_map={
            signal.SIGTERM: netd.signal_handler,
            signal.SIGINT: netd.signal_handler,
            signal.SIGHUP: netd.reload_handler,
        },
        umask=0o22
    )

    context.open()
    with context:
        netd.main()

else:
    # Run netd in the foreground.
    signal.signal(signal.SIGINT, netd.signal_handler)
    signal.signal(signal.SIGTERM, netd.signal_handler)
    signal.signal(signal.SIGHUP, netd.reload_handler)
    netd.main()
