#!/usr/bin/env bash

# Important: in this script we do not use the unofficial bash mode,
# because we actually rely on a proper failing status of curl

url="$1"

if [ -z "${url}" ]; then
  (>&2 echo "testUrl: Please provide an URL as the first parameter")
  exit 1
fi

curlHTTPStatus=$(curl --silent --output /dev/null -H "Origin: http://docker.localhost" --head --write-out "%{http_code}" "${url}")
curlExitStatus=$?

if [[ "${curlExitStatus}" -ne "0" ]]; then
  (>&2 echo "testUrl (${url}): curl returned exit code ${curlExitStatus} (https://curl.haxx.se/libcurl/c/libcurl-errors.html), unhealthy")
  exit 1
elif [[ "${curlHTTPStatus}" -ne "200" ]]; then
  (>&2 echo "testUrl (${url}): HEAD on returned ${curlHTTPStatus} != 200, unhealthy")
  exit 1
fi

echo "testUrl (${url}): healthy"
exit 0
