#!/usr/bin/python3

import os
import sys

from optparse import OptionParser
from checkbox.lib.fifo import FifoReader, FifoWriter

from checkbox.job import Job, FAIL


def main(args):
    usage = "Usage: %prog INPUT OUTPUT"
    parser = OptionParser(usage=usage)
    parser.add_option("-p", "--path",
        help="PATH variable to replace in the environment")
    (options, args) = parser.parse_args(args)

    if len(args) < 2:
        parser.error("Missing INPUT and OUTPUT")

    # Set PATH
    if options.path:
        os.environ["PATH"] = options.path

    # Set PYTHONPATH
    pythonpath = sys.path[0]
    if "PYTHONPATH" in os.environ:
        pythonpath = ":".join([pythonpath, os.environ["PYTHONPATH"]])
    os.environ["PYTHONPATH"] = pythonpath

    reader = FifoReader(args[0])
    writer = FifoWriter(args[1])

    while True:
        try:
            message = reader.read_object()
            #"unpack" the message
            sequence, message = message
            if message == "stop":
                break
            if message == "ping":
                #Build a tuple with the sequence number as
                #received
                writer.write_object((sequence, "pong",))
                continue
            if isinstance(message, dict) and "command" in message:
                job = Job(message["command"], message.get("environ"),
                    message.get("timeout"))
                status, data, duration = job.execute()
                try:
                    data = data.decode("utf-8")
                except UnicodeDecodeError:
                    status, data, duration = (FAIL, "Decode error", 0,)
            else:
                status, data, duration = (FAIL, "", 0,)
            #Build a tuple with sequence number
            writer.write_object((sequence, (status, data, duration,),))
        except IOError:
            break

    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
