#!/usr/bin/env bash
# Run the EKOS PDF searcher inside a transient systemd user-unit with
# CPU + memory caps. All extra args are forwarded to 02_search_pdfs.py.
#
# Profile env vars (override before invocation):
#   EKOS_CPU_QUOTA   default 300%   (3 cores)
#   EKOS_MEM_MAX     default 3G
#   EKOS_UNIT        default ekos-search-<timestamp>
#
# Examples:
#   bash scripts/run_capped.sh --slug cumhuriyet --priority-only --year-to 1931 --workers 2
#   EKOS_CPU_QUOTA=500% EKOS_MEM_MAX=4G bash scripts/run_capped.sh --priority-only --workers 4
#
# Monitor:
#   systemctl --user status <unit>
#   journalctl --user -u <unit> -f
#   systemctl --user stop <unit>

set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PY="${HERE}/.venv/bin/python"
SCRIPT="${HERE}/scripts/02_search_pdfs.py"

CPU_QUOTA="${EKOS_CPU_QUOTA:-300%}"
MEM_MAX="${EKOS_MEM_MAX:-3G}"
UNIT="${EKOS_UNIT:-ekos-search-$(date +%Y%m%d-%H%M%S)}"

if [[ ! -x "$PY" ]]; then
  echo "venv not found: $PY" >&2
  echo "create with: cd $HERE && python3 -m venv .venv && .venv/bin/pip install -r scripts/requirements.txt" >&2
  exit 1
fi

echo "Unit:      $UNIT"
echo "CPUQuota:  $CPU_QUOTA"
echo "MemoryMax: $MEM_MAX"
echo "Forward:   $*"
echo

exec systemd-run --user \
  --unit="$UNIT" \
  --working-directory="$HERE" \
  -p "CPUQuota=$CPU_QUOTA" \
  -p "MemoryMax=$MEM_MAX" \
  -p "MemorySwapMax=1G" \
  -p "Nice=10" \
  -p "IOWeight=50" \
  --setenv=PYTHONUNBUFFERED=1 \
  "$PY" "$SCRIPT" "$@"
