#!/usr/bin/env bash

set -e

cd "$(dirname "$0")/.."

if [[ -n "$1" && "$1" != '--'* ]]; then
  URL="$1"
  shift
else
  URL="$(grep 'openapi_spec_url' .stats.yml | cut -d' ' -f2)"
fi

# Check if the URL is empty
if [ -z "$URL" ]; then
  echo "Error: No OpenAPI spec path/url provided or found in .stats.yml"
  exit 1
fi

echo "==> Starting mock server with URL ${URL}"

# Run steady mock on the given spec
if [ "$1" == "--daemon" ]; then
  # Pre-install the package so the download doesn't eat into the startup timeout
  npm exec --package=@stdy/cli@0.19.7 -- steady --version

  npm exec --package=@stdy/cli@0.19.7 -- steady --host 127.0.0.1 -p 4010 --validator-form-array-format=brackets --validator-query-array-format=brackets --validator-form-object-format=brackets --validator-query-object-format=brackets "$URL" &> .stdy.log &

  # Wait for server to come online via health endpoint (max 30s)
  echo -n "Waiting for server"
  attempts=0
  while ! curl --silent --fail "http://127.0.0.1:4010/_x-steady/health" >/dev/null 2>&1; do
    if ! kill -0 $! 2>/dev/null; then
      echo
      cat .stdy.log
      exit 1
    fi
    attempts=$((attempts + 1))
    if [ "$attempts" -ge 300 ]; then
      echo
      echo "Timed out waiting for Steady server to start"
      cat .stdy.log
      exit 1
    fi
    echo -n "."
    sleep 0.1
  done

  echo
else
  npm exec --package=@stdy/cli@0.19.7 -- steady --host 127.0.0.1 -p 4010 --validator-form-array-format=brackets --validator-query-array-format=brackets --validator-form-object-format=brackets --validator-query-object-format=brackets "$URL"
fi
