#!/bin/bash

#
# Run this from anywhere, assumes that server is in $HOME/server and
# the build is in-tree (e.g. /home/user/server/build)
# Output written to /tmp/tto3
#
# This will run the innodb.temp_truncate_freed test and while it's
# running attempt to force a race condition by connecting other
# clients to the server-under-test.
#

set -u
B=$HOME/server/build
D=/tmp/tto3
VAR=$D/var
SOCK=$VAR/tmp/mysqld.1.sock
LOG=$VAR/log/mysqld.1.err
CL=$B/client/mariadb
C=${C:-8}
MAXSEC=${MAXSEC:-180}

rm -rf $D; mkdir -p $D
cat > $D/cycle.sql <<"SQL"
CREATE TEMPORARY TABLE t1(c1 MEDIUMTEXT) ENGINE=InnoDB;
INSERT INTO t1 VALUES (repeat(1,16777215));
DROP TEMPORARY TABLE t1;
SQL

cd $B/mysql-test
(nohup ./mtr --suite=innodb temp_truncate_freed --start --vardir=$VAR \
   --build-thread=480 > $D/start.log 2>&1 &)
for i in $(seq 1 120); do [ -S $SOCK ] && break; sleep 1; done
[ -S $SOCK ] || { echo "server did not start"; tail -20 $D/start.log; exit 1; }
sleep 2
$CL --socket=$SOCK -u root -e "
  SET GLOBAL innodb_immediate_scrub_data_uncompressed=1;
  SET GLOBAL innodb_max_dirty_pages_pct=0;
  SET GLOBAL innodb_buffer_pool_size=16777216" || exit 1

SECONDS=0
for c in $(seq 1 $C); do
  ( while [ ! -e $D/stop ]; do
      $CL --socket=$SOCK -u root test < $D/cycle.sql >/dev/null 2>&1 || break
    done ) &
done
( while [ ! -e $D/stop ]; do
    $CL --force --socket=$SOCK -u root -e \
      "SET GLOBAL innodb_buffer_pool_size=16777216;
       SET GLOBAL innodb_buffer_pool_size=6291456" >/dev/null 2>&1
  done ) &

while [ $SECONDS -lt $MAXSEC ]; do
  grep -q "got signal\|Error: attempt to " $LOG 2>/dev/null && break
  sleep 1
done
touch $D/stop
wait 2>/dev/null

if grep -q "got signal\|Error: attempt to " $LOG 2>/dev/null; then
  echo "REPRODUCED after ${SECONDS}s"
  grep -n "Error: attempt to \|got signal" $LOG | head -2
else
  echo "no failure in ${SECONDS}s"
fi
pkill -f "my_safe_proces[s].*/tmp/tto3/var" >/dev/null 2>&1
