#!/bin/bash
# Force unlock Proxmox VM when qm unlock times out
# Usage: Run on Proxmox node: bash force-unlock-vm-proxmox.sh <VMID>

VMID="${1:-100}"

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

echo "=== Force Unlocking VM $VMID ==="
echo ""

# 1. Check for stuck processes
echo "1. Checking for stuck processes..."
STUCK_PROCS=$(ps aux | grep -E "qm|qemu" | grep "$VMID" | grep -v grep)
if [ -n "$STUCK_PROCS" ]; then
    echo "   Found stuck processes:"
    echo "$STUCK_PROCS" | while read line; do
        echo "   $line"
    done
else
    echo "   ✅ No stuck processes found"
fi
echo ""

# 2. Check lock file
echo "2. Checking lock file..."
if [ -f "/var/lock/qemu-server/lock-$VMID.conf" ]; then
    echo "   Lock file exists: /var/lock/qemu-server/lock-$VMID.conf"
    echo "   Lock file contents:"
    cat "/var/lock/qemu-server/lock-$VMID.conf" 2>/dev/null || echo "   (unreadable)"
    echo ""
else
    echo "   ✅ No lock file found"
    echo ""
fi

# 3. Kill stuck processes
echo "3. Killing stuck processes..."
pkill -9 -f "qm.*$VMID" 2>/dev/null && echo "   ✅ Killed qm processes" || echo "   ℹ️  No qm processes to kill"
pkill -9 -f "qemu.*$VMID" 2>/dev/null && echo "   ✅ Killed qemu processes" || echo "   ℹ️  No qemu processes to kill"
sleep 2
echo ""

# 4. Force remove lock file
echo "4. Force 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 (may need root)"
        exit 1
    fi
else
    echo "   ℹ️  Lock file already removed"
fi
echo ""

# 5. Verify lock is gone
echo "5. Verifying lock is cleared..."
if [ ! -f "/var/lock/qemu-server/lock-$VMID.conf" ]; then
    echo "   ✅ Lock file confirmed removed"
else
    echo "   ⚠️  Lock file still exists"
    exit 1
fi
echo ""

# 6. Check VM status
echo "6. Checking VM status..."
qm status "$VMID" 2>&1
echo ""

# 7. Try unlock again (should work now)
echo "7. Attempting unlock again..."
qm unlock "$VMID" 2>&1
UNLOCK_RESULT=$?
if [ $UNLOCK_RESULT -eq 0 ]; then
    echo "   ✅ VM unlocked successfully"
else
    echo "   ⚠️  Unlock still failed (exit code: $UNLOCK_RESULT)"
    echo "   This may indicate the VM is in use or another issue exists"
fi
echo ""

echo "=== Force Unlock Complete ==="
echo ""
echo "Next steps:"
echo "1. Check VM status: qm status $VMID"
echo "2. Check VM config: qm config $VMID"
echo "3. If needed, restart VM: qm start $VMID"

