#!/bin/bash
# Exit immediately if a command exits with a non-zero status.
set -e
# --- Configuration ---
BACKEND_PORT=8000
FRONTEND_PORT=3000
# --- Dependency Check ---
check_dependencies() {
if ! command -v lsof &> /dev/null; then
echo "[DEV_SCRIPT] lsof not found. Attempting to install..."
if command -v apt-get &> /dev/null; then
sudo apt-get update && sudo apt-get install -y lsof
else
echo "[ERROR] lsof is missing and apt-get not found. Please install lsof manually."
exit 1
fi
fi
}
# Function to kill processes based on PID files or port usage
kill_existing() {
echo "[DEV_SCRIPT] Cleaning up preexisting processes..."
# 1. Kill by PID files if they exist
for pid_file in backend/uvicorn.pid backend/worker.pid; do
if [ -f "$pid_file" ]; then
PID=$(cat "$pid_file")
if ps -p "$PID" > /dev/null; then
echo "Killing process $PID from $pid_file"
kill "$PID" || kill -9 "$PID"
fi
rm "$pid_file"
fi
done
# 2. Port Cleanup (Insurance): Kill anything still holding the ports
for port in $BACKEND_PORT $FRONTEND_PORT; do
PID_ON_PORT=$(lsof -t -i:"$port" || true)
if [ -n "$PID_ON_PORT" ]; then
echo "Port $port is busy (PID: $PID_ON_PORT). Cleaning up..."
echo "$PID_ON_PORT" | xargs kill -9 2>/dev/null || true
fi
done
}
# Function to clean up background processes on exit
cleanup() {
echo ""
echo "[DEV_SCRIPT] Shutting down servers..."
kill_existing
echo "[DEV_SCRIPT] Cleanup complete."
}
# Trap signals (Ctrl+C, termination)
trap cleanup EXIT
# --- INITIALIZATION ---
check_dependencies
kill_existing
# --- Backend Setup ---
echo "[DEV_SCRIPT] Setting up and starting backend server..."
cd backend
if [ ! -d "venv" ]; then
echo "[DEV_SCRIPT] Creating Python virtual environment..."
python3 -m venv venv
fi
source venv/bin/activate
# Use python -m pip to ensure the venv's pip is used
echo "[DEV_SCRIPT] Updating pip and installing requirements..."
python3 -m pip install --upgrade pip
python3 -m pip install -r requirements.txt
echo "[DEV_SCRIPT] Starting backend server on http://localhost:$BACKEND_PORT..."
python3 -m uvicorn app.main:app --host 0.0.0.0 --port $BACKEND_PORT --reload &
echo $! > uvicorn.pid
echo "[DEV_SCRIPT] Starting worker process..."
python3 app/worker.py &
echo $! > worker.pid
cd ..
# --- Frontend Setup ---
echo ""
echo "[DEV_SCRIPT] Setting up and starting frontend server..."
cd frontend
# Ensure npm exists
if ! command -v npm &> /dev/null; then
echo "[ERROR] npm is not installed. Please install Node.js and npm."
exit 1
fi
npm install
echo "[DEV_SCRIPT] Starting frontend server on http://localhost:$FRONTEND_PORT..."
echo "[DEV_SCRIPT] Press Ctrl+C to stop both servers."
# Run in foreground
npm start