#!/usr/bin/env bash
# Rollback functions for deployment scripts
# Tracks created containers and provides rollback capability

ROLLBACK_FILE="${ROLLBACK_FILE:-/tmp/proxmox-deployment-rollback-$$.log}"

# Initialize rollback tracking
init_rollback() {
    local rollback_file="${1:-$ROLLBACK_FILE}"
    ROLLBACK_FILE="$rollback_file"
    > "$ROLLBACK_FILE"
    log_debug "Initialized rollback tracking: $ROLLBACK_FILE"
}

# Register a container for rollback
register_container() {
    local vmid="$1"
    local container_type="${2:-unknown}"
    local timestamp="${3:-$(date +%s)}"
    
    echo "$vmid|$container_type|$timestamp" >> "$ROLLBACK_FILE"
    log_debug "Registered container $vmid ($container_type) for rollback"
}

# Get all registered containers
get_registered_containers() {
    if [[ ! -f "$ROLLBACK_FILE" ]]; then
        return 1
    fi
    cat "$ROLLBACK_FILE"
}

# Rollback all registered containers
rollback_containers() {
    local rollback_file="${1:-$ROLLBACK_FILE}"
    
    if [[ ! -f "$rollback_file" ]]; then
        log_warn "No rollback file found: $rollback_file"
        return 0
    fi
    
    log_warn "========================================="
    log_warn "ROLLBACK: Removing containers..."
    log_warn "========================================="
    
    local count=0
    while IFS='|' read -r vmid container_type timestamp; do
        if [[ -z "$vmid" ]]; then
            continue
        fi
        
        log_info "Rolling back container $vmid ($container_type)..."
        
        # Check if container exists
        if pct list 2>/dev/null | grep -q "^\s*$vmid\s"; then
            local status
            status=$(pct status "$vmid" 2>/dev/null | awk '{print $2}' || echo "unknown")
            
            if [[ "$status" == "running" ]]; then
                log_info "  Stopping container $vmid..."
                pct stop "$vmid" --timeout 30 2>/dev/null || pct stop "$vmid" --skiplock 2>/dev/null || true
                sleep 2
            fi
            
            log_info "  Destroying container $vmid..."
            if pct destroy "$vmid" --purge 2>/dev/null; then
                log_success "  Container $vmid removed"
                count=$((count + 1))
            else
                log_error "  Failed to remove container $vmid"
            fi
        else
            log_info "  Container $vmid does not exist, skipping"
        fi
    done < "$rollback_file"
    
    # Clean up rollback file
    rm -f "$rollback_file"
    
    log_warn "Rollback complete: $count container(s) removed"
    return 0
}

# Clean up rollback file on success
cleanup_rollback() {
    local rollback_file="${1:-$ROLLBACK_FILE}"
    if [[ -f "$rollback_file" ]]; then
        log_debug "Cleaning up rollback file: $rollback_file"
        rm -f "$rollback_file"
    fi
}

# Set trap for rollback on error
set_rollback_trap() {
    local rollback_file="${1:-$ROLLBACK_FILE}"
    trap "rollback_containers '$rollback_file'; exit 1" ERR
    log_debug "Rollback trap set for errors"
}

# Clear rollback trap
clear_rollback_trap() {
    trap - ERR
    log_debug "Rollback trap cleared"
}

