#!/bin/bash

echo "=== Test PostgreSQL Replication ==="

# Test kết nối Master
echo "1. Test kết nối Master..."
psql -h 192.168.56.50 -U postgres -d testdb -c "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 Replica
echo "2. Test kết nối Replica..."
psql -h 192.168.56.51 -U postgres -d testdb -c "SELECT 'Replica connected successfully';" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✓ Replica connection OK"
else
    echo "✗ Replica connection failed"
fi

# Test replication
echo "3. Test replication..."
echo "Tạo bảng test trên Master..."
psql -h 192.168.56.50 -U postgres -d testdb -c "CREATE TABLE IF NOT EXISTS test_replication (id SERIAL PRIMARY KEY, message TEXT, created_at TIMESTAMP DEFAULT NOW());" 2>/dev/null

echo "Insert dữ liệu vào Master..."
psql -h 192.168.56.50 -U postgres -d testdb -c "INSERT INTO test_replication (message) VALUES ('Test replication at $(date)');" 2>/dev/null

sleep 2

echo "Kiểm tra dữ liệu trên Replica..."
REPLICA_COUNT=$(psql -h 192.168.56.51 -U postgres -d testdb -t -c "SELECT COUNT(*) FROM test_replication;" 2>/dev/null | xargs)

if [ "$REPLICA_COUNT" -gt "0" ]; then
    echo "✓ Replication working! Records on replica: $REPLICA_COUNT"
    psql -h 192.168.56.51 -U postgres -d testdb -c "SELECT * FROM test_replication ORDER BY created_at DESC LIMIT 5;" 2>/dev/null
else
    echo "✗ Replication not working"
fi