#!/bin/bash

# Quick fix for bcrypt "invalid ELF header" error
# Run this on your Linux production server

echo "🔧 Fixing bcrypt native binding issue..."
echo "=========================================="
echo ""

APP_NAME="luckychit-api"

# Get current directory
BACKEND_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$BACKEND_DIR"

echo "📍 Working directory: $BACKEND_DIR"
echo ""

# Stop PM2 if running
if pm2 describe $APP_NAME > /dev/null 2>&1; then
    echo "⏸️  Stopping PM2 process: $APP_NAME"
    pm2 stop $APP_NAME
else
    echo "ℹ️  PM2 process not running"
fi
echo ""

# Remove node_modules
if [ -d "node_modules" ]; then
    echo "🗑️  Removing old node_modules..."
    rm -rf node_modules
else
    echo "ℹ️  node_modules not found (already clean)"
fi

# Remove package-lock.json
if [ -f "package-lock.json" ]; then
    echo "🗑️  Removing package-lock.json..."
    rm -f package-lock.json
else
    echo "ℹ️  package-lock.json not found"
fi
echo ""

# Reinstall dependencies
echo "📦 Reinstalling dependencies on Linux..."
echo "   This will rebuild native bindings (bcrypt, etc.)"
echo ""
npm install
echo ""

# Check if installation was successful
if [ $? -eq 0 ]; then
    echo "✅ Dependencies installed successfully!"
    echo ""
    
    # Restart PM2
    if pm2 list | grep -q $APP_NAME; then
        echo "🔄 Restarting PM2 process..."
        pm2 restart $APP_NAME
        pm2 save
        echo ""
        
        # Show status
        echo "📊 Current status:"
        pm2 list
        echo ""
        
        echo "✅ Fix complete! Your app should be running now."
        echo ""
        echo "📝 Check logs with: pm2 logs $APP_NAME"
        echo "📊 Monitor with: pm2 monit"
    else
        echo "⚠️  PM2 process not found. Start it manually:"
        echo "   pm2 start ecosystem.config.js --env production"
    fi
else
    echo "❌ Installation failed. Check the errors above."
    exit 1
fi

echo ""
echo "=========================================="
echo "🎉 Done!"

