#!/bin/bash
# =============================================================================
#  m2-healthcheck -- is this container actually serving players?
#
#  "Serving players" means both doors are open: the login server AND at least
#  the first channel core.  A container where auth is up but every channel core
#  is dead accepts logins and then strands the player at "connecting to the
#  server", which is exactly the failure this check exists to catch.
#
#  Every port in the boot plan is checked, so raising M2_CHANNELS extends the
#  check automatically.
#
#  Deliberately a listen check and not a protocol handshake: a handshake every
#  15 seconds would put a real connection through the auth core's descriptor
#  table forever.  The real handshake test belongs in the verification suite.
# =============================================================================
set -uo pipefail

VAR_DIR="${M2_VAR_DIR:-/opt/metin2/var}"
PLAN="$VAR_DIR/boot-plan"

[ -r "$PLAN" ] || { echo "no boot plan yet (still starting)"; exit 1; }
[ -e "$VAR_DIR/.booted" ] || { echo "boot sequence still running"; exit 1; }

port_open() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; }

down=()
while IFS='|' read -r name _dir _bin port _kind; do
  [ -n "$name" ] || continue
  port_open "$port" || down+=("$name:$port")
done < "$PLAN"

if [ "${#down[@]}" -gt 0 ]; then
  echo "not listening: ${down[*]}"
  exit 1
fi

echo "all cores listening"
exit 0
