#!/bin/sh
# Healthcheck script — tests that Nginx + PHP-FPM are serving responses.
# Used by Docker/Railway to determine container health.
#
# Exit 0 = healthy, exit 1 = unhealthy.

set -e

TIMEOUT=5
URL="http://127.0.0.1/up"

# Attempt the request; capture HTTP status code
HTTP_STATUS=$(curl --silent --max-time "$TIMEOUT" --output /dev/null \
    --write-out "%{http_code}" "$URL" 2>/dev/null || echo "000")

if [ "$HTTP_STATUS" = "200" ]; then
    echo "[healthcheck] OK — /up returned HTTP 200"
    exit 0
fi

# Fall back to checking the root path if /up isn't defined
HTTP_STATUS_ROOT=$(curl --silent --max-time "$TIMEOUT" --output /dev/null \
    --write-out "%{http_code}" "http://127.0.0.1/" 2>/dev/null || echo "000")

if [ "$HTTP_STATUS_ROOT" = "200" ] || [ "$HTTP_STATUS_ROOT" = "302" ]; then
    echo "[healthcheck] OK — / returned HTTP $HTTP_STATUS_ROOT"
    exit 0
fi

echo "[healthcheck] FAIL — /up returned HTTP $HTTP_STATUS, / returned HTTP $HTTP_STATUS_ROOT"
exit 1
