#!/bin/bash

set -e

source debian/tests/utils

cleanup() {
    result=$?
    set +e
    lines=100
    if [ ${result} -ne 0 ]; then
        echo "## Something failed"
        echo
        echo "## Getting last ${lines} of haproxy unit logs"
        journalctl -u haproxy -n ${lines}
        echo
        echo "## Last ${lines} of dmesg"
        dmesg | tail -n ${lines} || :
        echo
        echo "## Last ${lines} of syslog"
        tail -n ${lines} /var/log/syslog
        echo
        if [ -f /var/log/haproxy.log ]; then
            echo "## Last ${lines} of /var/log/haproxy.log"
            tail -n ${lines} /var/log/haproxy.log
        else
            echo "## No /var/log/haproxy.log found"
        fi
    else
        echo "## All tests passed!"
    fi
    if [ -s ${orig_config} ]; then
        # preserve permissions and ownership
        cat ${orig_config} > /etc/haproxy/haproxy.cfg
        rm -f ${orig_config}
        systemctl restart haproxy
    fi
}

trap cleanup EXIT

# make sure we are confined and in enforce mode for this test, if supported
try_enforce_apparmor

orig_config=$(mktemp)
# preserve permissions
cat /etc/haproxy/haproxy.cfg > ${orig_config}

# relies on existing default config
if ! grep -q "^frontend test-front" /etc/haproxy/haproxy.cfg; then
    cat >> /etc/haproxy/haproxy.cfg <<EOF

frontend test-front
    bind *:8080
    mode http
    default_backend test-back

backend test-back
    mode http
    stick store-request src
    stick-table type ip size 256k expire 30m
    server test-1 localhost:80
EOF
fi

systemctl restart haproxy

# trigger the bug
truncate -s 0 /var/log/haproxy.log
systemctl restart rsyslog

random_file="autopkgtest$$"

echo "## Requesting http://localhost:8080/${random_file}"
curl -s -o /dev/null http://localhost:8080/${random_file}

echo
echo "## Checking logs for GET /${random_file}"
grep "GET /${random_file}" /var/log/haproxy.log
