#!/bin/sh
set -eu

cd "${AUTOPKGTEST_TMP}"

compressed_headers="${AUTOPKGTEST_TMP}/static-compressed.headers"
compressed_body="${AUTOPKGTEST_TMP}/static-compressed.body"
plain_headers="${AUTOPKGTEST_TMP}/static-plain.headers"
plain_body="${AUTOPKGTEST_TMP}/static-plain.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;
  gzip_vary on;

  location / {
    brotli_static on;
  }
}
EOF

mkdir -p /var/www/html
printf '%s\n' 'hello world' > /var/www/html/helloworld
brotli -9 < /var/www/html/helloworld > /var/www/html/helloworld.br
printf '%s\n' 'plain file' > /var/www/html/plain

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 "pre-compressed request"

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

# Regression test for #97: a file without a .br variant must not gain Vary.
curl --max-time 60 --fail --silent --show-error \
  --header 'Accept-Encoding: br' \
  --dump-header "${plain_headers}" \
  --output "${plain_body}" \
  http://127.0.0.1/plain || fail "plain request"

if grep -Eiq '^Content-Encoding:' "${plain_headers}"; then
  fail "plain response unexpectedly has Content-Encoding"
fi
if grep -Eiq '^Vary:' "${plain_headers}"; then
  fail "plain response unexpectedly has Vary"
fi
cmp -s /var/www/html/plain "${plain_body}" ||
  fail "plain response body differs"

echo "static compression and Vary regression tests ... OK"
