#!/bin/sh
set -eu

APP_DIR="${NFSE_APP_DIR:-/home/notanacional/www/masper-notanacional}"

cd "$APP_DIR"
. venv/bin/activate

set -a
. ./.env.prod
set +a

export PYTHONPATH="$APP_DIR/src"

PANEL_URL="http://${NFSE_WEB_HOST:-127.0.0.1}:${NFSE_WEB_PORT:-8080}/login"
PID_FILE="$APP_DIR/painel.pid"

if command -v curl >/dev/null 2>&1 && curl -fsS --max-time 5 "$PANEL_URL" >/dev/null 2>&1; then
  exit 0
fi

if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
  exit 0
fi

if pgrep -f "nf_nacional_web.app" >/dev/null 2>&1; then
  exit 0
fi

nohup python -m nf_nacional_web.app >> painel.log 2>&1 &
echo "$!" > "$PID_FILE"
