#!/usr/bin/env python

__author__ = "Rafael Ferreira da Silva"

import os
import shutil
import sys
from subprocess import Popen, PIPE, STDOUT

# configuration
work_dir = os.getcwd() + '/work'
dax = 'r-epa.dax'

# remove past runs
shutil.rmtree(work_dir, True)

# generating the workflow folder
print 'Generating workflow folder.'
p = Popen(
    ['pegasus-init', work_dir],
    stdin=PIPE,
    stdout=PIPE,
    stderr=PIPE)
p.stdin.write("y\n")
p.stdin.write("1\n")
p.stdin.write("5\n")
stdout, stderr = p.communicate()
exit_code = p.returncode
if exit_code != 0:
    # error
    print stdout
    print stderr
    exit(1)

# generating the workflow
print 'Generating workflow DAX.'
p = Popen(
    [work_dir + '/generate_dax.sh', dax],
    stdin=PIPE,
    stdout=sys.stdout,
    stderr=sys.stderr,
    cwd=r'%s' % work_dir)
p.stdin.write("\n")
stdout, stderr = p.communicate()
exit_code = p.returncode
if exit_code != 0:
    exit(1)

print 'Running the workflow.'
p = Popen(
    [work_dir + '/plan_dax.sh', dax],
    stdin=PIPE,
    stdout=sys.stdout,
    stderr=sys.stderr,
    cwd=r'%s' % work_dir)
stdout, stderr = p.communicate()
exit_code = p.returncode
if exit_code != 0:
    exit(1)
