#!/bin/bash
# Healthcheck for paperless-worker (OCR worker on SOLARIA -> broker @ PIHA)
#
# NOTE: SOLARIA is session-availability. This script reports the worker's
# health while the host is up; the worker being absent because SOLARIA is
# off is a normal state handled by the queue on PIHA, not a failure here.

# Container must be running
if ! docker ps --filter "name=paperless-worker" --filter "status=running" | grep -qw "paperless-worker"; then
    echo "[FAIL] paperless-worker container is not running"
    exit 1
fi

# Worker must answer a celery ping via the broker on PIHA — proves both
# broker connectivity (192.168.31.5:6380) and a live worker process.
if ! docker exec paperless-worker celery --app paperless inspect ping --timeout 10 2>/dev/null | grep -q "pong"; then
    echo "[FAIL] celery worker does not answer ping (broker @ 192.168.31.5:6380 unreachable or worker dead)"
    exit 1
fi

# NFS storage from PIHA must be readable AND writable (UID mapping check)
if ! docker exec paperless-worker sh -c 'touch /usr/src/paperless/media/.nfs-write-test && rm /usr/src/paperless/media/.nfs-write-test' 2>/dev/null; then
    echo "[FAIL] NFS media mount from PIHA is not writable (mount down or UID mismatch)"
    exit 1
fi

echo "[OK] paperless-worker is healthy"
exit 0
