#!/bin/bash
# Script to free a drive from ubuntu-vg and create Ceph OSD
# Run on R630-01 as root

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo "=========================================="
echo "Prepare Drive from ubuntu-vg for Ceph OSD"
echo "=========================================="
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}ERROR: Please run as root${NC}"
    exit 1
fi

echo -e "${BLUE}=== Step 1: Current ubuntu-vg Status ===${NC}"
echo "-----------------------------------"
if vgs ubuntu-vg &>/dev/null; then
    echo "Volume Group Information:"
    vgs ubuntu-vg
    echo ""
    echo "Logical Volumes:"
    lvs ubuntu-vg
    echo ""
    echo "Physical Volumes:"
    pvs | grep ubuntu-vg
    echo ""
else
    echo -e "${YELLOW}ubuntu-vg not found${NC}"
    echo ""
fi

echo -e "${BLUE}=== Step 2: Available 250GB Drives ===${NC}"
echo "-----------------------------------"
echo "250GB drives detected:"
drives=()
for disk in sdc sdd sde sdf sdg sdh; do
    if [ -b "/dev/$disk" ]; then
        size=$(fdisk -l "/dev/$disk" 2>/dev/null | grep "^Disk /dev/$disk" | awk '{print $3, $4}')
        in_vg=$(pvs 2>/dev/null | grep "/dev/${disk}3" | grep ubuntu-vg | wc -l)
        if [ "$in_vg" -gt 0 ]; then
            echo -e "  ${YELLOW}/dev/$disk: ${size} - In ubuntu-vg${NC}"
            drives+=("$disk")
        else
            echo -e "  ${GREEN}/dev/$disk: ${size} - Available${NC}"
            drives+=("$disk")
        fi
    fi
done
echo ""

echo -e "${BLUE}=== Step 3: Current Ceph OSD Status ===${NC}"
echo "-----------------------------------"
ceph osd tree 2>/dev/null || echo -e "${YELLOW}Ceph not accessible${NC}"
echo ""

echo "=========================================="
echo -e "${GREEN}Ready to Prepare Drive${NC}"
echo "=========================================="
echo ""
echo "To prepare a drive for Ceph OSD, run:"
echo ""
echo -e "${YELLOW}# Choose a drive (e.g., sdc, sdd, sde, sdf, sdg, or sdh)${NC}"
echo -e "${YELLOW}# Replace DRIVE with your choice${NC}"
echo ""
echo "# 1. Check if drive is in ubuntu-vg"
echo "pvs | grep DRIVE"
echo ""
echo "# 2. If in ubuntu-vg, unmount and remove (WARNING: Destroys data!)"
echo "umount /dev/ubuntu-vg/* 2>/dev/null || true"
echo "vgchange -a n ubuntu-vg"
echo "pvremove /dev/DRIVE3"
echo ""
echo "# 3. Wipe the entire drive"
echo "wipefs -a /dev/DRIVE"
echo "dd if=/dev/zero of=/dev/DRIVE bs=1M count=100"
echo ""
echo "# 4. Create Ceph OSD"
echo "ceph-volume lvm create --data /dev/DRIVE"
echo ""
echo "# 5. Verify"
echo "ceph osd tree"
echo "ceph health"
echo ""

