#!/bin/zsh
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
export PYTHONUNBUFFERED=1
export UFORIA_DB_ENABLED="${UFORIA_DB_ENABLED:-true}"
export UFORIA_DB_DSN="${UFORIA_DB_DSN:-postgresql:///uforia?user=$USER}"
export UFORIA_DB_READ_MODE="${UFORIA_DB_READ_MODE:-db}"
export UFORIA_DB_WRITE_MODE="${UFORIA_DB_WRITE_MODE:-db}"

uv run uforia-admin ingest deribit-options-daemon --underlying BTC --poll-seconds 5 --grace-seconds 90 &
BTC_PID=$!

uv run uforia-admin ingest deribit-options-daemon --underlying ETH --poll-seconds 5 --grace-seconds 90 &
ETH_PID=$!

cleanup() {
  kill "$BTC_PID" "$ETH_PID" 2>/dev/null || true
}

trap cleanup INT TERM EXIT

while true; do
  if ! kill -0 "$BTC_PID" 2>/dev/null; then
    wait "$BTC_PID"
    exit $?
  fi
  if ! kill -0 "$ETH_PID" 2>/dev/null; then
    wait "$ETH_PID"
    exit $?
  fi
  sleep 5
done
