#!/bin/bash

# Nohup wrapper for startup-web.sh
# Runs the startup script in background with nohup

echo "🚀 Starting Azan Peace Web/TV in background mode"
echo "================================================"
echo ""

# Check if startup-web.sh exists
if [ ! -f "startup-web.sh" ]; then
    echo "❌ Error: startup-web.sh not found!"
    echo "Please make sure startup-web.sh exists in the current directory."
    exit 1
fi

# Make sure startup-web.sh is executable
chmod +x startup-web.sh

# Kill any existing process on port 3000 first
echo "🔍 Checking for existing processes on port 3000..."
PID=$(lsof -ti:3000)

if [ ! -z "$PID" ]; then
    echo "⚠️  Port 3000 is in use by process $PID"
    echo "🔪 Killing process..."
    kill -9 $PID
    echo "✅ Process killed"
    sleep 2
fi

# Create logs directory if it doesn't exist
mkdir -p logs

# Run startup-web.sh with nohup in background
echo ""
echo "🎬 Starting server in background..."
nohup ./startup-web.sh > logs/web-server.log 2>&1 &

SERVER_PID=$!

# Wait a moment to check if the process started successfully
sleep 3

if ps -p $SERVER_PID > /dev/null; then
    echo "✅ Server started successfully!"
    echo ""
    echo "📊 Process Information:"
    echo "   - PID: $SERVER_PID"
    echo "   - Log file: logs/web-server.log"
    echo ""
    echo "📍 Application should be available at:"
    echo "   - Local:    http://localhost:3000"
    echo "   - Network:  http://$(hostname -I | awk '{print $1}' 2>/dev/null || ipconfig getifaddr en0 2>/dev/null || echo 'localhost'):3000"
    echo ""
    echo "📋 Useful commands:"
    echo "   - View logs:        tail -f logs/web-server.log"
    echo "   - Stop server:      kill $SERVER_PID"
    echo "   - Check status:     ps -p $SERVER_PID"
    echo ""
else
    echo "❌ Failed to start server!"
    echo "📋 Check logs for details: cat logs/web-server.log"
    exit 1
fi
