#!/usr/bin/env python

import sys
import os
import signal
import logging

import tankapi.server_defaults as server_defaults
from tankapi.server import detect_ipv6, add_file_handler_to_logger, start_lunapark_api_server, Daemon
from optparse import OptionParser


logger = logging.getLogger('tankapi')


def get_parameters():
    sys.path.append('/usr/share/tankapi')
    parser = OptionParser()
    parser.add_option('--host',
                      type='string',
                      action='store',
                      default=server_defaults.host,
                      help='Specify host for API server')
    parser.add_option('-p',
                      '--port',
                      type='int',
                      action='store',
                      default=server_defaults.port,
                      help='Port for tank API server.')
    parser.add_option('-w',
                      '--workdir',
                      type='string',
                      action='store',
                      default=server_defaults.workdir,
                      help='Path to tank API server workdir.')
    parser.add_option('-d',
                      '--daemonize',
                      action='store_true',
                      default=server_defaults.daemonize,
                      help='Run tank API server in background')

    parser.add_option('-6',
                      '--ipv6',
                      action='store_true',
                      default=server_defaults.ipv6,
                      help='use ipv6?')

    parser.add_option('-l',
                      '--lock-dir',
                      action='store',
                      default=server_defaults.lock_dir,
                      help='Directory to store lock file')

    script_options = parser.parse_args()[0]

    return (script_options.host, script_options.port, script_options.workdir,
            script_options.daemonize, script_options.ipv6, script_options.lock_dir)


def init_logger():
    """
        Initial logger setup
        Set logging level for stdout
    """
    logger.setLevel(logging.DEBUG)

    fmt_verbose = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s %(filename)s:%(lineno)d\t%(message)s")
    stderr_hdl = logging.StreamHandler(sys.stderr)
    stderr_hdl.setFormatter(fmt_verbose)
    stderr_hdl.setLevel(logging.WARN)

    logger.addHandler(stderr_hdl)

    logging.info("Logging stream done")
    logging.debug("Debug msg 0")


def main():
    init_logger()
    host, port, workdir, daemonize, ipv6, lock_dir = get_parameters()
    if not ipv6:
        ipv6 = detect_ipv6()

    signal.signal(signal.SIGINT, signal.SIG_DFL)
    if daemonize:
        pidfile_name = os.path.join(workdir, 'tank_api_server.pid')
        d = Daemon(pidfile_name)
        d.daemonize(workdir)
    log_file_path = os.path.join(workdir, 'server.log')
    add_file_handler_to_logger(log_file_path)
    tests_dir = os.path.join(workdir, 'tests')
    if not os.path.exists(tests_dir):
        logger.info("Tests folder does not exist. Trying to create it. Path: %s" % tests_dir)
        os.makedirs(tests_dir)
    start_lunapark_api_server(host, port, ipv6, tests_dir, lock_dir)


if __name__ == "__main__":
    main()
