#!/bin/bash

# @file poll-http
#
# Copyright (C) Metaswitch Networks 2016
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# This script uses HTTP to poll a process and check whether it is healthy.
# Grab the command-line argument.
[ $# = 1 ] || { echo "Usage: poll-http <address>" >&2 ; exit 2 ; }
address=$1

. /etc/clearwater/config
[ -z $signaling_namespace ] || namespace_prefix="ip netns exec $signaling_namespace"

# Send HTTP request, writing the return code as well as the body to ensure we
# catch overload correctly. Check that the response is "OK200" or "503".
http_url=http://$address/ping
$namespace_prefix curl -f -g -m 2 -s $http_url --write-out %{http_code} 2> /tmp/poll-http.sh.stderr.$$ | tee /tmp/poll-http.sh.stdout.$$ | head -1 | egrep -q "(^OK200$|^503$)"
rc=$?

# Check the return code and log if appropriate.
if [ $rc != 0 ] ; then
  echo HTTP failed to $http_url   >&2
  echo "stderr was:"              >&2
  cat /tmp/poll-http.sh.stderr.$$ >&2
  echo "stdout was:"              >&2
  cat /tmp/poll-http.sh.stdout.$$ >&2
fi
rm -f /tmp/poll-http.sh.stderr.$$ /tmp/poll-http.sh.stdout.$$

exit $rc
