#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
STATE_DIR="${KORA_SURFPOOL_STATE_DIR:-"${ROOT_DIR}/.secrets/kora-surfpool"}"
RUNTIME_ENV_FILE="${STATE_DIR}/runtime.env"

if [ "${1:-}" = "--" ]; then
  shift
fi

if [ "$#" -eq 0 ]; then
  echo "Usage: pnpm kora:surfpool:run -- <command> [args...]" >&2
  exit 1
fi

configure_local_custody() {
  if [ "${SDP_INTEGRATION_CUSTODY_PROVIDER}" != "local" ]; then
    return
  fi

  export SIGNING_PROVIDER=local
  export SIGNING_PROVIDERS=local

  if [ -n "${KORA_SURFPOOL_CUSTODY_PRIVATE_KEY:-}" ]; then
    export CUSTODY_PRIVATE_KEY="${KORA_SURFPOOL_CUSTODY_PRIVATE_KEY}"
  elif [ -z "${CUSTODY_PRIVATE_KEY:-}" ]; then
    echo "Generating test-only local custody signer."
    CUSTODY_PRIVATE_KEY="$(pnpm --silent --filter @sdp/api keygen:local --quiet)"
    export CUSTODY_PRIVATE_KEY
  fi
}

cleanup() {
  "${ROOT_DIR}/scripts/kora-surfpool/down.sh"
}
trap cleanup EXIT

if [ -n "${KORA_SURFPOOL_KORA_RPC_URL:-}" ]; then
  export KORA_RPC_URL="${KORA_SURFPOOL_KORA_RPC_URL}"
elif [ "${DOPPLER_RUN_ACTIVE:-}" = "1" ]; then
  export KORA_RPC_URL="http://127.0.0.1:18080"
else
  export KORA_RPC_URL="${KORA_RPC_URL:-http://127.0.0.1:18080}"
fi

export FEE_PAYMENT_PROVIDER="${FEE_PAYMENT_PROVIDER:-kora}"
export RUN_INTEGRATION_TESTS="${RUN_INTEGRATION_TESTS:-true}"
export KORA_SURFPOOL_SHIM="${KORA_SURFPOOL_SHIM:-true}"
export SDP_INTEGRATION_CUSTODY_PROVIDER="${SDP_INTEGRATION_CUSTODY_PROVIDER:-local}"
configure_local_custody
export SOLANA_RPC_DEFAULT_PROVIDER=default
export DATABASE_URL="${KORA_SURFPOOL_DATABASE_URL:-${DATABASE_URL:-postgresql://sdp:sdp@127.0.0.1:5432/sdp}}"
export REDIS_URL="${REDIS_URL:-redis://127.0.0.1:6379}"

"${ROOT_DIR}/scripts/kora-surfpool/up.sh"
if [ -f "${RUNTIME_ENV_FILE}" ]; then
  set -a
  # shellcheck disable=SC1090
  . "${RUNTIME_ENV_FILE}"
  set +a
fi

export DATABASE_URL="${KORA_SURFPOOL_DATABASE_URL:-${DATABASE_URL:-postgresql://sdp:sdp@127.0.0.1:5432/sdp}}"
export REDIS_URL="${REDIS_URL:-redis://127.0.0.1:6379}"
export SDP_INTEGRATION_CUSTODY_PROVIDER="${SDP_INTEGRATION_CUSTODY_PROVIDER:-local}"
configure_local_custody
export SOLANA_RPC_DEFAULT_PROVIDER=default

"$@"
