#!/bin/sh

set -eu

# Needed to find lighttpd binary and the chromedriver binary
export PATH="/sbin:/usr/sbin:/usr/bin:$PATH"

chromedriver --version

PORT=8888
DOCROOT="$AUTOPKGTEST_TMP/docroot"
CONF="$AUTOPKGTEST_TMP/lighttpd.conf"
mkdir -p "$DOCROOT"
# Remove this when postinst is implemented
sudo cp debian/conf/lighttpd.conf /etc/dmarc-srg/lighttpd.conf
# Copy default config
sudo cp /etc/dmarc-srg/conf.sample.php /etc/dmarc-srg/conf.php
cat >"$CONF" <<EOF
server.document-root = "$DOCROOT"
server.port = $PORT
server.modules = ( "mod_access", "mod_auth", "mod_fastcgi", "mod_alias" )
fastcgi.server += ( ".php" =>
        ((
                "bin-path" => "/usr/bin/php-cgi",
                "socket" => "$AUTOPKGTEST_TMP/php.socket",
                "max-procs" => 1,
                "bin-environment" => (
                        "PHP_FCGI_CHILDREN" => "4",
                        "PHP_FCGI_MAX_REQUESTS" => "10000"
                ),
                "bin-copy-environment" => (
                        "PATH", "SHELL", "USER"
                ),
                "broken-scriptfilename" => "enable"
        ))
)
include "/etc/dmarc-srg/lighttpd.conf"
mimetype.assign   += ( ".html" => "text/html", ".css" => "text/css", ".php" => "application/php" )
index-file.names            = ( "index.php" )
static-file.exclude-extensions = ( ".php" )

EOF

# validate test configuration
lighttpd -tt -f "$CONF"

lighttpd -D -f "$CONF" 2>/dev/stdout &
LIGHTTPD_PID=$!

# Allow commands to fail
set +e

# Wait a bit for things to stale
sleep 5
# Do tests
# Send to stdout (https://bugs.python.org/issue16164)
python3 ./debian/tests/test_dmarc-srg_web.py 2>/dev/stdout

EXIT_CODE=$?
if [ "$EXIT_CODE" -ne "0" ]; then
    echo "Tests failed !"
fi

trap 'kill "$LIGHTTPD_PID"' EXIT

exit $EXIT_CODE
