#!/usr/bin/env bash
# Run Streamlit in the background for cPanel/WHM deployment.
# Usage: ./scripts/start_streamlit.sh
# Stop:  kill $(cat streamlit.pid)

set -e
cd "$(dirname "$0")/.."
DIR="$(pwd)"

if [ -d "venv" ]; then
  source venv/bin/activate
fi

PORT="${PORT:-8501}"
LOG="${DIR}/streamlit.log"
PID="${DIR}/streamlit.pid"

if [ -f "$PID" ]; then
  OLD_PID=$(cat "$PID")
  if kill -0 "$OLD_PID" 2>/dev/null; then
    echo "Streamlit already running (PID $OLD_PID). Stop with: kill $OLD_PID"
    exit 1
  fi
  rm -f "$PID"
fi

nohup streamlit run app.py \
  --server.port="$PORT" \
  --server.address=127.0.0.1 \
  --server.headless=true \
  >> "$LOG" 2>&1 &
echo $! > "$PID"
echo "Streamlit started (PID $(cat $PID)). Log: $LOG"
