#!/bin/bash

set -e

server="$1"
tempfile=$(mktemp)

trap debug_failure ERR

debug_failure()
{
  sudo systemctl status "$server" || true
  sudo journalctl --no-pager -t "$server"
  cat "$tempfile"
  rm "$tempfile"
}

if [ -n "$AUTOPKGTEST_TMP" ]; then
  case "$server" in
  tomcat10)
    sudo sed -i '/common.loader/ s#$#,/usr/share/tomcat-jakartaee-migration/lib/*.jar#' "/etc/tomcat10/catalina.properties"
    ;;
  tomcat11)
    sudo sed -i '/common.loader/ s#$#,/usr/share/tomcat-jakartaee-migration/lib/*.jar#' "/etc/tomcat11/catalina.properties"
    ;;
  esac

  sudo systemctl restart "$server"
  sleep 5
  sudo systemctl status "$server"
fi

#echo "current path: $PWD"

curl -v --stderr - \
  -F file=@debian/tests/sample.css \
  -F profile=css3svg  \
  -F usermedium=all  \
  -F warning=1  \
  -F vextwarning=  \
  -F lang=en \
  -o "$tempfile" \
  "http://localhost:8080/css-validator/validator"

if grep "<h3>Congratulations! No Error Found.</h3>" "$tempfile"; then
  echo "Validation of file was successful."
else
  debug_failure
  echo "-------------"
  cat "$tempfile"
  echo "-------------"
  echo "Issue validating the file. Output is above."
  exit 1
fi

rm "$tempfile"
