#!/usr/bin/env bash

set -e

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

if [[ -n "$1" && "$1" != '--'* ]]; then
  URL="$1"
  shift
elif [[ -f .castiron.stats.yml && -f api_reference/openapi.transformed.yml ]]; then
  URL="api_reference/openapi.transformed.yml"
  EXPECTED_HASH="$(awk '$1 == "openapi_transformed_spec_hash:" { print $2; exit }' .castiron.stats.yml)"
  ACTUAL_HASH="$(node -e 'process.stdout.write(require("node:crypto").createHash("md5").update(require("node:fs").readFileSync(process.argv[1])).digest("hex"))' "$URL")"

  if [[ -z "$EXPECTED_HASH" || "$ACTUAL_HASH" != "$EXPECTED_HASH" ]]; then
    echo "Error: Local OpenAPI specification does not match generation metadata" >&2
    exit 1
  fi
else
  echo "Error: No OpenAPI spec path/url provided and local Castiron generation metadata is unavailable" >&2
  exit 1
fi

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

STEADY="$(./scripts/steady/install --print-executable)"

STEADY_ARGS=(
  --host 127.0.0.1
  -p 4010
  --validator-query-array-format=brackets
  --validator-form-array-format=brackets
  --validator-query-object-format=brackets
  --validator-form-object-format=brackets
  "$URL"
)

# Run steady mock on the given spec.
if [ "$1" == "--daemon" ]; then
  "$STEADY" "${STEADY_ARGS[@]}" &> .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
  "$STEADY" "${STEADY_ARGS[@]}"
fi
