#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
FIXTURE_HOST="${FIXTURE_HOST:-127.0.0.1}"
FIXTURE_PORT="${FIXTURE_PORT:-8080}"
TUNNEL_PORT="${MYSQL_TUNNEL_LOCAL_PORT:-13306}"
FIXTURE_DOCROOT="${ROOT_DIR}/tests/fixture"
PID_FILE="${ROOT_DIR}/working/fixture_server_${FIXTURE_PORT}.pid"
LOG_FILE="${ROOT_DIR}/working/fixture_server_${FIXTURE_PORT}.log"

mkdir -p "${ROOT_DIR}/working"

start_server() {
  if [[ -f "${PID_FILE}" ]] && kill -0 "$(cat "${PID_FILE}")" >/dev/null 2>&1; then
    echo "Fixture server already running on http://${FIXTURE_HOST}:${FIXTURE_PORT} (pid $(cat "${PID_FILE}"))"
    return 0
  fi

  export MYSQL_TUNNEL_LOCAL_PORT="${TUNNEL_PORT}"
  nohup php -S "${FIXTURE_HOST}:${FIXTURE_PORT}" -t "${FIXTURE_DOCROOT}" >"${LOG_FILE}" 2>&1 &
  echo $! >"${PID_FILE}"

  sleep 0.4
  if kill -0 "$(cat "${PID_FILE}")" >/dev/null 2>&1; then
    echo "Fixture server started: http://${FIXTURE_HOST}:${FIXTURE_PORT}"
    echo "Fixture index: http://${FIXTURE_HOST}:${FIXTURE_PORT}/index.php"
    echo "Mailshots UI:  http://${FIXTURE_HOST}:${FIXTURE_PORT}/mailshots_fixture.php"
    echo "Using MySQL tunnel port: ${MYSQL_TUNNEL_LOCAL_PORT}"
  else
    echo "Failed to start fixture server; check ${LOG_FILE}" >&2
    exit 1
  fi
}

stop_server() {
  if [[ ! -f "${PID_FILE}" ]]; then
    echo "Fixture server not running (no pid file)."
    return 0
  fi

  local pid
  pid="$(cat "${PID_FILE}")"
  if kill -0 "${pid}" >/dev/null 2>&1; then
    kill "${pid}" >/dev/null 2>&1 || true
    sleep 0.2
    if kill -0 "${pid}" >/dev/null 2>&1; then
      kill -9 "${pid}" >/dev/null 2>&1 || true
    fi
  fi

  rm -f "${PID_FILE}"
  echo "Fixture server stopped."
}

status_server() {
  if [[ -f "${PID_FILE}" ]] && kill -0 "$(cat "${PID_FILE}")" >/dev/null 2>&1; then
    echo "Fixture server running on http://${FIXTURE_HOST}:${FIXTURE_PORT} (pid $(cat "${PID_FILE}"))"
  else
    echo "Fixture server not running on http://${FIXTURE_HOST}:${FIXTURE_PORT}"
  fi
}

case "${1:-start}" in
  start) start_server ;;
  stop) stop_server ;;
  status) status_server ;;
  restart) stop_server; start_server ;;
  *)
    echo "Usage: $(basename "$0") [start|stop|status|restart]"
    exit 2
    ;;
esac
