#!/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 

export REMOTE_PEGASUS_HOME=/nfs/ccg4/scratch-purge-no-backups/bamboo/installs/pegasus-`pegasus-version`

# build the dax generator
export PYTHONPATH=`pegasus-config --python`
./blackdiamond.py $REMOTE_PEGASUS_HOME > blackdiamond.dax

# we need a f.a file to start
echo "Hello world!" >f.a

# empty replica catalog 
cat /dev/null >rc.data

# 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_64" os="LINUX" osrelease="deb" osversion="8">
        <directory type="shared-scratch" path="$TOP_DIR/scratch">
            <file-server operation="all" url="file://$TOP_DIR/scratch"/>
        </directory>
        <directory type="local-storage" path="$TOP_DIR/outputs">
            <file-server operation="all" url="file://$TOP_DIR/outputs"/>
        </directory>
        <profile namespace="env" key="PATH">$PEGASUS_BIN_DIR:/ccg/software/gsutil:/usr/bin:/bin</profile>
    </site>
    <site  handle="condor_pool" arch="x86_64" os="LINUX">
        <profile namespace="pegasus" key="style" >condor</profile>
        <profile namespace="condor" key="universe" >vanilla</profile>
        <profile namespace="env" key="PATH">/ccg/software/gsutil:/usr/bin:/bin</profile>
        <profile namespace="env" key="PEGASUS_HOME">$REMOTE_PEGASUS_HOME</profile>
    </site>
    <site  handle="staging_site" arch="x86_64" os="LINUX">
        <directory type="shared-scratch" path="/pegasus-wms-test001/scratch">
            <file-server operation="all" url="gs://pegasus-wms-test001/scratch"/>
        </directory>
        <directory type="local-storage" path="/pegasus-wms/outputs">
            <file-server operation="all" url="gs://pegasus-wms/outputs"/>
        </directory>
        <profile namespace="pegasus" key="BOTO_CONFIG" >/localhome/bamboo/.boto.service</profile>
        <profile namespace="pegasus" key="GOOGLE_PKCS12" >/localhome/bamboo/.google-service-account.p12</profile>
    </site>
</sitecatalog>
EOF

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

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

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

echo
echo
echo "Starting the workflow..."
pegasus-run $WORK_DIR


