#!/bin/bash
# Install required packages on R630-01 for Ceph and system management
# Run on R630-01 as root

set -e

# Set non-interactive mode to avoid prompts
export DEBIAN_FRONTEND=noninteractive

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

echo "=========================================="
echo -e "${CYAN}R630-01 Package Installation${NC}"
echo "=========================================="
echo ""

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

# Update package list
echo -e "${BLUE}=== Step 1: Update Package Lists ===${NC}"
echo "-----------------------------------"
apt-get update
echo -e "${GREEN}✓ Package lists updated${NC}"
echo ""

# Essential utilities
echo -e "${BLUE}=== Step 2: Install Essential Utilities ===${NC}"
echo "-----------------------------------"
ESSENTIAL_PACKAGES=(
    "curl"
    "wget"
    "git"
    "jq"
    "vim"
    "nano"
    "htop"
    "tree"
    "unzip"
    "zip"
    "rsync"
    "screen"
    "tmux"
)

for pkg in "${ESSENTIAL_PACKAGES[@]}"; do
    if dpkg -l | grep -q "^ii  $pkg "; then
        echo -e "  ${GREEN}✓${NC} $pkg (already installed)"
    else
        echo "  Installing $pkg..."
        apt-get install -y "$pkg" && echo -e "  ${GREEN}✓${NC} $pkg installed"
    fi
done
echo ""

# Disk and storage management
echo -e "${BLUE}=== Step 3: Install Disk & Storage Tools ===${NC}"
echo "-----------------------------------"
STORAGE_PACKAGES=(
    "lvm2"           # LVM management
    "parted"          # Disk partitioning
    "gdisk"           # GPT partition table tools
    "fdisk"           # Partition table manipulator
    "util-linux"      # lsblk and other utilities
    "smartmontools"   # SMART disk monitoring
)

for pkg in "${STORAGE_PACKAGES[@]}"; do
    if dpkg -l | grep -q "^ii  $pkg "; then
        echo -e "  ${GREEN}✓${NC} $pkg (already installed)"
    else
        echo "  Installing $pkg..."
        apt-get install -y "$pkg" && echo -e "  ${GREEN}✓${NC} $pkg installed"
    fi
done
echo ""

# Time synchronization
echo -e "${BLUE}=== Step 4: Install Time Synchronization ===${NC}"
echo "-----------------------------------"
if dpkg -l | grep -q "^ii  chrony "; then
    echo -e "${GREEN}✓ chrony (already installed)${NC}"
else
    echo "Installing chrony..."
    apt-get install -y chrony
    systemctl enable chronyd || systemctl enable chrony
    systemctl start chronyd || systemctl start chrony
    echo -e "${GREEN}✓ chrony installed and started${NC}"
fi
echo ""

# Python and development tools
echo -e "${BLUE}=== Step 5: Install Python & Development Tools ===${NC}"
echo "-----------------------------------"
PYTHON_PACKAGES=(
    "python3"
    "python3-pip"
    "python3-venv"
    "build-essential"
)

for pkg in "${PYTHON_PACKAGES[@]}"; do
    if dpkg -l | grep -q "^ii  $pkg "; then
        echo -e "  ${GREEN}✓${NC} $pkg (already installed)"
    else
        echo "  Installing $pkg..."
        apt-get install -y "$pkg" && echo -e "  ${GREEN}✓${NC} $pkg installed"
    fi
done
echo ""

# Ceph packages (if Ceph repository is configured)
echo -e "${BLUE}=== Step 6: Install Ceph Packages ===${NC}"
echo "-----------------------------------"

CEPH_VERSION="${CEPH_VERSION:-quincy}"
CEPH_REPO_CONFIGURED=false

# Check if Ceph repository is configured
if [ -f /etc/apt/sources.list.d/ceph.list ] || [ -f /etc/apt/sources.list.d/ceph-no-sub.list ]; then
    CEPH_REPO_CONFIGURED=true
    echo -e "${GREEN}✓ Ceph repository already configured${NC}"
else
    echo "Ceph repository not found. Setting up..."
    
    # Create keyrings directory
    mkdir -p /etc/apt/keyrings
    
    # Download Ceph release key
    if wget -q -O /etc/apt/keyrings/ceph-release.asc 'https://download.ceph.com/keys/release.asc'; then
        # Detect Debian/Proxmox version
        if [ -f /etc/debian_version ]; then
            DEBIAN_VERSION=$(cat /etc/debian_version | cut -d. -f1)
            if [ "$DEBIAN_VERSION" = "11" ]; then
                CODENAME="bullseye"
            elif [ "$DEBIAN_VERSION" = "12" ]; then
                CODENAME="bookworm"
            else
                CODENAME="bullseye"  # Default
            fi
        else
            CODENAME="bullseye"  # Default for Proxmox
        fi
        
        # Add Ceph repository
        echo "deb [signed-by=/etc/apt/keyrings/ceph-release.asc] https://download.ceph.com/debian-${CEPH_VERSION}/ ${CODENAME} main" > /etc/apt/sources.list.d/ceph.list
        
        # Try Proxmox Ceph repo as fallback
        if [ -f /etc/os-release ] && grep -q "Proxmox" /etc/os-release; then
            echo "deb http://download.proxmox.com/debian/ceph-${CEPH_VERSION} ${CODENAME} no-subscription" >> /etc/apt/sources.list.d/ceph-no-sub.list
        fi
        
        apt-get update || apt-get update --allow-releaseinfo-change || true
        CEPH_REPO_CONFIGURED=true
        echo -e "${GREEN}✓ Ceph repository configured${NC}"
    else
        echo -e "${YELLOW}⚠ Could not download Ceph repository key${NC}"
        echo "  You may need to configure Ceph repository manually"
    fi
