#!/bin/bash
# STRESS TEST: Simulates Index Churn vs Blob Churn
# Usage: ./repro.sh

# --- CONFIGURATION ---
DB_USER="sstuser"
DB_PASS="sstpwd"
DB_HOST="127.0.0.1"
DB_PORT="54321"
DB_NAME="test_corruption"

# Path to the mariadb/mysql client binary
DB_CMD="/var/opt/data/myharem/instances/mariadb-enterprise-11.4.7-4-rhel-9-x86_64.54320/bin/mariadb"
# ---------------------

# 1. SETUP DATABASE AND TABLE
echo "--- Setting up database and table ---"
$DB_CMD -u$DB_USER -p$DB_PASS -h$DB_HOST -P$DB_PORT -e "DROP DATABASE IF EXISTS $DB_NAME; CREATE DATABASE $DB_NAME;"
$DB_CMD -u$DB_USER -p$DB_PASS -h$DB_HOST -P$DB_PORT $DB_NAME < json.table.sql

# 2. DEFINE WORKLOAD LOOPS

# THREAD 1: Index Churn
# Uses a persistent connection (pipe) to toggle keys rapidly without spawning new processes.
update_index_churn() {
    (
        while true; do
            echo "UPDATE table_json SET value = JSON_SET(value, '$.complete', 'false', '$.result', 'FAILURE') WHERE id = 1;"
            echo "UPDATE table_json SET value = JSON_SET(value, '$.complete', 'true', '$.result', 'SUCCESS') WHERE id = 1;"
        done
    ) | $DB_CMD -u$DB_USER -p$DB_PASS -h$DB_HOST -P$DB_PORT $DB_NAME --skip-column-names > /dev/null 2>&1
}

# THREAD 2: Blob Churn
# Uses UUID() to generate random data inside SQL, avoiding shell overhead.
update_blob_churn() {
    (
        while true; do
            echo "UPDATE table_json SET value = JSON_SET(value, '$.auditTimestamp', UUID()) WHERE id = 1;"
        done
    ) | $DB_CMD -u$DB_USER -p$DB_PASS -h$DB_HOST -P$DB_PORT $DB_NAME --skip-column-names > /dev/null 2>&1
}

# THREAD 3: Corruption Checker
check_corruption() {
    while true; do
        $DB_CMD -u$DB_USER -p$DB_PASS -h$DB_HOST -P$DB_PORT $DB_NAME -e "SELECT id, virtresult FROM table_json FORCE INDEX (ix_result_complete) WHERE virtresult = 'SUCCESS';" > /dev/null 2>&1
        
        if [ $? -ne 0 ]; then
            echo "!!!!! CORRUPTION DETECTED !!!!!"
            echo "Check error logs for Error 180."
            kill -9 $PID1 $PID2 # Stop the stressors immediately
            exit 1
        fi
        sleep 0.1 # Prevent this thread from eating 100% CPU
    done
}

echo "--- Starting Stress Test ---"
echo "Using Client: $DB_CMD"

update_index_churn &
PID1=$!
update_blob_churn &
PID2=$!
check_corruption &
PID3=$!

wait $PID1 $PID2 $PID3
