#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "$SCRIPT_DIR/common.sh"

WAIT_FIRST_RUN=1
TIMEOUT_SECS=""

usage() {
  cat <<'USAGE'
Usage: ./scripts/start.sh [--no-wait-first-run] [--timeout-secs N]

Start ours RP. If no successful run exists, wait for the first snapshot to succeed
before starting metrics, Prometheus and Grafana.
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --no-wait-first-run)
      WAIT_FIRST_RUN=0
      shift
      ;;
    --timeout-secs)
      TIMEOUT_SECS="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      die "unknown option: $1"
      ;;
  esac
done

load_env
assert_arch_compatibility
create_data_dirs
timeout_secs="${TIMEOUT_SECS:-$FIRST_RUN_WAIT_TIMEOUT_SECS}"
before_latest="$(latest_run_dir || true)"
had_success=0
if has_success_run; then
  had_success=1
fi

log "starting core soak service"
compose_cmd --profile core up -d ours-rp-soak

if [[ "$had_success" == "0" && "$WAIT_FIRST_RUN" == "1" ]]; then
  log "no previous successful run found; waiting for first run timeout=${timeout_secs}s"
  wait_for_new_success_run "$before_latest" "$timeout_secs"
fi

log "starting metrics and monitor services"
compose_cmd --profile sidecar --profile monitor up -d artifact-metrics prometheus grafana
"$SCRIPT_DIR/status.sh" --brief || true
