#!/bin/bash

# Backend Stop Script for cPanel
# This script stops the FastAPI backend

BACKEND_DIR="/home/$(whoami)/backend"
PID_FILE="$BACKEND_DIR/backend.pid"

if [ ! -f "$PID_FILE" ]; then
    echo "Backend is not running (no PID file found)"
    exit 1
fi

PID=$(cat "$PID_FILE")

if ! ps -p "$PID" > /dev/null 2>&1; then
    echo "Backend is not running (stale PID file)"
    rm "$PID_FILE"
    exit 1
fi

echo "Stopping backend (PID: $PID)..."
kill "$PID"

# Wait for process to stop
for i in {1..10}; do
    if ! ps -p "$PID" > /dev/null 2>&1; then
        echo "Backend stopped successfully"
        rm "$PID_FILE"
        exit 0
    fi
    sleep 1
done

# Force kill if still running
echo "Force killing backend..."
kill -9 "$PID"
rm "$PID_FILE"
echo "Backend stopped (force kill)"
