#!/bin/bash
# Restart script - Nginx serves static files directly (NO VITE, NO PORT 5100)

echo "=== Restarting Church Music Platform ==="

# Kill old backend processes only
echo "Stopping old backend..."
lsof -ti:8080 2>/dev/null | xargs kill -9 2>/dev/null
sleep 2

# Rebuild frontend if code changed
echo "Rebuilding frontend..."
cd /media/pts/Website/Church_HOP_MusicData/new-site/frontend
npm run build

# Start backend
echo "Starting backend on port 8080..."
cd /media/pts/Website/Church_HOP_MusicData/new-site/backend
node server.js > /tmp/backend.log 2>&1 &
BACKEND_PID=$!
echo "Backend started (PID: $BACKEND_PID)"

# Reload Nginx to serve new build
echo "Reloading Nginx..."
sudo systemctl reload nginx

sleep 2

# Check status
echo ""
echo "=== Status Check ==="
if curl -s http://localhost:8080/api/lists > /dev/null 2>&1; then
    echo "✓ Backend responding on port 8080"
else
    echo "✗ Backend NOT responding"
    tail -20 /tmp/backend.log
fi

if curl -s https://houseofprayer.ddns.net > /dev/null 2>&1; then
    echo "✓ Nginx serving frontend"
else
    echo "✗ Nginx NOT serving"
    sudo nginx -t
fi

echo ""
echo "=== Site Running (Nginx direct serve - NO VITE) ==="
echo "Visit: https://houseofprayer.ddns.net"
echo ""
echo "Backend PID: $BACKEND_PID"
echo "Frontend: Nginx serves /media/pts/Website/Church_HOP_MusicData/new-site/frontend/dist"

