#!/bin/sh
# This script is used both as autopkgtest and at package build time.

set -e

export GNUSTEP_MAKEFILES=/usr/share/GNUstep/Makefiles
export GNUSTEP_INSTALLATION_DOMAIN=SYSTEM

if [ -z $AUTOPKGTEST_TMP ]; then
    # The script is invoked from the override_dh_auto_test target.
    EOUTIL=test/usr/bin/eoutil
    GDLGSDOC=test/usr/bin/gdlgsdoc
    export ADDITIONAL_INCLUDE_DIRS=-I`pwd`/test/usr/include/${DEB_HOST_MULTIARCH}/GNUstep
    export ADDITIONAL_LIB_DIRS=-L`pwd`/test/usr/lib/${DEB_HOST_MULTIARCH}
    export LD_LIBRARY_PATH=`pwd`/test/usr/lib/${DEB_HOST_MULTIARCH}
    export LD=$OBJC
    dpkg-buildflags --export=sh
else
    # Running as autopkgtest.
    DEB_HOST_MULTIARCH=$(dpkg-architecture --query DEB_HOST_MULTIARCH)
    EOUTIL=eoutil
    GDLGSDOC=gdlgsdoc
fi

# We need this configuration file to load the Trading framework.
printf "GNUSTEP_LOCAL_LIBRARY=`pwd`/test/usr/lib/${DEB_HOST_MULTIARCH}/GNUstep\n" > test.conf
chmod 0644 test.conf
export GNUSTEP_CONFIG_FILE=`pwd`/test.conf
EXTRA_LDFLAGS=-Wl,-rpath,`pwd`/test/usr/lib/${DEB_HOST_MULTIARCH}

if [ ! "`echo "$DEB_BUILD_OPTIONS" | grep terse`" ]; then
    verbose="messages=yes"
fi

make -e -C Examples $verbose LDFLAGS="$LDFLAGS $EXTRA_LDFLAGS -LTrading.framework"
make -C Examples install DESTDIR=`pwd`/test

printf "Running createTradingDB tool...\n"
pg_virtualenv <<EOF
 createdb gdl2trading
 test/usr/bin/createTradingDB
EOF

cp Examples/library.eomodel .
printf "Running connection tool...\n"
./test/usr/bin/connection
printf "Running eoexample tool...\n"
./test/usr/bin/eoexample
printf "Running eoexample2 tool...\n"
./test/usr/bin/eoexample2

printf "Running eoutil dump...\n"
$EOUTIL dump ./Examples/Trading/Trading.eomodeld \
        -source plist ./Examples/Trading/Trading.eomodeld/Product.plist \
        -schemaCreate tables -dest script test.script
printf "Running eoutil convert...\n"
$EOUTIL convert ./Examples/library.eomodel \
        PostgreSQL '{ databaseName = test; hostName = localhost; userName = postgres; password = postgres; }' \
        test.eomodel
printf "Running gdlgsdoc...\n"
$GDLGSDOC --template=Tools/eomodeltemplate.gsdoc Examples/library.eomodel

exit 0
