#!/bin/bash
# Healthcheck for Paperless-ngx (web + db + broker) on PIHA

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Ports are bound to the LAN interface only, so localhost won't answer.
# Read the bind IP from .env (same file compose uses for the port mapping).
if [ -f "$SCRIPT_DIR/.env" ]; then
    # shellcheck disable=SC1091
    source "$SCRIPT_DIR/.env"
fi
BIND_IP="${LAN_BIND_IP:-127.0.0.1}"

for c in paperless paperless-db paperless-broker; do
    if ! docker ps --filter "name=$c" --filter "status=running" | grep -qw "$c"; then
        echo "[FAIL] $c container is not running"
        exit 1
    fi
done

# Web UI must respond (login page redirect counts — follow it)
if ! curl -sfL --max-time 10 "http://${BIND_IP}:8210/" > /dev/null; then
    echo "[FAIL] paperless web is not responding on ${BIND_IP}:8210"
    exit 1
fi

# Redis broker must answer on the LAN bind (the SOLARIA worker depends on it).
# requirepass is set — auth with PAPERLESS_REDIS_PASSWORD from .env.
if ! docker exec paperless-broker redis-cli -h "${BIND_IP}" -p 6380 -a "${PAPERLESS_REDIS_PASSWORD}" --no-auth-warning ping | grep -q PONG; then
    echo "[FAIL] redis broker is not answering on ${BIND_IP}:6380 (worker@SOLARIA cannot connect)"
    exit 1
fi

echo "[OK] paperless is healthy"
exit 0
