#!/usr/bin/env bash
# kb-watch - re-index 2dph when corpus files change.
#
#   kb-watch [dir...] [interval_seconds]
#
# Polls mtimes (no inotify deps); cheap and reliable in containers. Defaults:
# dirs = /corpus (compose) or . ; interval = 30s.
set -euo pipefail

DEFAULT_DIRS="${KB_WATCH_DIRS:-/corpus}"
DIRS=("$@")
[[ ${#DIRS[@]} -eq 0 ]] && DIRS=(${DEFAULT_DIRS})
INTERVAL="${KB_WATCH_INTERVAL:-30}"

index() { "${KB_PY:-python3}" /app/bin/kb/index; }

LAST_STAMP=""
while true; do
  STAMP=$(find "${DIRS[@]}" -type f -newermt "-${INTERVAL} seconds" 2>/dev/null \
    | head -1 | md5sum)
  if [[ -n "$STAMP" && "$STAMP" != "$LAST_STAMP" ]]; then
    echo "kb-watch: changes detected, re-indexing" >&2
    index || echo "kb-watch: index failed; will retry" >&2
    LAST_STAMP="$STAMP"
  fi
  sleep "$INTERVAL"
done