#!/bin/bash

set -e
set -v


if [ X${testdir} = "X" ]; then
    testdir=`dirname  $0`
    export testdir
fi

TOPDIR=`pwd`

CONDOR_POOL_SHARED_FS=/nfs/ccg4/scratch-purge-no-backups/bamboo
mkdir -p $CONDOR_POOL_SHARED_FS/inputs

# generate the input file
echo "This is sample input to KEG" > f.a
echo "This is sample input to KEG" > $CONDOR_POOL_SHARED_FS/inputs/f.a1

#A output directory
mkdir -p outputs
mkdir -p work

# build the dax generator
export PYTHONPATH=`pegasus-config --python`
$testdir/blackdiamond.py /usr $CONDOR_POOL_SHARED_FS/inputs > blackdiamond.dax

# create the 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  path="$TOPDIR/outputs" type="shared-storage" free-size="" total-size="">
                <file-server  operation="all" url="file://$TOPDIR/outputs">
                </file-server>
        </directory>
        <directory  path="$TOPDIR/work" type="shared-scratch" free-size="" total-size="">
                <file-server  operation="all" url="file://$TOPDIR/work">
                </file-server>
        </directory>
</site>
<site handle="condorpool" arch="x86_64" os="LINUX" >
        <directory  path="${CONDOR_POOL_SHARED_FS}/shared-scratch" type="shared-scratch" free-size="" total-size="">
             <file-server  operation="all" url="gsiftp://cartman.isi.edu/${CONDOR_POOL_SHARED_FS}/shared-scratch">
                </file-server> 
        </directory>           
        <profile namespace="condor" key="universe" >vanilla</profile>
        <profile namespace="pegasus" key="style" >condor</profile>
</site>

</sitecatalog>

EOF

# plan the  workflow
pegasus-plan \
    --conf $testdir/pegasusrc \
    --sites condorpool \
    --output-site local \
    --dir work \
    --cleanup leaf \
    --dax blackdiamond.dax \
     | tee $TOPDIR/plan.out


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

#check if planner did the right thing
if [ ls "$WORK_DIR/stage_in_remote_*in" 1> /dev/null 2>&1 ]; then
    echo "Planner did not create any remote stagein jobs"
    exit 1
fi

set +e
grep  'f.a1\b' $WORK_DIR/stage_in_remote*in 1> /dev/null 2>&1
EC=$?
set -e


if [ $EC -ne 0 ]; then
    echo "remote stage in job does not stagein file f.a1"
    exit 1
fi

set +e
grep  'f.a\b' $WORK_DIR/stage_in_local*in 1> /dev/null 2>&1
EC=$?
set -e


if [ $EC -ne 0 ]; then
    echo "local stage in job does not stagein file f.a"
    exit 1
fi


#now submit the workflow to run
pegasus-run  $WORK_DIR

