#!/bin/sh
set -e

OCC="php /var/www/html/occ"

# Wait for database
sleep 5

# Disable unnecessary apps
$OCC app:disable dashboard || true
$OCC app:disable weather_status || true
$OCC app:disable firstrunwizard || true
$OCC app:disable recommendations || true
$OCC app:disable survey_client || true

# Enable needed apps
$OCC app:enable files || true
$OCC app:enable calendar || true
$OCC app:enable contacts || true
$OCC app:enable groupfolders || true
$OCC app:enable user_oidc || true

# Configure OIDC (Authentik)
$OCC config:app:set user_oidc --value="1" allow_multiple_user_backends
$OCC user_oidc:provider Authentik \
    --clientid="${NC_OIDC_CLIENT_ID:-${OIDC_CLIENT_ID:-ulti-nextcloud}}" \
    --clientsecret="${NC_OIDC_CLIENT_SECRET:-${OIDC_CLIENT_SECRET:-changeme}}" \
    --discoveryuri="${NC_OIDC_DISCOVERY_URL:-${OIDC_DISCOVERY_URL:-http://nginx/auth/application/o/nextcloud/.well-known/openid-configuration}}" \
    --unique-uid=1 \
    --check-bearer=1 \
    --mapping-uid=preferred_username \
    --mapping-email=email \
    --mapping-displayname=name || true

# Performance tuning
$OCC config:system:set memcache.local --value='\OC\Memcache\APCu'
$OCC config:system:set memcache.distributed --value='\OC\Memcache\Redis'
$OCC config:system:set memcache.locking --value='\OC\Memcache\Redis'
$OCC config:system:set redis host --value='keydb'
$OCC config:system:set redis port --value='6379' --type=integer
$OCC config:system:set default_phone_region --value='FR'

# Disable theming/UI since we use headless
$OCC config:system:set skeletondirectory --value=''

echo "Nextcloud initialization complete."
