#!/usr/bin/env bash
# Remove and prune all containers with VMID 120 and above
# This will STOP, DESTROY, and PRUNE containers

set -euo pipefail

HOST="${1:-192.168.11.10}"
USER="${2:-root}"
PASS="${3:-}"

if [[ -z "$PASS" ]]; then
    echo "Usage: $0 [HOST] [USER] [PASSWORD]"
    echo "Example: $0 192.168.11.10 root 'password'"
    exit 1
fi

export SSHPASS="$PASS"

echo "=== Removing Containers VMID 120+ ==="
echo "Host: $HOST"
echo ""

# Get list of containers to remove
echo "Fetching list of containers VMID 120+..."
containers=$(sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct list | awk 'NR>1 && \$1 >= 120 {print \$1}' | sort -n")

if [[ -z "$containers" ]]; then
    echo "No containers found with VMID >= 120"
    exit 0
fi

echo "Containers to be removed:"
for vmid in $containers; do
    status=$(sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct status $vmid 2>/dev/null | awk '{print \$2}' || echo 'missing'")
    name=$(sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct list | awk '\$1 == $vmid {print \$3}' || echo 'unknown'")
    echo "  VMID $vmid: $name (status: $status)"
done

echo ""
echo "⚠️  WARNING: This will DESTROY all containers VMID 120+"
echo "   This action cannot be undone!"
echo ""

# Process each container
for vmid in $containers; do
    echo "Processing VMID $vmid..."
    
    # Get container name for logging
    name=$(sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct list | awk '\$1 == $vmid {print \$3}' || echo 'unknown'")
    
    # Check if container exists
    if ! sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct list | grep -q \"^\s*$vmid\s\""; then
        echo "  ⚠️  VMID $vmid does not exist, skipping"
        continue
    fi
    
    # Stop container if running
    status=$(sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct status $vmid 2>/dev/null | awk '{print \$2}' || echo 'stopped'")
    if [[ "$status" == "running" ]]; then
        echo "  Stopping container $vmid ($name)..."
        sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct stop $vmid" || echo "  ⚠️  Failed to stop $vmid (continuing)"
        sleep 2
    fi
    
    # Destroy container
    echo "  Destroying container $vmid ($name)..."
    if sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct destroy $vmid" 2>&1; then
        echo "  ✅ Container $vmid destroyed"
    else
        echo "  ❌ Failed to destroy container $vmid"
    fi
done

echo ""
echo "=== Cleanup and Pruning ==="

# Prune unused volumes (optional - be careful with this)
echo "Note: Volume pruning is not performed automatically to avoid data loss"
echo "To manually prune unused volumes, run on Proxmox host:"
echo "  pvesm prune-orphans"

echo ""
echo "=== Container Removal Complete ==="
echo "Remaining containers:"
sshpass -e ssh -o StrictHostKeyChecking=no "$USER@$HOST" "pct list"

