#!/bin/bash

echo "=== Test MySQL Replication ==="

MASTER_IP="192.168.56.71"
SLAVE1_IP="192.168.56.72"
SLAVE2_IP="192.168.56.73"
ROOT_PASS="mysql123"

# Test kết nối Master
echo "1. Test kết nối Master..."
mysql -h $MASTER_IP -u root -p$ROOT_PASS -e "SELECT 'Master connected successfully';" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✓ Master connection OK"
else
    echo "✗ Master connection failed"
fi

# Test kết nối Slaves
echo "2. Test kết nối Slaves..."
mysql -h $SLAVE1_IP -u root -p$ROOT_PASS -e "SELECT 'Slave1 connected successfully';" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✓ Slave1 connection OK"
else
    echo "✗ Slave1 connection failed"
fi

mysql -h $SLAVE2_IP -u root -p$ROOT_PASS -e "SELECT 'Slave2 connected successfully';" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✓ Slave2 connection OK"
else
    echo "✗ Slave2 connection failed"
fi

# Test replication
echo "3. Test replication..."
echo "Tạo bảng test trên Master..."
mysql -h $MASTER_IP -u root -p$ROOT_PASS -e "USE testdb; CREATE TABLE IF NOT EXISTS test_replication (id INT AUTO_INCREMENT PRIMARY KEY, message TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);" 2>/dev/null

echo "Insert dữ liệu vào Master..."
mysql -h $MASTER_IP -u root -p$ROOT_PASS -e "USE testdb; INSERT INTO test_replication (message) VALUES ('Test replication at $(date)');" 2>/dev/null

sleep 3

echo "Kiểm tra dữ liệu trên Slaves..."
SLAVE1_COUNT=$(mysql -h $SLAVE1_IP -u root -p$ROOT_PASS -e "USE testdb; SELECT COUNT(*) FROM test_replication;" 2>/dev/null | tail -n1)
SLAVE2_COUNT=$(mysql -h $SLAVE2_IP -u root -p$ROOT_PASS -e "USE testdb; SELECT COUNT(*) FROM test_replication;" 2>/dev/null | tail -n1)

if [ "$SLAVE1_COUNT" -gt "0" ] && [ "$SLAVE2_COUNT" -gt "0" ]; then
    echo "✓ Replication working! Records on slaves: Slave1=$SLAVE1_COUNT, Slave2=$SLAVE2_COUNT"
    mysql -h $SLAVE1_IP -u root -p$ROOT_PASS -e "USE testdb; SELECT * FROM test_replication ORDER BY created_at DESC LIMIT 3;" 2>/dev/null
else
    echo "✗ Replication not working"
fi

# Kiểm tra slave status
echo "4. Kiểm tra slave status..."
mysql -h $SLAVE1_IP -u root -p$ROOT_PASS -e "SHOW SLAVE STATUS\G" 2>/dev/null | grep -E "(Slave_IO_Running|Slave_SQL_Running)"