#!/bin/bash
# Kill stuck Proxmox task processes for a specific VM
# Usage: bash kill-stuck-proxmox-tasks.sh <VMID>

VMID="${1:-100}"

if [ -z "$VMID" ]; then
    echo "Usage: $0 <VMID>"
    echo "Example: $0 100"
    exit 1
fi

echo "=== Killing Stuck Proxmox Tasks for VM $VMID ==="
echo ""

# 1. Find all task processes for this VM
echo "1. Finding stuck processes..."
TASK_PROCS=$(ps aux | grep -E "task.*$VMID|qm.*$VMID|qemu.*$VMID" | grep -v grep)

if [ -z "$TASK_PROCS" ]; then
    echo "   ✅ No stuck processes found"
else
    echo "   Found processes:"
    echo "$TASK_PROCS" | while read line; do
        PID=$(echo "$line" | awk '{print $2}')
        CMD=$(echo "$line" | awk '{for(i=11;i<=NF;i++) printf "%s ", $i; print ""}')
        echo "   PID $PID: $CMD"
    done
    echo ""
    
    # Extract PIDs
    PIDS=$(echo "$TASK_PROCS" | awk '{print $2}' | tr '\n' ' ')
    
    # 2. Kill all task processes
    echo "2. Killing stuck processes..."
    for PID in $PIDS; do
        if kill -9 "$PID" 2>/dev/null; then
            echo "   ✅ Killed PID $PID"
        else
            echo "   ⚠️  Failed to kill PID $PID (may already be gone)"
        fi
    done
    echo ""
fi

# 3. Also try pkill for any remaining processes
echo "3. Cleaning up any remaining processes..."
pkill -9 -f "task.*$VMID" 2>/dev/null && echo "   ✅ Killed remaining task processes" || echo "   ℹ️  No remaining task processes"
pkill -9 -f "qm.*$VMID" 2>/dev/null && echo "   ✅ Killed remaining qm processes" || echo "   ℹ️  No remaining qm processes"
sleep 2
echo ""

# 4. Verify no processes remain
echo "4. Verifying no processes remain..."
REMAINING=$(ps aux | grep -E "task.*$VMID|qm.*$VMID|qemu.*$VMID" | grep -v grep)
if [ -z "$REMAINING" ]; then
    echo "   ✅ No processes remaining"
else
    echo "   ⚠️  Some processes still running:"
    echo "$REMAINING"
fi
echo ""

# 5. Remove lock file
echo "5. Removing lock file..."
if [ -f "/var/lock/qemu-server/lock-$VMID.conf" ]; then
    rm -f "/var/lock/qemu-server/lock-$VMID.conf"
    if [ ! -f "/var/lock/qemu-server/lock-$VMID.conf" ]; then
        echo "   ✅ Lock file removed"
    else
        echo "   ⚠️  Failed to remove lock file"
        exit 1
    fi
else
    echo "   ℹ️  Lock file already removed"
fi
echo ""

# 6. Final verification
echo "6. Final status check..."
echo "   Lock file: $([ ! -f "/var/lock/qemu-server/lock-$VMID.conf" ] && echo "✅ Removed" || echo "⚠️  Still exists")"
echo "   Processes: $([ -z "$(ps aux | grep -E 'task.*'$VMID'|qm.*'$VMID'|qemu.*'$VMID | grep -v grep)" ] && echo "✅ None" || echo "⚠️  Some remain")"
echo ""

echo "=== Cleanup Complete ==="
echo ""
echo "Next steps:"
echo "1. Try unlock: qm unlock $VMID"
echo "2. Check VM status: qm status $VMID"
echo "3. Check VM config: qm config $VMID"

