#!/bin/bash

echo "=== Restarting Backend Server ==="

# Kill existing backend process
echo "Stopping existing backend..."
pkill -f "node.*server.js" 2>/dev/null
sleep 2

# Change to backend directory
cd /media/pts/Website/Church_HOP_MusicData/new-site/backend || exit 1

# Start backend
echo "Starting backend server on port 8080..."
nohup node server.js > /tmp/backend.log 2>&1 &
BACKEND_PID=$!

echo "Backend started with PID: $BACKEND_PID"
sleep 3

# Verify it's running
if ps -p $BACKEND_PID > /dev/null 2>&1; then
    echo "✅ Backend is running!"
    
    # Test health endpoint
    echo ""
    echo "Testing health endpoint..."
    curl -s http://localhost:8080/health || echo "Health check failed"
else
    echo "❌ Backend failed to start. Check logs:"
    tail -20 /tmp/backend.log
    exit 1
fi

echo ""
echo "Backend restart complete."
echo "View logs: tail -f /tmp/backend.log"
