#!/bin/bash
# Build and run a program against libflightcrew, to verify that the
# headers and library files are installed correctly.
# Author: Francois Mazen <francois@mzf.fr>

set -e

DEBIAN_TEST_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

EPUB_PATH=$DEBIAN_TEST_DIR/test.epub
if [ -f "$EPUB_PATH" ]; then
    echo "$EPUB_PATH exist"
else 
    echo "ERROR: $EPUB_PATH does not exist"
    exit 1
fi

# Create a temporary workdir that will be removed at the end of the script.
echo "creating temporary folder..."
WORKDIR=$(mktemp -d)
trap "rm -rf $WORKDIR" 0 INT QUIT ABRT PIPE TERM
cd $WORKDIR

# Create the program.
cat <<EOF > flightcrew_test.cpp
#include <iostream>
#include <flightcrew.h>
int main(int argc, char *argv[])
{
    std::vector<FlightCrew::Result> results;

    try
    {
        results = FlightCrew::ValidateEpub("$EPUB_PATH");
    }
    catch(...)
    {
        std::cout << "Exception catched during epub validation." << std::endl;
        return 1;
    }

    if(results.empty())
    {
        std::cout << "Empty results!" << std::endl;
        return 1;
    }
    else
    {
        std::cout << "Validation OK, results:" << std::endl;
        for(std::vector<FlightCrew::Result>::iterator resultIterator = results.begin();
            resultIterator != results.end();
            ++resultIterator)
        {
            std::cout << resultIterator->GetMessage() << std::endl;
        }
    }

    std::cout << "Test Program OK" << std::endl;
    return 0;
}
EOF

# Build the program
echo "building..."
g++ -o flightcrew_test flightcrew_test.cpp -lFlightCrew -I/usr/include/FlightCrew
echo "build: OK"

# Run the program
echo "running..."
test -x flightcrew_test
./flightcrew_test
echo "run: OK"
