#!/usr/bin/env bash
#
# repro_mdev41294_gdb_fault_inject.sh
#
# Deterministic repro of MDEV-41294 via gdb fault injection: forces
# ha_maria::open() to fail for the internal Aria temp table used by the
# CTE query in the ticket, then lets real code carry the crash from
# there (free_tmp_table -> ha_maria::drop_table NULL deref).
#
# This does NOT reproduce MDEV-41295's specific "error 126 Index is
# corrupted" -- it's a generic forced failure, not real corruption.
#
# Requires: gdb, ptrace permission to attach to your own mariadbd
# process (check /proc/sys/kernel/yama/ptrace_scope if attach fails),
# a debug build with symbols for ha_maria::open (yours qualifies --
# "10.11.19_debug_debug").
#
# NOT independently tested by the assistant against a live binary.

set -u

BASEDIR="${BASEDIR:-/home/shipra/Projects/mariadb/main_release/data/Server_bin/main_release}"
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")")/fault_inject.gdb}"
WORKDIR="$(mktemp -d /tmp/mdev41294_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..."
  fire_target_query
  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 "fault-injection.*forcing return 1" "$GDB_LOG" 2>/dev/null; then
    log "Confirmed: the fault-injection breakpoint DID fire for the internal temp table."
    if grep -q "STOPPED (likely crash)" "$GDB_LOG" 2>/dev/null; then
      log "Confirmed: the process subsequently stopped again after the forced failure"
      log "-- almost certainly the SIGSEGV in ha_maria::drop_table. Review the backtrace"
      log "above and confirm frame 0 matches ha_maria::drop_table with 'file' == 0x0."
    else
      log "The breakpoint fired but no crash was captured afterward -- either the"
      log "code path recovered gracefully (would itself be notable -- check server_alive"
      log "and the error log above for what actually happened), or gdb detached/exited"
      log "before the crash. Check $GDB_LOG in full."
    fi
  else
    log "The fault-injection breakpoint never appears to have fired. Possible causes:"
    log "  - The temp table name doesn't actually contain 'sql-temptable' in this"
    log "    version/config -- check the error log or add a plain (unconditional)"
    log "    breakpoint on ha_maria::open temporarily to see real names passed."
    log "  - gdb failed to attach (permissions/ptrace_scope) -- check $GDB_LOG for errors."
    log "  - The query didn't actually need an on-disk Aria temp table this run --"
    log "    confirm with EXPLAIN / Created_tmp_disk_tables status counter."
  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 "$@"
