#!/bin/sh
# version 20260804

# Generic test that verifies that all installed libnginx-mod-* packages depend
# on the nginx ABI and that nginx is running with the given module(s):
# - after installation
# - after nginx reload
# - after nginx restart

EX=0

curl_test()
{
  curl --max-time 60 --silent --fail -o /dev/null "$@"
}

# Change directory to $AUTOPKGTEST_TMP
cd "${AUTOPKGTEST_TMP}"

# Verify that every installed nginx module package has the ABI dependency
# generated by dh_nginx.  Without it, upgrades can load an incompatible module.
packages="$(dpkg-query -W \
  -f='${binary:Package}\t${db:Status-Status}\n' \
  'libnginx-mod-*' 2>/dev/null |
  awk -F '\t' '$2 == "installed" { print $1 }')"

if [ -z "${packages}" ]; then
  echo "MISS no installed libnginx-mod-* package found"
  EX=1
fi

for pkg in ${packages}; do
  depends="$(dpkg-query -W -f='${Depends}\n' "${pkg}")"
  abi_dependency="$(printf '%s\n' "${depends}" |
    grep -oE 'nginx-abi-[a-z0-9][a-z0-9+.-]*' | head -n 1)"

  if [ -n "${abi_dependency}" ]; then
    echo "${pkg} module dependency on ${abi_dependency} ... OK"
  else
    echo "${pkg} module dependency on nginx-abi-* ... FAILED, Depends: ${depends:-<none>}"
    EX=1
  fi
done

# Verify that nginx serves requests after module installation
if curl_test \
  -w 'curl after installation: http status: %{http_code} ... ' \
  http://127.0.0.1/; then
  echo "OK"
else
  EX=1
  echo "FAILED"
fi

# Reload nginx to verify that the module configuration remains valid
printf '%s' "nginx reload ... "
if invoke-rc.d nginx reload; then
  echo "OK"
else
  EX=1
  echo "FAILED"
fi
sleep 5

# Verify that nginx serves requests after reload
if curl_test \
  -w 'curl after reload: http status: %{http_code} ... ' \
  http://127.0.0.1/; then
  echo "OK"
else
  EX=1
  echo "FAILED"
fi

# Restart nginx to verify that the module can be loaded from a clean start
printf '%s' "nginx restart ... "
if invoke-rc.d nginx restart; then
  echo "OK"
else
  EX=1
  echo "FAILED"
fi
sleep 5

# Verify that nginx serves requests after restart
if curl_test \
  -w 'curl after restart: http status: %{http_code} ... ' \
  http://127.0.0.1/; then
  echo "OK"
else
  EX=1
  echo "FAILED"
fi

# Print service and nginx diagnostics when any test phase fails
if [ "${EX}" -ne 0 ]; then
  echo "=== journalctl ==="
  journalctl -n all -xu nginx.service || :

  echo "=== error.log ==="
  if [ -f /var/log/nginx/error.log ]; then
    if [ "$(wc -l < /var/log/nginx/error.log)" -gt 100 ]; then
      head -n 50 /var/log/nginx/error.log
      echo '...'
      tail -n 50 /var/log/nginx/error.log
    else
      cat /var/log/nginx/error.log
    fi
  else
    echo "/var/log/nginx/error.log not found"
  fi
fi

exit "${EX}"
