#!/bin/bash

echo "=== Test Pacemaker Failover ==="

VIP="192.168.56.62"
NODE1="192.168.56.60"
NODE2="192.168.56.61"

# Test web service
echo "1. Test web service trên VIP..."
curl -s http://$VIP | grep -q "High Availability" && echo "✓ Web service OK" || echo "✗ Web service failed"

# Kiểm tra cluster status
echo "2. Kiểm tra cluster status..."
ssh vagrant@$NODE1 "sudo pcs status --full" 2>/dev/null | grep -q "Online:" && echo "✓ Cluster online" || echo "✗ Cluster offline"

# Test failover
echo "3. Test failover..."
echo "Dừng node hiện tại đang chạy resource..."

# Tìm node nào đang chạy resource
ACTIVE_NODE=$(ssh vagrant@$NODE1 "sudo pcs status" 2>/dev/null | grep "Started" | grep -o "pacemaker[12]" | head -1)

if [ "$ACTIVE_NODE" = "pacemaker1" ]; then
    TARGET_IP=$NODE1
    STANDBY_NODE="pacemaker1"
else
    TARGET_IP=$NODE2
    STANDBY_NODE="pacemaker2"
fi

echo "Active node: $ACTIVE_NODE"
echo "Putting $STANDBY_NODE into standby mode..."

ssh vagrant@$TARGET_IP "sudo pcs node standby $STANDBY_NODE" 2>/dev/null

sleep 10

# Kiểm tra failover
echo "Kiểm tra sau failover..."
curl -s http://$VIP | grep -q "High Availability" && echo "✓ Failover successful" || echo "✗ Failover failed"

# Khôi phục node
echo "Khôi phục node..."
ssh vagrant@$TARGET_IP "sudo pcs node unstandby $STANDBY_NODE" 2>/dev/null

echo "✓ Failover test hoàn tất"