#!/bin/bash
# remove-test-vms.sh
# Remove test VMs 100-115 from Proxmox

set -euo pipefail

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

# Load environment
if [ -f "${PROJECT_ROOT}/.env" ]; then
    set -a
    source "${PROJECT_ROOT}/.env"
    set +a
fi

PROXMOX_PASS="${PROXMOX_ROOT_PASS:-L@kers2010}"
PROXMOX_1_URL="https://192.168.11.10:8006"
PROXMOX_2_URL="https://192.168.11.11:8006"

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

log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $*"
}

log_success() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] ✅${NC} $*"
}

log_warning() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] ⚠️${NC} $*"
}

log_error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ❌${NC} $*"
}

# Get ticket
get_ticket() {
    local api_url=$1
    local response
    response=$(curl -k -s -X POST \
        -d "username=root@pam&password=${PROXMOX_PASS}" \
        "${api_url}/api2/json/access/ticket" 2>/dev/null)
    
    if echo "${response}" | grep -q "authentication failure"; then
        echo ""
        return 1
    fi
    
    if command -v jq &> /dev/null; then
        echo "${response}" | jq -r '.data.ticket // empty' 2>/dev/null
    else
        echo "${response}" | grep -o '"ticket":"[^"]*' | head -1 | cut -d'"' -f4
    fi
}

# Get CSRF
get_csrf() {
    local api_url=$1
    local response
    response=$(curl -k -s -X POST \
        -d "username=root@pam&password=${PROXMOX_PASS}" \
        "${api_url}/api2/json/access/ticket" 2>/dev/null)
    
    if echo "${response}" | grep -q "authentication failure"; then
        echo ""
        return 1
    fi
    
    if command -v jq &> /dev/null; then
        echo "${response}" | jq -r '.data.CSRFPreventionToken // empty' 2>/dev/null
    else
        echo "${response}" | grep -o '"CSRFPreventionToken":"[^"]*' | head -1 | cut -d'"' -f4
    fi
}

# Get VM info
get_vm_info() {
    local api_url=$1
    local node=$2
    local vmid=$3
    local ticket=$4
    
    curl -k -s -b "PVEAuthCookie=${ticket}" \
        "${api_url}/api2/json/nodes/${node}/qemu/${vmid}/config" 2>/dev/null | \
        jq -r '.data.name // empty' 2>/dev/null
}

# Delete VM
delete_vm() {
    local api_url=$1
    local node=$2
    local vmid=$3
    local ticket=$4
    local csrf=$5
    
    # Stop VM first if running
    curl -k -s -X POST \
        -H "CSRFPreventionToken: ${csrf}" \
        -b "PVEAuthCookie=${ticket}" \
        "${api_url}/api2/json/nodes/${node}/qemu/${vmid}/status/stop" > /dev/null 2>&1
    
    sleep 2
    
    # Delete VM
    local response
    response=$(curl -k -s -X DELETE \
        -H "CSRFPreventionToken: ${csrf}" \
        -b "PVEAuthCookie=${ticket}" \
        "${api_url}/api2/json/nodes/${node}/qemu/${vmid}" 2>/dev/null)
    
    if echo "${response}" | grep -q '"data":null'; then
        return 0
    fi
    
    return 1
}

# Find test VMs
find_test_vms() {
    local api_url=$1
    local node=$2
    local ticket=$3
    
    curl -k -s -b "PVEAuthCookie=${ticket}" \
        "${api_url}/api2/json/nodes/${node}/qemu" 2>/dev/null | \
        jq -r '.data[] | select(.vmid >= 100 and .vmid <= 115) | "\(.vmid) - \(.name)"' 2>/dev/null
}

main() {
    log "=========================================="
    log "Removing Test VMs (100-115)"
    log "=========================================="
    log ""
    
    # Site 1
    log "Site 1 (ml110-01):"
    local ticket1 csrf1
    ticket1=$(get_ticket "${PROXMOX_1_URL}")
    csrf1=$(get_csrf "${PROXMOX_1_URL}")
    
    if [ -z "${ticket1}" ] || [ -z "${csrf1}" ]; then
        log_error "Failed to authenticate to Site 1"
    else
        log_success "Authenticated to Site 1"
        
        local test_vms
        test_vms=$(find_test_vms "${PROXMOX_1_URL}" "ml110-01" "${ticket1}")
        
        if [ -z "${test_vms}" ]; then
            log "  No test VMs found (100-115)"
        else
            echo "${test_vms}" | while IFS=' - ' read -r vmid vmname; do
                log "  Found test VM: ${vmid} - ${vmname}"
                log "    Deleting..."
                if delete_vm "${PROXMOX_1_URL}" "ml110-01" "${vmid}" "${ticket1}" "${csrf1}"; then
                    log_success "    VM ${vmid} deleted"
                else
                    log_error "    Failed to delete VM ${vmid}"
                fi
                sleep 1
            done
        fi
    fi
    
    log ""
    
    # Site 2
    log "Site 2 (r630-01):"
    local ticket2 csrf2
    ticket2=$(get_ticket "${PROXMOX_2_URL}")
    csrf2=$(get_csrf "${PROXMOX_2_URL}")
    
    if [ -z "${ticket2}" ] || [ -z "${csrf2}" ]; then
        log_error "Failed to authenticate to Site 2"
    else
        log_success "Authenticated to Site 2"
        
        local test_vms
        test_vms=$(find_test_vms "${PROXMOX_2_URL}" "r630-01" "${ticket2}")
        
        if [ -z "${test_vms}" ]; then
            log "  No test VMs found (100-115)"
        else
            echo "${test_vms}" | while IFS=' - ' read -r vmid vmname; do
                log "  Found test VM: ${vmid} - ${vmname}"
                log "    Deleting..."
                if delete_vm "${PROXMOX_2_URL}" "r630-01" "${vmid}" "${ticket2}" "${csrf2}"; then
                    log_success "    VM ${vmid} deleted"
                else
                    log_error "    Failed to delete VM ${vmid}"
                fi
                sleep 1
            done
        fi
    fi
    
    log ""
    log "=========================================="
    log_success "Test VM cleanup complete!"
    log ""
}

main "$@"

