#!/usr/bin/env python
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Author: "Chris Ward <cward@redhat.com>

'''
metrique-server.py contains a CLI for metrique server.

    It is possible to start, stop, restart and request
    current running status for metriqued

    # ... ^^^ cube class definition above ^^^ ...
    if __name__ == '__main__':
        from metrique.argparsers import cube_cli
        obj, args = cube_cli(Bug)
        obj.extract(force=args.force)

'''

import os
import sys

from metriqued.config import metriqued_config
from metriqued.tornadohttp import TornadoHTTPServer
from metriqued.utils import get_pids


def stop(args):
    for pid in args.pids:
        print "Sending signal (%s) to (%s)" % (args.signal, pid)
        os.kill(pid, args.signal)


def start(args):
    if not args.instances:
        args.instances = 1
    # A) there are no instances currently running
    # B) there are instances running; add additional
    args.port = args.port + running_k
    pids = []
    for k in range(args.instances):
        pid = os.fork()
        if pid == 0:
            _start(args)
        else:
            pids.append(pid)
        args.port += 1
    print 'Started: %s' % ', '.join(map(str, pids))


def _start(args):
    host = args.host
    port = args.port
    debug = args.debug
    metriqued = TornadoHTTPServer(host=host, port=port, debug=debug)
    metriqued.start()
    sys.exit()


if __name__ == '__main__':
    import argparse
    _args = argparse.ArgumentParser(description='metrique server CLI')

    __cmds__ = ['start', 'stop', 'restart', 'status']
    _args.add_argument('command', type=str, choices=__cmds__)
    _args.add_argument('-d', '--debug', type=int, default=True)
    _args.add_argument('-c', '--server-config-file', type=str)
    _args.add_argument('-H', '--host', type=str)
    _args.add_argument('-P', '--port', type=int)
    _args.add_argument('-i', '--instances', type=int)
    _args.add_argument('-p', '--pid-dir', type=str)
    _args.add_argument('-ps', '--pids', nargs='+', type=int)
    # 2 = SIGINT; 15 = SIGTERM
    _args.add_argument('-s', '--signal', type=int, choices=[2, 9, 15],
                       default=2)

    # parse sys.argv
    args = _args.parse_args()

    server_config_file = args.server_config_file
    mconf = metriqued_config(config_file=server_config_file)

    # shorten varnames
    cmd = args.command

    args.debug = args.debug
    args.host = args.host or mconf.host
    args.port = args.port or mconf.port
    args.pid_dir = args.pid_dir or mconf.piddir
    args.pid_dir = os.path.expanduser(args.pid_dir)

    running = get_pids(args.pid_dir)
    running_k = len(running)

    args.pids = args.pids or running

    if cmd == 'start':
        start(args)
    elif cmd == 'stop':
        stop(args)
    elif cmd == 'restart':
        stop(args)
        args.cmd = 'start'
        args.instances = args.instances or running_k
        start(args)
    elif cmd == 'status':
        print 'RUNNING: %s' % ', '.join(map(str, get_pids(args.pid_dir)))
    else:
        raise SystemExit('bad command "%s"... Try --help' % cmd)
