#!/bin/bash
# Fix Passenger lock file permissions
# Run this on the server to resolve "Can't acquire lock" error

echo "=========================================="
echo "FIXING PASSENGER LOCK FILE ISSUES"
echo "=========================================="
echo ""

# Navigate to app directory
cd ~/product-finder

# Remove any stale lock files
echo "🧹 Cleaning stale lock files..."
if [ -d "tmp" ]; then
    rm -rf tmp/*
    echo "   ✓ tmp directory cleaned"
else
    echo "   ⚠️  tmp directory doesn't exist - will create it"
fi

# Create tmp directory with correct permissions
echo ""
echo "📁 Setting up tmp directory..."
mkdir -p tmp
chmod 755 tmp
echo "   ✓ tmp directory created with 755 permissions"

# Create restart file
echo ""
echo "🔄 Restarting Passenger..."
touch tmp/restart.txt
chmod 644 tmp/restart.txt
echo "   ✓ tmp/restart.txt created"

# Set correct permissions for app files
echo ""
echo "🔒 Setting file permissions..."
chmod 755 .
chmod 644 passenger_wsgi.py
chmod 644 app.py
chmod 644 .htaccess
chmod -R 755 data 2>/dev/null || mkdir -p data && chmod 755 data
chmod -R 755 templates
chmod -R 755 static 2>/dev/null || true
echo "   ✓ File permissions set"

# Show current tmp directory status
echo ""
echo "📊 Current tmp directory status:"
ls -la tmp/
echo ""

echo "=========================================="
echo "✓ LOCK FILE ISSUE FIXED"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Wait 30 seconds for Passenger to restart"
echo "2. Test: https://columbiawindows.com/product-finder/"
echo ""
echo "If still failing, check error log:"
echo "tail -50 ~/logs/error_log"
echo ""
