#!/bin/bash
# Fix VM lock issues on Proxmox nodes

set -e

VMID=${1:-100}
NODE=${2:-ml110-01}

echo "=== Fixing VM Lock for VMID $VMID on $NODE ==="
echo ""

# Load environment variables
if [ -f .env ]; then
    source .env
else
    echo "ERROR: .env file not found"
    exit 1
fi

echo "1. Checking VM status:"
echo "----------------------------------------"
sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "qm status $VMID" || echo "  ⚠️  Could not get VM status"

echo ""
echo "2. Checking for lock file:"
echo "----------------------------------------"
LOCK_FILE="/var/lock/qemu-server/lock-$VMID.conf"
if sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "test -f $LOCK_FILE"; then
    echo "  ⚠️  Lock file exists: $LOCK_FILE"
    echo "  Lock file contents:"
    sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "cat $LOCK_FILE" || echo "    Could not read lock file"
else
    echo "  ✅ No lock file found"
fi

echo ""
echo "3. Checking for stuck processes:"
echo "----------------------------------------"
PROCS=$(sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "ps aux | grep -E 'qm (start|stop|destroy|set)' | grep -v grep || echo ''")
if [ -n "$PROCS" ]; then
    echo "  ⚠️  Found processes:"
    echo "$PROCS" | sed 's/^/    /'
else
    echo "  ✅ No stuck processes found"
fi

echo ""
echo "4. Attempting to unlock VM:"
echo "----------------------------------------"
if sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "qm unlock $VMID" 2>&1; then
    echo "  ✅ Unlock command executed"
else
    echo "  ⚠️  Unlock command failed or VM not locked"
fi

echo ""
echo "5. Removing lock file (if exists):"
echo "----------------------------------------"
if sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "rm -f $LOCK_FILE" 2>&1; then
    echo "  ✅ Lock file removed (if it existed)"
else
    echo "  ⚠️  Could not remove lock file"
fi

echo ""
echo "6. Final VM status:"
echo "----------------------------------------"
sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "qm status $VMID" || echo "  ⚠️  Could not get VM status"

echo ""
echo "=== Done ==="
echo ""
echo "If issues persist, you may need to:"
echo "1. Stop the VM: qm stop $VMID"
echo "2. Wait a few seconds"
echo "3. Remove lock file: rm -f $LOCK_FILE"
echo "4. Retry the operation"

