#!/bin/bash
# Healthcheck for Nextcloud (app + cron + db + redis)

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

# Port is bound to the LAN interface only, so localhost won't answer.
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 nextcloud nextcloud-cron nextcloud-db nextcloud-redis; 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

# status.php must report installed:true (also proves DB connectivity)
if ! curl -sf --max-time 10 "http://${BIND_IP}:8220/status.php" | grep -q '"installed":true'; then
    echo "[FAIL] Nextcloud status.php not healthy on ${BIND_IP}:8220"
    exit 1
fi

echo "[OK] nextcloud is healthy"
exit 0
