#!/bin/bash

# SmartINBOX Start Script
# This script starts the SmartINBOX server

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Print info message
info() {
    echo -e "${YELLOW}INFO: $1${NC}"
}

# Print success message
success() {
    echo -e "${GREEN}SUCCESS: $1${NC}"
}

# Print error message
error() {
    echo -e "${RED}ERROR: $1${NC}"
}

# Change to script directory
cd "$(dirname "$0")"

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

# Check if server is already running
if [ -f .pid ]; then
    PID=$(cat .pid)
    if ps -p $PID > /dev/null; then
        error "Server is already running with PID $PID"
        exit 1
    else
        info "Removing stale PID file"
        rm .pid
    fi
fi

# Start the server
info "Starting SmartINBOX server..."
nohup node server.js > logs/server.out 2> logs/server.err &
echo $! > .pid
success "Server started with PID $(cat .pid)"
info "Logs are available in logs/server.out and logs/server.err"
info "To stop the server, run: ./stop.sh"