#!/usr/bin/python

import subprocess
import sys
import os
from os import path
import platform
import datetime

dir = sys.argv[1]

with open(path.join(dir, "command")) as f:
    wccl_cmd = f.readline().strip()

result_file = open(path.join(dir, "results"), "w")
log_file = open(path.join(dir, "log"), "w")

log_file.write("hostname: %s\n" % platform.node())
log_file.write("%s\n" % str(datetime.datetime.now()))
log_file.write("=== stderr log ===\n")


r_p, w_p = os.pipe()
r_f = os.fdopen(r_p, "r")
w_f = os.fdopen(w_p, "w")

wccl = subprocess.Popen(wccl_cmd.split(), stdout = subprocess.PIPE, stderr = w_f,
  close_fds = True)
triple_filter = subprocess.Popen(["python", "triple_filter.py"], stdin = wccl.stdout,
  stdout = result_file, stderr = w_f, close_fds = True)
w_f.close()

errs = r_f.readlines()

wccl.wait()
triple_filter.wait()

for l in errs:
    log_file.write(l)

log_file.write("=== stderr end ===\n")
log_file.write("%s\n" % str(datetime.datetime.now()))
log_file.write("STATUS %d %d\n" % (wccl.returncode, triple_filter.returncode))

result_file.close()
log_file.close()
