#!/usr/bin/env python

import argparse
import logging
import signal
import sys
import yaml

from pgspawn import PipeGraphSpawner, Graph, GraphException


parser = argparse.ArgumentParser(description="Spawn graph of streaming commands.")
parser.add_argument("file", type=argparse.FileType('r'), help="file containing graph description")
parser.add_argument(
    "-l", "--log",
    dest='log', default=sys.stderr, type=argparse.FileType('w'),
    help="where to put logs, use something like /proc/self/fd/5 for logging to custom fd",
)
parser.add_argument(
    "-v", "--verbose",
    dest='verbose_count', action='count', default=0,
    help="increases log verbosity for each occurence",
)

if __name__ == '__main__':
    signal.signal(signal.SIGINT, lambda signal, frame: logging.debug("ignoring SIGINT"))

    arguments = parser.parse_args()

    # Sets log level to WARN going more verbose for each new -v.
    logging.basicConfig(
        format='%(process)d %(levelname)s: %(message)s',
        level=max(3 - arguments.verbose_count, 0) * 10,
        stream=arguments.log,
    )

    logging.debug("Hi, this is pgspawn speaking. Running with commandline {}.".format(sys.argv))

    logging.debug("Reading description.")
    description = yaml.load(arguments.file)
    arguments.file.close()

    logging.debug("Constructing and checking the graph.")
    try:
        g = Graph.from_dict(description)
    except GraphException as e:
        logging.error(str(e))
        sys.exit(1)

    logging.debug("Making pipes, spawning child processes. Sounds like fun...")
    pgs = PipeGraphSpawner.from_graph(g)
    pgs.close_fds()
    statusses = pgs.join()

    logging.debug("See ya. It was pgspawn speaking.")
    if len(statusses) == 0:
        sys.exit(0)
    else:
        sys.exit(max(statusses.values()))
