#!/bin/bash

# 1. Navigate to the application root directory
cd /home/gebhyibo/api.urlml.olien.my.id/pys || { echo "Directory not found"; exit 1; }

# 2. Ensure the logs directory exists so redirection doesn't fail
mkdir -p logs

# 3. Kill the old, cached uvicorn process using the stored PID
PID_FILE="logs/uvicorn.pid"
if [ -f "$PID_FILE" ]; then
    OLD_PID=$(cat "$PID_FILE")
    if kill -0 "$OLD_PID" 2>/dev/null; then
        echo "Stopping old Uvicorn process (PID: $OLD_PID)..."
        kill "$OLD_PID"
        sleep 2 # Give it a moment to release the port
        
        # Force-kill if it's still hanging
        if kill -0 "$OLD_PID" 2>/dev/null; then
            echo "Process didn't stop. Force killing PID $OLD_PID..."
            kill -9 "$OLD_PID"
        fi
    else
        echo "Old PID file found, but process $OLD_PID is not running."
    fi
else
    # Fallback safety: kill any uvicorn process running on your port if PID file is missing
    echo "Checking for any rogue processes on port 8765..."
    fuser -k 8765/tcp 2>/dev/null
fi

# 4. Activate the virtual environment
source /home/gebhyibo/virtualenv/api.urlml.olien.my.id/pys/3.10/bin/activate

# 5. Set environment variables to prevent thread contention/leakage
export OPENBLAS_NUM_THREADS=1
export OMP_NUM_THREADS=1
export MKL_NUM_THREADS=1

# 6. Launch the updated application in the background using nohup
echo "Starting fresh Uvicorn instance..."
nohup uvicorn api:app --host 127.0.0.1 --port 8765 --log-level info >> logs/uvicorn.log 2>&1 &

# 7. Immediately save the new process ID
echo $! > "$PID_FILE"
echo "Uvicorn started successfully with PID: $!"