#!/bin/bash

# Fix script for 503 Service Unavailable error
# This script fixes the corrupted Next.js installation issue

echo "========================================="
echo "Fixing 503 Service Unavailable Error"
echo "========================================="
echo ""

# Navigate to project directory (adjust path as needed)
cd /home/betruixl/trustrank.live || exit 1

echo "Step 1: Removing corrupted .next build directory..."
rm -rf .next
echo "✓ .next directory removed"

echo ""
echo "Step 2: Removing node_modules cache..."
rm -rf node_modules/.cache 2>/dev/null
echo "✓ Cache cleared"

echo ""
echo "Step 3: Reinstalling Next.js to fix corrupted installation..."
# Activate virtual environment if using nodevenv
if [ -f "nodevenv/bin/activate" ]; then
    source nodevenv/bin/activate
    echo "✓ Virtual environment activated"
fi

# Reinstall Next.js specifically
npm uninstall next
npm install next@16.0.3 --save
echo "✓ Next.js reinstalled"

echo ""
echo "Step 4: Rebuilding the application..."
npm run build

if [ $? -eq 0 ]; then
    echo ""
    echo "✓ Build completed successfully!"
    echo ""
    echo "Step 5: Restarting the server..."
    echo "Please restart your server using your hosting control panel or:"
    echo "  - pm2 restart all"
    echo "  - systemctl restart your-service"
    echo "  - Or use your hosting's restart command"
else
    echo ""
    echo "✗ Build failed. Please check the errors above."
    exit 1
fi

echo ""
echo "========================================="
echo "Fix completed!"
echo "========================================="

