#!/bin/bash
# Fresh Ceph setup on Proxmox VE nodes
set -e

PUBLIC_NETWORK="192.168.11.0/24"
CLUSTER_NETWORK="192.168.11.0/24"
HOSTNAME=$(hostname -s)

echo "=== Fresh Ceph Setup on $HOSTNAME ==="

# Check if we're on a Proxmox node
if [ ! -d "/etc/pve" ]; then
    echo "ERROR: This script must be run on a Proxmox node"
    exit 1
fi

echo ""
echo "=== Step 1: Installing Ceph packages ==="
apt-get update
apt-get install -y ceph ceph-common ceph-base

echo ""
echo "=== Step 2: Initializing Ceph cluster (only on first node) ==="
if [ "$HOSTNAME" = "ml110-01" ]; then
    echo "Initializing Ceph cluster on ml110-01..."
    if [ ! -f "/etc/pve/ceph.conf" ]; then
        pveceph init --network $PUBLIC_NETWORK --cluster-network $CLUSTER_NETWORK
    else
        echo "Ceph already initialized"
    fi
else
    echo "Skipping init on $HOSTNAME (should be done on ml110-01 first)"
fi

echo ""
echo "=== Step 3: Creating monitor ==="
if [ "$HOSTNAME" = "ml110-01" ]; then
    echo "Creating monitor on ml110-01..."
    pveceph mon create 2>&1 || echo "Monitor may already exist"
elif [ "$HOSTNAME" = "r630-01" ]; then
    echo "Creating monitor on r630-01..."
    pveceph mon create 2>&1 || echo "Monitor may already exist"
fi

echo ""
echo "=== Step 4: Starting monitor service ==="
systemctl enable ceph-mon@$HOSTNAME
systemctl start ceph-mon@$HOSTNAME
sleep 5
systemctl status ceph-mon@$HOSTNAME --no-pager | head -15

echo ""
echo "=== Step 5: Verifying quorum ==="
sleep 10
if ceph quorum_status &>/dev/null; then
    echo "Quorum established!"
    ceph quorum_status 2>&1 | head -10
else
    echo "Quorum not yet established (may take a few minutes)"
fi

echo ""
echo "=== COMPLETE ==="
echo "Next steps:"
echo "1. Verify quorum: ceph quorum_status"
echo "2. Create OSDs: ceph-volume lvm create --data /dev/<disk>"
echo "3. Check cluster health: ceph -s"

