#!/usr/bin/env bash
#
# repro_mdev41295_corruption_inject.sh
#
# Attempt at a higher-fidelity repro for MDEV-41295: rather than forcing
# ha_maria::open() to fail synthetically (fault_inject.gdb), this pauses
# at the same breakpoint, corrupts the REAL on-disk .MAI file for the
# internal Aria temp table via gdb's Python API, then lets the ACTUAL
# maria_open() validation logic run against the damaged file. Goal is a
# genuine validation-triggered failure (ideally "Got error 126 Index is
# corrupted", possibly a related code like 145) rather than a synthetic
# one, and to see whether it cascades into the same MDEV-41294 crash.
#
# Corruption offset/pattern (first 16 bytes of the .MAI file, zeroed to
# 0xFF) is an educated guess at hitting Aria's header/magic validation,
# not a verified exact match for what happened in the original incident.
# Whatever error number actually comes back is the real result -- note
# it rather than assuming it must be 126.
#
# Requires: gdb with Python scripting support (check `gdb --configuration`
# for "--with-python" if the python block errors out), ptrace permission
# (already confirmed working in your environment), a debug build with
# symbols for ha_maria::open.
#
# NOT independently tested by the assistant against a live binary.

set -u

BASEDIR="${BASEDIR:-/home/shipra/Projects/mariadb/10.11.19_debug_debug/data/Server_bin/10.11.19_debug_debug}"
DATADIR="${DATADIR:-$BASEDIR/data}"
TMPDIR_ARIA="${TMPDIR_ARIA:-$BASEDIR/tmp}"
SOCK="${SOCK:-$BASEDIR/socket.sock}"
PORT="${PORT:-10515}"
ERRLOG="${ERRLOG:-$BASEDIR/log/master.err}"
SERVER_ID="${SERVER_ID:-100}"

MYSQLD="$BASEDIR/bin/mariadbd"
CLIENT="$BASEDIR/bin/mariadb"
[ -x "$CLIENT" ] || CLIENT="$BASEDIR/bin/mysql"
ADMIN="$BASEDIR/bin/mariadb-admin"
[ -x "$ADMIN" ] || ADMIN="$BASEDIR/bin/mysqladmin"

GDB_SCRIPT="${GDB_SCRIPT:-$(dirname "$(readlink -f "$0")")/corrupt_inject.gdb}"
WORKDIR="$(mktemp -d /tmp/mdev41295_gdb.XXXXXX)"
GDB_LOG="$WORKDIR/gdb_output.log"

log() { echo "[$(date +%H:%M:%S)] $*"; }

stop_current_server() {
  if [ -S "$SOCK" ]; then
    log "Shutting down currently running server on $SOCK ..."
    "$ADMIN" --no-defaults -uroot --socket="$SOCK" shutdown >/dev/null 2>&1
    local waited=0
    while [ -S "$SOCK" ] && [ $waited -lt 20 ]; do
      sleep 0.5; waited=$((waited + 1))
    done
  fi
  pkill -f "mariadbd .*--datadir=$DATADIR" >/dev/null 2>&1
  sleep 1
}

# Restart with normal/generous settings -- we are NOT relying on any
# fd-limit trickery this time, gdb does the fault injection directly.
start_normal_server() {
  : > "$ERRLOG"
  "$MYSQLD" --no-defaults \
    --loose-innodb-buffer-pool-in-core-dump=0 \
    --max_connections=10000 \
    --table_open_cache=2000 \
    --core-file \
    --basedir="$BASEDIR" \
    --tmpdir="$TMPDIR_ARIA" \
    --datadir="$DATADIR" \
    --socket="$SOCK" \
    --port="$PORT" \
    --log-error="$ERRLOG" \
    --server-id="$SERVER_ID" \
    --open-files-limit=1024 \
    >/dev/null 2>&1 &

  local wait_s=0
  while [ ! -S "$SOCK" ] && [ $wait_s -lt 20 ]; do
    sleep 0.5
    wait_s=$((wait_s + 1))
  done
  [ -S "$SOCK" ]
}

server_pid() {
  pgrep -f "mariadbd .*--datadir=$DATADIR" | head -1
}

server_alive() {
  pgrep -f "mariadbd .*--datadir=$DATADIR" >/dev/null 2>&1
}

sql() {
  "$CLIENT" --no-defaults -uroot --socket="$SOCK" -N -B -e "$1" 2>&1
}

setup_schema() {
  sql "CREATE DATABASE IF NOT EXISTS repro;"
  sql "DROP TABLE IF EXISTS repro.t;"
  sql "
    CREATE TABLE repro.t (
      id int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
      value1 char(10) DEFAULT NULL,
      identifier char(32) DEFAULT NULL,
      user_id int unsigned DEFAULT NULL,
      created timestamp(6) NOT NULL DEFAULT '0000-00-00 00:00:00.000000',
      received timestamp(6) NOT NULL DEFAULT current_timestamp(6),
      need_reply tinyint(1) DEFAULT 0
    ) ENGINE=InnoDB;"
  sql "
    INSERT INTO repro.t (value1, identifier, user_id, need_reply) VALUES
      ('abc', NULL, NULL, 1),
      (NULL, 'xyz', 1, 1),
      ('def', NULL, NULL, 1),
      (NULL, 'xyz', 2, 1);"
}

fire_target_query() {
  sql "
    WITH cte AS
      (SELECT created, received, value1, NULL AS user_id, NULL AS identifier
         FROM repro.t WHERE need_reply = TRUE AND value1 IS NOT NULL
       UNION
       SELECT MIN(created), MAX(received), NULL, GROUP_CONCAT(DISTINCT user_id), identifier
         FROM repro.t WHERE need_reply = TRUE AND identifier IS NOT NULL GROUP BY identifier)
    SELECT value1, user_id, identifier FROM cte ORDER BY created;"
}

