#!/usr/bin/env python3
# Kamina - The />p/ social network
# Copyright (C) 2018, The Kamina Project
#
# 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.

"""
app.py - the command-line driver for Kamina.
This module parses command-line options, arguments, flags, and sub-commands.
It also instantiates a logger, deals with POSIX signals, loads JSON config
files, invokes the daemon process for a Kamina instance, and populates the
attributes of internal classes.
"""

import os
import sys
import logging
import logging.config
import logging.handlers
import importlib

import click

from kamina.process import KaminaProcess
from kamina.config import KaminaConfiguration

# I have a low opinion of sigils, so function decorators have always looked
# like pythonic cancer.  Despite that, I've gotta admit the Click framework
# makes writing these cli apps insanely easy, so... I'll roll with it.


@click.group(context_settings=dict(help_option_names=["-h", "--help"]))
@click.version_option(version=0.1, prog_name="Kamina Community")
@click.option("--debug", default=False, is_flag=True,
              help="Show all log messages, must be before any command.")
@click.option("--verbose", default=False, is_flag=True,
              help="Same as --debug, but with a plus, must be before any command.")
@click.option("--log", "-l", default=None, type=click.Path(),
              help="Redirect logging location.")
@click.option("--config-dir", "-c", default=os.path.dirname(os.path.abspath(__file__)),
              type=click.Path(exists=True),
              help="Specify alternate configuration directory.")
@click.pass_context
def main(ctx, verbose, debug, log, config_dir) -> None:
    """The Kamina service utility"""
    kamina_conf = KaminaConfiguration(config_dir)
    conf = kamina_conf.conf
    logger = logging.getLogger("kamina")
    handlers = []

    # If you specified an alternate log location on the command-line, use that.
    # Otherwise, use syslog, so we at least have that, even if the config file
    # didn't specify any logging info.
    if log:
        handlers.append(logging.FileHandler(log))
    else:
        # Make sure we're not setting up two syslog handlers
        if not logger.handlers:
            handlers.append(logging.handlers.SysLogHandler(address="/dev/log"))

    if verbose:
        conf["troubleshoot"]["verbose"] = True
        logger.setLevel(logging.DEBUG)

    if debug:
        logger.setLevel(logging.DEBUG)

    if not logger.handlers:  # Only add handlers if logger is not configured
        for handle in handlers:
            logger.addHandler(handle)

    # Now, propogate the context for our sub-commands
    ctx.obj = {"CONF": conf, "LOG": logger}

    # Give value to our globals
    kamina_process = KaminaProcess(conf)
    if not conf["storage"]["ipfs"]["enable"]:
        cli_commands = importlib.import_module("core.non-ipfs.cli_commands").CliCommands(kamina_process)
    else:
        cli_commands = importlib.import_module("core.ipfs.cli_commands").CliCommands(kamina_process)

    # Add variable to global ctx object
    ctx.obj["CLI_COMMANDS"] = cli_commands
    ctx.obj["KAMINA_PROCESS"] = kamina_process


@main.command()
@click.option("--install-ipfs", is_flag=True, help="Install ipfs locally.")
@click.pass_context
def init(ctx, install_ipfs) -> None:
    """Setup a new community node."""
    logger = ctx.obj["LOG"]
    conf = ctx.obj["CONF"]
    cli_commands = ctx.obj["CLI_COMMANDS"]

    if not logger or not conf:
        print("Error: no valid conf or logger passed. Exiting.")
        sys.exit(1)

    cli_commands.init(install_ipfs)


@main.command()
@click.pass_context
def daemon(ctx) -> None:
    """Initialize kamina's community daemon."""
    cli_commands = ctx.obj["CLI_COMMANDS"]
    cli_commands.daemon()


if __name__ == "__main__":
    main()
