#!/bin/sh
# Container healthcheck for php-fpm (Phase 2).
#
# Asks the FPM pool itself whether it can still serve a FastCGI request, which
# is strictly stronger than checking that PID 1 exists: a pool with every worker
# wedged still has a live master process.
#
# Requires `ping.path = /ping` in the pool config and the `fcgi` package.

set -eu

FPM_HOST="127.0.0.1"
FPM_PORT="9000"
PING_PATH="/ping"
EXPECTED="pong"

RESPONSE=$(
    env -i \
        SCRIPT_NAME="${PING_PATH}" \
        SCRIPT_FILENAME="${PING_PATH}" \
        REQUEST_METHOD=GET \
        cgi-fcgi -bind -connect "${FPM_HOST}:${FPM_PORT}" 2>/dev/null
) || {
    echo "healthcheck: cannot connect to php-fpm on ${FPM_HOST}:${FPM_PORT}" >&2
    exit 1
}

case "${RESPONSE}" in
    *"${EXPECTED}"*)
        exit 0
        ;;
    *)
        echo "healthcheck: unexpected response from ${PING_PATH}: ${RESPONSE}" >&2
        exit 1
        ;;
esac
