#!/bin/bash

# Startup script for Azan Peace Web/TV Application
# This script kills any process on port 3000 and starts the server

echo "🚀 Azan Peace Web/TV Startup Script"
echo "===================================="
echo ""

# Step 1: Kill any process running on port 3000
echo "🔍 Step 1: Checking if port 3000 is in use..."
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 successfully"
    sleep 2
else
    echo "✅ Port 3000 is available"
fi

echo ""
echo "🏗️  Step 2: Building application..."
# Build the application using webpack
npm run build

if [ $? -eq 0 ]; then
    echo "✅ Build completed successfully"
else
    echo "❌ Build failed!"
    exit 1
fi

echo ""
echo "🌐 Step 3: Starting production server..."
echo ""
echo "📍 Application will 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 ""

# Change to dist directory and serve
cd dist

# Start the server using npx serve
echo "⚡ Starting server on port 3000..."
npx serve -s . -l 3000

# Note: This will keep the terminal running. Use Ctrl+C to stop or use nohup-startup-web.sh for background execution
