#!/bin/bash
#
# Script to make a HAProxy capable of monitoring the Swift proxy backends status.
# This script checks the given scan target(auth endpoint) and also performs a Swift
# healthcheck via the given Swift endpoint with the given connect timeout.
# Reports an HTTP 200 OK, if all of the results are OK.
# If the healthcheck result was not OK or the Swift/Auth endpoint was not reachable,
# it would report an HTTP 503 Error.
#
# Author: Bogdan Dobrelya <bdobrelia@mirantis.com>
#

if [[ $1 == '-h' || $1 == '--help' || "$#" -ne 3 ]];then
    echo "Usage: $0 <local_swift_endpoint> <scan_target> <connect_timeout>"
    exit
fi

# Set options
url=${1%/} # remove trailing slash
scan_target=${2/:/ } # convert to netcat format
connect_timeout=$3
ncat=$(type -P nc)
curl=$(type -P curl)
waiting_time=3
pause=1
result='UNDEFINED'

# Scan for the target availability
while !($ncat -z ${scan_target}) && [ $waiting_time -gt 0 ]; do
    sleep $pause
    (( waiting_time -= pause ))
done

# Check for the swift healthcheck report via given endpoint url
if [[ $waiting_time -gt 0 ]]; then
    result=$($curl --silent --connect-timeout ${connect_timeout} --retry 1 -XGET ${url}/healthcheck)
fi

if [[ $result == 'OK' ]]; then
    # Swift healthcheck is OK and endpoint is reachable
    # return HTTP 200. Shell return-code is 0
    echo -en "HTTP/1.1 200 OK\r\n"
    echo -en "Content-Type: text/plain\r\n"
    echo -en "Connection: close\r\n"
    echo -en "Content-Length: 5\r\n"
    echo -en "\r\n"
    echo -en "OK.\r\n"
    sleep 0.1
    exit 0
else
    # Swift healthcheck failed or endpoint was not reachable,
    # return HTTP 503. Shell return-code is 1
    echo -en "HTTP/1.1 503 Service Unavailable\r\n"
    echo -en "Content-Type: text/plain\r\n"
    echo -en "Connection: close\r\n"
    echo -en "Content-Length: 8\r\n"
    echo -en "\r\n"
    echo -en "Error.\r\n"
    sleep 0.1
    exit 1
fi
