#!/bin/bash
# ============================================================
# WolfStack Keepalived Deploy Script
# Usage:
#   sudo bash deploy.sh [install] [node1-primary|node2-secondary|node3-tertiary]
#
# Examples:
#   sudo bash deploy.sh install                    # install + auto-detect
#   sudo bash deploy.sh node1-primary              # deploy role, no install
#   sudo bash deploy.sh install node1-primary      # install + deploy role
# ============================================================

set -e

NODE_TYPE=""
CONF_DIR="/home/jarvis/wolfstack-keepalived"
KEEPALIVED_CONF="/etc/keepalived/keepalived.conf"

detect_node() {
    local ip
    ip=$(hostname -I | tr ' ' '\n' | grep -E '^192\.168\.' | head -n1)
    [[ -z "$ip" ]] && ip=$(hostname -I | awk '{print $1}')

    case "$ip" in
        192.168.50.41)
            NODE_TYPE="node1-primary"
            ;;
        192.168.5.214)
            NODE_TYPE="node2-secondary"
            ;;
        192.168.15.182)
            NODE_TYPE="node3-tertiary"
            ;;
        *)
            echo "ERROR: Could not auto-detect node type from IP: $ip"
            echo "Please specify manually: node1-primary | node2-secondary | node3-tertiary"
            exit 1
            ;;
    esac
    echo "Detected IP: $ip -> $NODE_TYPE"
}

install_keepalived() {
    if command -v apt-get &>/dev/null; then
        echo "Installing keepalived (Debian/Ubuntu)..."
        sudo apt-get update -qq
        sudo apt-get install -y keepalived netcat-openbsd
    elif command -v dnf &>/dev/null; then
        echo "Installing keepalived (RHEL/Fedora)..."
        sudo dnf install -y keepalived nc
    elif command -v zypper &>/dev/null; then
        echo "Installing keepalived (openSUSE)..."
        sudo zypper install -y keepalived netcat-openbsd
    elif command -v pacman &>/dev/null; then
        echo "Installing keepalived (Arch)..."
        sudo pacman -Sy --noconfirm keepalived openbsd-netcat
    else
        echo "ERROR: Unsupported package manager. Install keepalived manually."
        exit 1
    fi
}

deploy_config() {
    local src="$CONF_DIR/keepalived-${NODE_TYPE}.conf"
    if [[ ! -f "$src" ]]; then
        echo "ERROR: Config not found: $src"
        exit 1
    fi

    echo "Deploying $src -> $KEEPALIVED_CONF"
    sudo mkdir -p /etc/keepalived
    sudo cp "$src" "$KEEPALIVED_CONF"
    sudo chmod 644 "$KEEPALIVED_CONF"
}

enable_service() {
    if systemctl is-active --quiet keepalived 2>/dev/null; then
        echo "Keepalived already running. Restarting to pick up new config..."
        sudo systemctl restart keepalived
    else
        echo "Enabling and starting keepalived..."
        sudo systemctl enable keepalived --now
    fi
    sleep 1
    sudo systemctl status keepalived --no-pager
}

# --- main ---

ARGS=("$@")

# Check if first arg is 'install'
if [[ "${ARGS[0]:-}" == "install" ]]; then
    install_keepalived
    ARGS=("${ARGS[@]:1}")   # remove 'install' from args
fi

# If a node type arg remains, use it; otherwise auto-detect
if [[ -n "${ARGS[0]:-}" ]]; then
    NODE_TYPE="${ARGS[0]}"
    echo "Using provided node type: $NODE_TYPE"
else
    detect_node
fi

deploy_config
enable_service

echo ""
echo "========================================"
echo "Keepalived deployed for $NODE_TYPE"
echo "VIP should appear on this node if it is MASTER."
echo "Check: ip addr show | grep 192.168.63.254"
echo "========================================"
