#!/bin/sh
set -eu

cd "${AUTOPKGTEST_TMP}"

compressed_headers="${AUTOPKGTEST_TMP}/filter-compressed.headers"
compressed_body="${AUTOPKGTEST_TMP}/filter-compressed.body"
short_headers="${AUTOPKGTEST_TMP}/filter-short.headers"
short_body="${AUTOPKGTEST_TMP}/filter-short.body"

diagnostics()
{
  for headers in "${AUTOPKGTEST_TMP}"/*.headers; do
    if [ -f "${headers}" ]; then
      echo "=== ${headers} ==="
      sed 's/\r$//' "${headers}"
    fi
  done
  echo "=== journalctl ==="
  journalctl -n all -xu nginx.service || :
  echo "=== error.log ==="
  if [ -f /var/log/nginx/error.log ]; then
    cat /var/log/nginx/error.log
  else
    echo "/var/log/nginx/error.log not found"
  fi
}

fail()
{
  echo "FAILED: $*" >&2
  diagnostics
  exit 1
}

cat <<EOF > /etc/nginx/sites-enabled/default
server {
  listen 80 default_server;
  root /var/www/html;

  location /helloworld {
    default_type text/plain;
    brotli on;
    brotli_types text/plain;
    brotli_min_length 10;
    brotli_comp_level 11;
  }
}
EOF

mkdir -p /var/www/html
printf '%s\n' 'hello world' > /var/www/html/helloworld

nginx -t || fail "nginx configuration test"
invoke-rc.d nginx restart || fail "nginx restart"

curl --max-time 60 --compressed --fail --silent --show-error \
  --header 'Accept-Encoding: br' \
  --dump-header "${compressed_headers}" \
  --output "${compressed_body}" \
  http://127.0.0.1/helloworld || fail "compressed request"

grep -Eiq '^Content-Encoding:[[:space:]]*br[[:space:]]*$' "${compressed_headers}" ||
  fail "compressed response lacks Content-Encoding: br"
cmp -s /var/www/html/helloworld "${compressed_body}" ||
  fail "decoded compressed response body differs"

# Exercise the upstream bounds fix with a one-byte Accept-Encoding value.
curl --max-time 60 --fail --silent --show-error \
  --header 'Accept-Encoding: b' \
  --dump-header "${short_headers}" \
  --output "${short_body}" \
  http://127.0.0.1/helloworld || fail "short Accept-Encoding request"

if grep -Eiq '^Content-Encoding:' "${short_headers}"; then
  fail "short Accept-Encoding unexpectedly enabled compression"
fi
cmp -s /var/www/html/helloworld "${short_body}" ||
  fail "response body for short Accept-Encoding differs"

echo "filter compression and short Accept-Encoding tests ... OK"
