#!/bin/bash
# =============================================================================
#  m2-tail-syserr -- forward each core's error log to the container log.
#
#  The cores write syserr next to themselves on the state volume, because the
#  path is relative to CWD and is not configurable.  An operator whose server
#  misbehaves will run `docker compose logs game', not exec into the container
#  and go looking, so the file that actually says what is wrong is followed
#  here and republished with a core-name prefix.
#
#  Startup noise that appears on every single boot is filtered out.  It is
#  filtered rather than left in because a log whose first ten lines are always
#  SYSERR teaches the operator to ignore SYSERR.
# =============================================================================
set -uo pipefail

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

# pid_init/pid_deinit fire on every clean start and stop.
# TABLE_POSTFIX is db announcing it will use the default -- which is correct.
# hupsig is the core acknowledging SIGTERM: it is logged to syserr, but it is
# the sound of a *successful* graceful shutdown, and the supervisor already
# reports stops in its own log.
BENIGN='pid_init|pid_deinit|TABLE_POSTFIX|hupsig'

[ -r "$PLAN" ] || exit 0

while IFS='|' read -r name dir _bin _port _kind; do
  [ -n "$name" ] || continue

  # The file may not exist yet; --retry makes tail wait for it rather than
  # exiting, and -n0 means only new lines are forwarded (the whole history is
  # on the volume for anyone who wants it).
  tail -F -n0 "$dir/syserr" 2>/dev/null \
    | grep --line-buffered -Ev "$BENIGN" \
    | sed -u "s|^|[$name syserr] |" &

  tail -F -n0 "$dir/container.log" 2>/dev/null \
    | sed -u "s|^|[$name] |" &
done < "$PLAN"

wait
