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

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

: "${BLOGGER_API_URL:=${BLOGGER_API_BASE_URL:-http://localhost}}"
: "${BLOGGER_WEB_URL:=${BLOGGER_WEB_BASE_URL:-http://localhost}}"

BLOGGER_API_URL=${BLOGGER_API_URL%/}
BLOGGER_WEB_URL=${BLOGGER_WEB_URL%/}

if ! command -v curl >/dev/null 2>&1; then
  echo "curl is required for smoke tests" >&2
  exit 1
fi

LAST_STATUS=''
LAST_BODY=''

function fail() {
  echo "FAIL: $*" >&2
  exit 1
}

function section() {
  echo
  printf "== %s ==\n" "$1"
}

function curl_capture() {
  local method=$1
  local url=$2
  shift 2

  local tmp
  tmp=$(mktemp)
  if ! LAST_STATUS=$(curl -sS -w '%{http_code}' -o "$tmp" -X "$method" "$@" "$url"); then
    rm -f "$tmp"
    fail "curl failed to reach $url"
  fi

  LAST_BODY=$(cat "$tmp")
  rm -f "$tmp"
}

function assert_status() {
  local expected=$1
  if [[ "$LAST_STATUS" != "$expected" ]]; then
    fail "Expected HTTP $expected but got $LAST_STATUS (body: $LAST_BODY)"
  fi
}

function assert_body_contains() {
  local expected=$1
  if ! grep -qF "$expected" <<< "$LAST_BODY"; then
    fail "Expected response to contain '$expected' but got: $LAST_BODY"
  fi
}