fi

# Install Ceph packages if repository is configured
if [ "$CEPH_REPO_CONFIGURED" = true ]; then
    CEPH_PACKAGES=(
        "ceph"
        "ceph-common"
        "ceph-base"
        "ceph-volume"
        "ceph-mds"
    )
    
    for pkg in "${CEPH_PACKAGES[@]}"; do
        if dpkg -l | grep -q "^ii  $pkg "; then
            echo -e "  ${GREEN}✓${NC} $pkg (already installed)"
        else
            echo "  Installing $pkg..."
            if apt-get install -y "$pkg" 2>&1 | grep -v "WARNING: apt does not have a stable CLI interface"; then
                echo -e "  ${GREEN}✓${NC} $pkg installed"
            else
                echo -e "  ${YELLOW}⚠${NC} $pkg installation had issues (may already be installed)"
            fi
        fi
    done
else
    echo -e "${YELLOW}⚠ Skipping Ceph package installation (repository not configured)${NC}"
    echo "  To install Ceph later, configure the repository and run:"
    echo "  apt-get install -y ceph ceph-common ceph-base ceph-volume"
fi
echo ""

# Network tools
echo -e "${BLUE}=== Step 7: Install Network Tools ===${NC}"
echo "-----------------------------------"
NETWORK_PACKAGES=(
    "net-tools"       # ifconfig, netstat
    "iproute2"        # ip command
    "tcpdump"         # Network packet analyzer
    "nmap"            # Network scanner
)

for pkg in "${NETWORK_PACKAGES[@]}"; do
    if dpkg -l | grep -q "^ii  $pkg "; then
        echo -e "  ${GREEN}✓${NC} $pkg (already installed)"
    else
        echo "  Installing $pkg..."
        apt-get install -y "$pkg" && echo -e "  ${GREEN}✓${NC} $pkg installed"
    fi
done

# iperf3 with pre-configured answer (don't start as daemon)
if dpkg -l | grep -q "^ii  iperf3 "; then
    echo -e "  ${GREEN}✓${NC} iperf3 (already installed)"
else
    echo "  Installing iperf3..."
    echo "iperf3 iperf3/start_daemon boolean false" | debconf-set-selections
    apt-get install -y iperf3 && echo -e "  ${GREEN}✓${NC} iperf3 installed"
fi
echo ""

# Monitoring and system info
echo -e "${BLUE}=== Step 8: Install Monitoring Tools ===${NC}"
echo "-----------------------------------"
MONITORING_PACKAGES=(
    "iotop"           # I/O monitoring
    "nethogs"         # Network usage by process
    "iftop"           # Network bandwidth monitor
)

for pkg in "${MONITORING_PACKAGES[@]}"; do
    if dpkg -l | grep -q "^ii  $pkg "; then
        echo -e "  ${GREEN}✓${NC} $pkg (already installed)"
    else
        echo "  Installing $pkg..."
        apt-get install -y "$pkg" && echo -e "  ${GREEN}✓${NC} $pkg installed"
    fi
done
echo ""

# Cleanup
echo -e "${BLUE}=== Step 9: Cleanup ===${NC}"
echo "-----------------------------------"
apt-get autoremove -y
apt-get autoclean -y
echo -e "${GREEN}✓ Cleanup complete${NC}"
echo ""

# Summary
echo "=========================================="
echo -e "${GREEN}Installation Complete!${NC}"
echo "=========================================="
echo ""
echo "Installed packages:"
echo "  ✓ Essential utilities (curl, wget, git, jq, etc.)"
echo "  ✓ Disk & storage tools (lvm2, parted, gdisk, etc.)"
echo "  ✓ Time synchronization (chrony)"
echo "  ✓ Python & development tools"
if [ "$CEPH_REPO_CONFIGURED" = true ]; then
    echo "  ✓ Ceph packages (ceph, ceph-common, ceph-volume, etc.)"
else
    echo "  ⚠ Ceph packages (repository needs configuration)"
fi
echo "  ✓ Network tools"
echo "  ✓ Monitoring tools"
echo ""
echo "Next steps:"
echo "1. Verify Ceph installation: ceph --version"
echo "2. Check disk layout: ./scripts/analyze-r630-disk-layout.sh"
echo "3. Setup Ceph OSDs: ./scripts/setup-ceph-osds-r630.sh"
echo ""

