#!/bin/bash
set -e

RELEASE_DIR=$1

if [ -z "$RELEASE_DIR" ]; then
  echo "Usage: $0 <release-dir>"
  exit 1
fi

echo "=================================================="
echo "RELEASE DIR: $RELEASE_DIR"
echo "=================================================="

# -----------------------------
# locate mariadb-binlog
# -----------------------------
BINLOG_TOOL="$RELEASE_DIR/bin/mariadb-binlog"

if [ ! -x "$BINLOG_TOOL" ]; then
  echo "mariadb-binlog not found in release bin/"
  echo "Trying PATH..."
  BINLOG_TOOL=$(which mariadb-binlog 2>/dev/null || true)
fi

if [ -z "$BINLOG_TOOL" ] || [ ! -x "$BINLOG_TOOL" ]; then
  echo "ERROR: mariadb-binlog not found"
  exit 1
fi

echo "USING TOOL: $BINLOG_TOOL"

# -----------------------------
# locate binlog directory
# -----------------------------
VAR_DIR=$(find "$RELEASE_DIR" -type d -path "*mariadb-test/var*" 2>/dev/null | head -1)

if [ -z "$VAR_DIR" ]; then
  echo "ERROR: cannot find mariadb-test/var directory"
  exit 1
fi

echo "VAR DIR: $VAR_DIR"

BINLOG=$(find "$VAR_DIR" -type f -name "mysqld-bin.000001" | head -1)

if [ -z "$BINLOG" ]; then
  echo "ERROR: binlog file not found"
  exit 1
fi

echo "BINLOG: $BINLOG"
echo

# -----------------------------
# run tests
# -----------------------------
echo "[1] Full dump..."
$BINLOG_TOOL "$BINLOG" > all.out

echo "[2] stop-datetime test..."
$BINLOG_TOOL \
  --stop-datetime='2099-12-31 23:59:59' \
  "$BINLOG" > stop.out

# -----------------------------
# verification
# -----------------------------
echo
echo "=================================================="
echo "RESULTS"
echo "=================================================="

FULL=$(grep -c GTID all.out || true)
STOP=$(grep -c GTID stop.out || true)

echo "FULL GTID COUNT : $FULL"
echo "STOP GTID COUNT : $STOP"
echo

wc -l all.out stop.out
echo

echo "STOP SAMPLE:"
head -20 stop.out

# -----------------------------
# verdict
# -----------------------------
echo
echo "=================================================="
echo "VERDICT"
echo "=================================================="

if [ "$STOP" -eq 0 ]; then
  echo "BUG REPRODUCED"
  echo "   stop-datetime skipped transactional events"
  exit 1
elif [ "$STOP" -lt "$FULL" ]; then
  echo "⚠️ PARTIAL LOSS DETECTED"
  exit 2
else
  echo "✔ OK"
  exit 0
fi
