#!/usr/bin/env bash
# Force unlock Terraform state (use only if process is stuck)

set -e

LOCK_ID="a383e8af-e9b1-a8af-b7f0-36dd3001faa2"

echo "=== Force Unlock Terraform State ==="
echo ""
echo "⚠️  WARNING: This will force unlock the Terraform state"
echo "   Only use this if the Terraform process is stuck or not running"
echo ""
echo "Lock ID: $LOCK_ID"
echo ""

# Check if process is running
if ps aux | grep -i "terraform apply" | grep -v grep > /dev/null; then
  TERRAFORM_PID=$(ps aux | grep -i "terraform apply" | grep -v grep | awk '{print $2}' | head -1)
  echo "❌ ERROR: Terraform process is still running (PID: $TERRAFORM_PID)"
  echo "   Do not force unlock while process is active!"
  echo ""
  echo "Recommendation: Wait for process to complete or kill it first"
  echo "   To kill: kill $TERRAFORM_PID"
  exit 1
fi

echo "✅ No Terraform process found - safe to force unlock"
echo ""
read -p "Are you sure you want to force unlock? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "Cancelled"
  exit 1
fi

echo ""
echo "Force unlocking..."
cd terraform/well-architected/cloud-sovereignty
terraform force-unlock "$LOCK_ID"

echo ""
echo "✅ State unlocked"
echo ""
echo "You can now run terraform apply again"
