#!/bin/bash

# SmartINBOX Stop Script
# This script stops 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")"

# Check if server is running
if [ ! -f .pid ]; then
    error "Server is not running (no PID file found)"
    exit 1
fi

PID=$(cat .pid)
if ! ps -p $PID > /dev/null; then
    error "Server is not running (PID $PID not found)"
    rm .pid
    exit 1
fi

# Stop the server
info "Stopping SmartINBOX server with PID $PID..."
kill $PID
sleep 2

# Check if server was stopped
if ps -p $PID > /dev/null; then
    error "Failed to stop server gracefully, forcing termination..."
    kill -9 $PID
    sleep 1
fi

# Verify server is stopped
if ps -p $PID > /dev/null; then
    error "Failed to stop server"
    exit 1
else
    rm .pid
    success "Server stopped successfully"
fi