#!/bin/sh
# Build and run a program against libzipios, to verify that the
# headers and library files are installed correctly.
# The tested program is inspired by zipios_example.cpp from the
# documentation.
# Author: Francois Mazen <francois@mzf.fr>

set -e

# 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 a zip file.
echo "creating test.zip file..."
touch test.txt
echo "This is a test." > test.txt
zip test test.txt
rm test.txt

# Create the program.
cat <<EOF > zipiostest.c
#include "zipios/zipfile.hpp"
int main(int argc, char *argv[])
{
    try
    {
        std::cout << "Instantiating a ZipFile" << std::endl;
        zipios::ZipFile zf("test.zip");
        std::cout << "list length: " << zf.size() << std::endl;
        if(zf.size() != 1)
        {
            std::cerr << "error: wrong number of entries, " << zf.size() << " instead of 1." << std::endl;
            return 1;
        }
        zipios::FileEntry::vector_t entries(zf.entries());
        for(auto it = entries.begin(); it != entries.end(); ++it)
        {
            std::cout << "  " << *(*it) << std::endl;
        }
        zipios::FileEntry::pointer_t ent(zf.getEntry("test.txt", zipios::FileCollection::MatchPath::IGNORE));
        if(ent)
        {
            zipios::ZipFile::stream_pointer_t is(zf.getInputStream(ent->getName()));
            if(is)
            {
                std::cout << "Contents of entry, " << ent->getName() << ":" << std::endl;
                std::cout << is->rdbuf();
            }
            else
            {
                std::cerr << "error: found an entry for " << ent->getName() << " in test.zip, but could not read it with getInputStream()" << std::endl;
                return 1;
            }
        }
        else
        {
            std::cerr << "error: could not read " << ent->getName() << " from test.zip" << std::endl;
            return 1;
        }
        std::cout << "end of main()" << std::endl;
    }
    catch(std::exception const& e)
    {
        std::cerr << "Exception caught in main() :" << std::endl;
        std::cerr << e.what() << std::endl;
        return 1;
    }
    return 0;
}
EOF

# Build the program
echo "building..."
g++ -o zipiostest zipiostest.c -lzipios
echo "build: OK"

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