#!/usr/bin/env bash
# Expand container storage dynamically

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

source "$PROJECT_ROOT/lib/common.sh"
source "$PROJECT_ROOT/lib/proxmox-api.sh"

# Load configuration
load_config

# Function to expand container storage
expand_container_storage() {
    local vmid="$1"
    local additional_size="${2:-50}"  # GB
    
    log_info "Expanding storage for container $vmid by ${additional_size}GB..."
    
    # Check if container exists
    if ! pct list | grep -q "^\s*$vmid\s"; then
        error_exit "Container $vmid does not exist"
    fi
    
    # Get current disk size
    local current_config
    current_config=$(pct config "$vmid" 2>/dev/null | grep "^rootfs:" || echo "")
    
    if [[ -z "$current_config" ]]; then
        error_exit "Could not get current disk configuration for container $vmid"
    fi
    
    # Extract storage and current size
    local storage_pool
    local current_size
    storage_pool=$(echo "$current_config" | sed -n 's/.*storage=\([^,]*\).*/\1/p' || echo "${PROXMOX_STORAGE}")
    current_size=$(echo "$current_config" | grep -oP 'size=\K[0-9]+' || echo "0")
    
    local new_size=$((current_size + additional_size))
    
    log_info "Container $vmid current size: ${current_size}GB"
    log_info "New size: ${new_size}GB (adding ${additional_size}GB)"
    
    # Check storage availability
    local node
    node=$(pct list | grep "^\s*$vmid\s" | awk '{print $3}' || echo "${PROXMOX_NODE}")
    
    log_info "Expanding container $vmid disk on node $node..."
    
    # Expand disk
    if proxmox_expand_disk "$vmid" "$additional_size" "$node"; then
        log_success "Successfully expanded container $vmid disk to ${new_size}GB"
        
        # Optionally expand filesystem inside container
        read -p "Expand filesystem inside container? [y/N]: " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            log_info "Expanding filesystem inside container..."
            pct exec "$vmid" -- bash -c "growpart /dev/sda 1 && resize2fs /dev/sda1" || {
                log_warn "Manual filesystem expansion may be required"
            }
        fi
    else
        error_exit "Failed to expand container storage"
    fi
}

# Main
if [[ $# -lt 2 ]]; then
    echo "Usage: $0 <VMID> <additional_size_GB>"
    echo ""
    echo "Examples:"
    echo "  $0 1000 50    # Expand container 1000 (validator) by 50GB"
    echo "  $0 2500 100   # Expand container 2500 (RPC core) by 100GB"
    exit 1
fi

check_root
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

VMID="$1"
ADDITIONAL_SIZE="$2"

expand_container_storage "$VMID" "$ADDITIONAL_SIZE"

log_success "Storage expansion completed!"

