#! /bin/bash

## Set these variables to 1/0 do enable/disable the individual sanity
## tests. Note that the "UNPACK" and "COMPILE" tests are prerequisites
## for the following tests.

SANITY_TEST_UNPACK=1
#SANITY_TEST_COMPILE=1
#SANITY_TEST_RUN_TEST1=1


set -o errexit

if [[ $# != 1 ]]; then
    echo need exactly one argument: seq-opt-bjolp, seq-sat-lama-2011 or some such
    exit 2
fi

DIST=$1

COMMANDLINEOPTIONS="$DIST"

PACKAGE=$DIST.tar.gz

echo "Making sure destination is clear..."
mkdir $DIST

echo "Exporting code..."
hg archive -I 're:src\/translate\/' $DIST
hg archive -I 're:src\/preprocess\/' $DIST
hg archive -I 're:src\/search\/' $DIST
hg archive -I 're:src\/build_all' $DIST
hg archive -I 're:src\/plan-ipc' $DIST


echo "Preparing distribution directory..."
cp build $DIST/
echo '#! /bin/bash' > $DIST/plan
echo '"$(dirname "$0")"/src/plan-ipc' "$COMMANDLINEOPTIONS" '"$@"' >> $DIST/plan
chmod 755 $DIST/plan

echo "Removing LP code..."
rm -r $DIST/src/search/lp

echo "Changing -m32 compiler option to -m64"
sed -i -e "s/-m32/-m64/g" $DIST/src/preprocess/Makefile
sed -i -e "s/-m32/-m64/g" $DIST/src/search/Makefile

# Packaging
echo "Packaging..."
rm -f $PACKAGE
tar czf $PACKAGE $DIST/
rm -rf $DIST

# Sanity tests

testdir=`pwd`/data/tests

function planner-test-run () {
    TESTID=$1
    echo "Sanity test: $TESTID..."
    ./plan $testdir/$TESTID-domain.pddl $testdir/$TESTID-problem.pddl $TESTID-plan

    rm -f output.sas output sas_plan
}

if [[ "$SANITY_TEST_UNPACK" == 1 ]]; then
    echo "Sanity test: Unpacking package..."
    tar xzf $PACKAGE

    if [[ "$SANITY_TEST_COMPILE" == 1 ]]; then
        echo "Sanity test: Compiling..."
        cd $DIST
        ./build

        if [[ "$SANITY_TEST_RUN_TEST1" == 1 ]]; then
            planner-test-run test1
        fi
    fi

    echo "Cleaning up..."
    rm -rf $DIST
fi

echo "Done: $PACKAGE"
