#!/bin/bash

show_usage() {
    echo "Sử dụng: $0 [status|start|stop|standby|unstandby] [node1|node2|all]"
    echo "Ví dụ:"
    echo "  $0 status all         # Kiểm tra trạng thái cluster"
    echo "  $0 standby node1      # Đưa node1 vào standby"
    echo "  $0 unstandby node1    # Khôi phục node1"
    echo "  $0 stop all           # Dừng cluster"
}

if [ $# -lt 1 ]; then
    show_usage
    exit 1
fi

ACTION=$1
TARGET=${2:-all}

NODE1_IP="192.168.56.60"
NODE2_IP="192.168.56.61"

execute_on_node() {
    local node_ip=$1
    local command=$2
    ssh vagrant@$node_ip "sudo $command" 2>/dev/null
}

case $ACTION in
    status)
        echo "=== Cluster Status ==="
        execute_on_node $NODE1_IP "pcs status"
        ;;
    start)
        echo "=== Starting Cluster ==="
        if [ "$TARGET" = "all" ]; then
            execute_on_node $NODE1_IP "pcs cluster start --all"
        elif [ "$TARGET" = "node1" ]; then
            execute_on_node $NODE1_IP "pcs cluster start"
        elif [ "$TARGET" = "node2" ]; then
            execute_on_node $NODE2_IP "pcs cluster start"
        fi
        ;;
    stop)
        echo "=== Stopping Cluster ==="
        if [ "$TARGET" = "all" ]; then
            execute_on_node $NODE1_IP "pcs cluster stop --all"
        elif [ "$TARGET" = "node1" ]; then
            execute_on_node $NODE1_IP "pcs cluster stop"
        elif [ "$TARGET" = "node2" ]; then
            execute_on_node $NODE2_IP "pcs cluster stop"
        fi
        ;;
    standby)
        echo "=== Setting Node to Standby ==="
        if [ "$TARGET" = "node1" ]; then
            execute_on_node $NODE1_IP "pcs node standby pacemaker1"
        elif [ "$TARGET" = "node2" ]; then
            execute_on_node $NODE1_IP "pcs node standby pacemaker2"
        fi
        ;;
    unstandby)
        echo "=== Removing Node from Standby ==="
        if [ "$TARGET" = "node1" ]; then
            execute_on_node $NODE1_IP "pcs node unstandby pacemaker1"
        elif [ "$TARGET" = "node2" ]; then
            execute_on_node $NODE1_IP "pcs node unstandby pacemaker2"
        fi
        ;;
    *)
        echo "Hành động không hợp lệ: $ACTION"
        show_usage
        exit 1
        ;;
esac