#!/bin/bash

# Post-install/update specifics for Nextcloud — dispatched by appUpdateSpecifics.
#
# Nextcloud's official image runs `occ maintenance:install` on first boot from the
# NEXTCLOUD_ADMIN_USER + MYSQL_* env vars (so no web wizard). After that, wire
# Redis as the distributed cache + file-locking backend — this is the actual
# performance win for sync-heavy workloads. The redis container is on the same
# docker network as nextcloud-service, so the hostname `nextcloud-redis` resolves.
# Idempotent: `occ config:system:set` with the same value is a no-op.
appUpdateSpecifics_nextcloud() {
    # Wait for Nextcloud's first-boot init to complete (config.php exists +
    # occ reports installed). 60 × 2s = 2 minute timeout.
    local i=0
    while (( i++ < 60 )); do
        if runFileOp docker exec -u www-data nextcloud-service test -f /var/www/html/config/config.php 2>/dev/null \
           && runFileOp docker exec -u www-data nextcloud-service php occ status 2>/dev/null | grep -q 'installed: true'; then
            break
        fi
        sleep 2
    done
    if (( i >= 60 )); then
        isNotice "Nextcloud not yet initialized; skipping Redis wiring (re-run by reinstalling once it's up)"
        return 0
    fi

    isNotice "Wiring Redis caching + APCu into Nextcloud..."
    local rc=0
    # APCu = in-process local cache (cheap, fast). The fpm image ships with the
    # apcu PHP extension; under CLI mode it isn't enabled by default which makes
    # `occ` emit a harmless "memory cache not available" notice — Nextcloud's
    # graceful, the FPM worker still uses APCu fine.
    runFileOp docker exec -u www-data nextcloud-service php occ config:system:set memcache.local       --value '\OC\Memcache\APCu'  >/dev/null 2>&1 || rc=1
    runFileOp docker exec -u www-data nextcloud-service php occ config:system:set memcache.distributed --value '\OC\Memcache\Redis' >/dev/null 2>&1 || rc=1
    runFileOp docker exec -u www-data nextcloud-service php occ config:system:set memcache.locking     --value '\OC\Memcache\Redis' >/dev/null 2>&1 || rc=1
    runFileOp docker exec -u www-data nextcloud-service php occ config:system:set redis host          --value nextcloud-redis      >/dev/null 2>&1 || rc=1
    runFileOp docker exec -u www-data nextcloud-service php occ config:system:set redis port          --value 6379 --type=integer  >/dev/null 2>&1 || rc=1
    runFileOp docker exec -u www-data nextcloud-service php occ config:system:set filelocking.enabled --value true --type=boolean  >/dev/null 2>&1 || rc=1
    if [[ $rc -eq 0 ]]; then
        isSuccessful "Nextcloud → APCu (local) + Redis (distributed + file-locking) wired."
    else
        isNotice "Cache wiring had errors (non-fatal; Nextcloud still functions without it)"
    fi
}
