#!/bin/bash

tempfile=$(mktemp)

trap debug_failure ERR

debug_failure()
{
  sudo systemctl status "$server" || true
  sudo journalctl --no-pager -t "$server"
  if [ "$server" = "jetty12" ]; then
    sudo cat /var/log/jetty12/"$(sudo ls -t1 /var/log/jetty12/ | head -n1)"
  fi
  cat "$tempfile"
  rm "$tempfile"
}

wait_until_not_state()
{
  local server state count count_max
  server="$1"
  state="$2"
  count=0
  count_max=180
  echo "Leaving state '$state' and entering state '$(systemctl show -P ActiveState "$server")'."
  TIMEFORMAT='Elapsed time is %R seconds.'
  { time {
  while [ "$(systemctl show -P ActiveState "$server")" == "$state" ] ; do
    if [ $count -gt $count_max ]; then
      break
    fi
    count=$((count + 1))
    sleep 1
  done
  } } 2>&1
  if [ ! $count -gt $count_max ]; then
    echo "Success."
  else
    echo "Failed (reached max count '$count_max')." >&2
    debug_failure >&2
    exit 1
  fi
}

wait_until_ready()
{
  local server port count count_max
  server="$1"
  port="$2"
  path="$3"
  count=0
  count_max=180
  echo "Waiting until servlet on $server is ready at http://localhost:${port}/$path"
  TIMEFORMAT='Elapsed time is %R seconds.'
  { time {
  while ! nc -z localhost "${port}" >/dev/null 2>&1 && [[ "$(curl -s -o /dev/null -w ''%{http_code}'' http://localhost:${port}/$path)" != "200" ]]; do
    if [ $count -gt $count_max ]; then
      break
    fi
    count=$((count + 1))
    sleep 1
  done
  } } 2>&1
  if [ ! $count -gt $count_max ]; then
    echo "Success."
  else
    echo "Failed (reached max count '$count_max')." >&2
    debug_failure >&2
    exit 1
  fi
}

start_server()
{
  local server port path
  server="$1"
  port="$2"
  path="$3"
  if [ -n "$AUTOPKGTEST_TMP" ]; then
    case "$server" in
    tomcat11)
      if [ "$(dpkg --print-architecture)" = "i386" ]; then
        echo "Adding -Xss2048k JVM option."
        echo -e '[Service]\nEnvironment="CATALINA_OPTS=-Xss2048k"' | sudo systemctl edit --drop-in vnu-tomcat11.conf --stdin tomcat11.service 2>&1
      fi
      if [ "$(dpkg --print-architecture)" = "loong64" ]; then
        echo "Adding -Xss3072k JVM option."
        echo -e '[Service]\nEnvironment="CATALINA_OPTS=-Xss3072k"' | sudo systemctl edit --drop-in vnu-tomcat11.conf --stdin tomcat11.service 2>&1
      fi
      ;;
    esac

    # Need to use 2>&1 because, every now and then, with jetty, systemctl outputs
    # "Stopping 'jetty9.service', but its triggering units are still active"
    sudo systemctl stop --job-mode=triggering "$server" 2>&1
    wait_until_not_state "$server" "active"
    sudo systemctl start "$server"
    wait_until_ready "$server" "$port" "$path"
    sudo systemctl status "$server"
  fi

}
