#!/bin/bash

set -e

TOP_DIR=`pwd`

# figure out where Pegasus is installed
export PEGASUS_BIN_DIR=`pegasus-config --bin`
if [ "x$PEGASUS_BIN_DIR" = "x" ]; then
    echo "Please make sure pegasus-plan is in your path"
    exit 1
fi 

# build the dax generator
export PYTHONPATH=.:`pegasus-config --python`
./blackdiamond.py $PEGASUS_BIN_DIR/.. a > one.dax
./blackdiamond.py $PEGASUS_BIN_DIR/.. d > two.dax

./super.py > super-blackdiamond.dax

echo "f.a" > f.a

# site catalog
cat >sites.xml <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<sitecatalog xmlns="http://pegasus.isi.edu/schema/sitecatalog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pegasus.isi.edu/schema/sitecatalog http://pegasus.isi.edu/schema/sc-4.0.xsd" version="4.0">
    <site  handle="local" arch="x86" os="LINUX">
        <directory type="shared-scratch" path="/nfs/ccg4/scratch-purge-no-backups/http-scratch/bamboo">
            <file-server operation="get" url="http://obelix.isi.edu/shared-scratch/bamboo"/>
            <file-server operation="put" url="file:///nfs/ccg4/scratch-purge-no-backups/http-scratch/bamboo"/>
        </directory>
        <directory type="local-storage" path="$TOP_DIR/outputs">
            <file-server operation="all" url="file://$TOP_DIR/outputs"/>
        </directory>
        <profile namespace="env" key="PEGASUS_BIN_DIR">$PEGASUS_BIN_DIR</profile>
    </site>
    <site  handle="condor_pool" arch="x86" os="LINUX">
        <profile namespace="pegasus" key="style">condor</profile>
        <profile namespace="condor" key="universe">vanilla</profile>
    </site>
</sitecatalog>
EOF

echo
echo
echo "The site catalog is:"
cat sites.xml

echo
echo
echo "Planning and submitting the workflow..."
pegasus-plan \
    --conf pegasusrc \
    --dir work \
    --dax super-blackdiamond.dax \
    --sites condor_pool \
    --staging-site local \
    --output-site local \
    --submit | tee $TOP_DIR/plan.out


WORK_DIR=`cat plan.out | grep pegasus-remove | sed -E 's/.*pegasus-remove[ ]+//'`
cd $WORK_DIR

while :
do
	sleep 1
	
	if [ -e "diamond-a_ID0000001/diamond-a-0.cache" ]; then
		set +e
		grep -v -P "diamond-.*-4\.0" diamond-a_ID0000001/diamond-a-0.cache | grep -v "http://" 
		EC=$?
		set -e

		if [ $EC -eq 0 ]; then
			echo "Cache file contains non http URL's" 
			exit 1
		fi

		break
	fi
done