main() {
  [ -f "$GDB_SCRIPT" ] || { log "FATAL: gdb script not found at $GDB_SCRIPT"; exit 1; }
  command -v gdb >/dev/null 2>&1 || { log "FATAL: gdb not found in PATH"; exit 1; }

  log "Work directory: $WORKDIR"
  log "gdb output log: $GDB_LOG"

  stop_current_server
  log "Starting server with normal/generous limits (gdb does the fault injection, not fd limits)..."
  start_normal_server || { log "FATAL: server failed to start"; exit 1; }

  setup_schema

  local pid
  pid="$(server_pid)"
  [ -n "$pid" ] || { log "FATAL: could not find mariadbd pid"; exit 1; }
  log "mariadbd pid=$pid"

  log "Attaching gdb and arming fault-injection breakpoint..."
  gdb -p "$pid" -batch -x "$GDB_SCRIPT" > "$GDB_LOG" 2>&1 &
  GDB_BG_PID=$!

  # Give gdb a moment to attach, set the breakpoint, and issue `continue`
  # (server was stopped by the attach itself; it must resume before we
  # can query it again).
  local waited=0
  while [ ! -S "$SOCK" ] && [ $waited -lt 15 ]; do
    sleep 0.5; waited=$((waited + 1))
  done
  # Extra settle time so the breakpoint is definitely armed before we fire.
  sleep 2

  if ! grep -q "breakpoint armed" "$GDB_LOG" 2>/dev/null; then
    log "WARNING: gdb log doesn't yet show 'breakpoint armed' -- proceeding anyway,"
    log "but if nothing happens, check $GDB_LOG for an attach/permission error"
    log "(e.g. ptrace_scope restricting attach -- see /proc/sys/kernel/yama/ptrace_scope)."
  fi

  log "Firing target CTE query..."
  local query_output
  query_output="$(fire_target_query)"
  echo "$query_output"
  echo

  sleep 2

  if ! server_alive; then
    log ">>> mariadbd process is no longer running -- crash likely reproduced."
  else
    log "mariadbd still alive. Checking gdb log for what happened..."
  fi

  log "---- gdb output ($GDB_LOG) ----"
  cat "$GDB_LOG"
  log "---- end gdb output ----"

  log "---- tail of server error log ----"
  tail -n 40 "$ERRLOG"
  log "---- end error log ----"

  if grep -q "corrupted.*bytes at offset" "$GDB_LOG" 2>/dev/null; then
    log "Confirmed: a range of the .MAI file WAS corrupted on disk before the real maria_open() ran"
    log "(this round: offset 64, length 32, leaving the leading signature/version bytes untouched)."

    if echo "$query_output" | grep -qiE "126|corrupt|crashed"; then
      log ">>> Client query output mentions an index-corruption-style error -- check the"
      log "    exact text above against 'Got error 126 \"Index is corrupted\"' from the ticket."
    fi

    if grep -iE "Got error [0-9]+|Index is corrupted|error: 126|not a table|no signature" "$ERRLOG" 2>/dev/null; then
      log ">>> Server error log (FULL, not just tail) shows a relevant message. Exact line(s):"
      grep -iE "Got error [0-9]+|Index is corrupted|not a table|no signature" "$ERRLOG"
    else
      log "No 'Got error'/corruption-style message found anywhere in the full error log."
    fi

    if ! server_alive; then
      log ">>> mariadbd also died -- check the backtrace above: if frame 0 is"
      log "    ha_maria::drop_table with file==0x0, this confirms BOTH tickets in one"
      log "    run (real corruption-triggered open failure -> same NULL-deref crash)."
    elif grep -qiE "Got error 126|Index is corrupted" "$ERRLOG" "$WORKDIR"/* 2>/dev/null; then
      log "Server survived but a real error-126-style failure was logged -- this means"
      log "the corruption produced a genuine open failure WITHOUT reaching the crash."
      log "That would itself be worth investigating: check whether db_stat/file state"
      log "actually matches the crash-reachable conditions from the ticket, or whether"
      log "this corruption pattern is caught/handled earlier than the production incident."
    else
      log "No crash, and no obvious error-126-style message found. Possible reasons:"
      log "  - The corruption offset/pattern didn't actually break Aria's validation"
      log "    (try a different offset, or corrupt more/different bytes -- e.g. the"
      log "    whole first 256 bytes, or truncate the file instead)."
      log "  - The .MAI path guess (name + '.MAI') doesn't match this version's actual"
      log "    on-disk naming -- check what files actually exist under the tmp dir"
      log "    for a #sql-temptable during a normal (non-corrupted) run."
      log "  - maria_open() may have already read/cached what it needs before our"
      log "    breakpoint fired -- corruption timing may need to be earlier, e.g. at"
      log "    the tail end of create_internal_tmp_table's maria_create() call instead."
    fi
  else
    log "The corruption step never appears to have run. Possible causes:"
    log "  - The breakpoint on ha_maria::open never fired -- check ptrace/attach errors"
    log "    in the gdb log above."
    log "  - gdb's Python support may be missing/broken -- look for a Python traceback"
    log "    or 'Python scripting is not supported' in the gdb log above."
    log "  - The temp table naming assumption ('sql-temptable') doesn't match this run."
  fi

  # Leave gdb running in the background in case it's still waiting on
  # something; give the user the option to inspect/kill manually.
  if kill -0 "$GDB_BG_PID" >/dev/null 2>&1; then
    log "Note: background gdb process (pid $GDB_BG_PID) is still running -- inspect"
    log "or kill manually if needed: kill $GDB_BG_PID"
  fi
}

main "$@"
