#!/usr/bin/env bash
# Provision Nextcloud user via occ (wizard VM112 calls this or OCS API)
# Usage: occ-provision-user.sh admin@dominio.com.br "Display Name" 25GB [password]
set -euo pipefail

STACK_DIR="${STACK_DIR:-/opt/vm116-nextcloud}"
USERID="${1:?userid (email)}"
DISPLAY="${2:-$USERID}"
QUOTA="${3:-25GB}"
PASSWORD="${4:-}"

cd "$STACK_DIR"
[[ -f .env ]] && set -a && source .env && set +a

if docker compose exec -T -u www-data nextcloud occ user:info "$USERID" &>/dev/null; then
  echo "User $USERID already exists"
  docker compose exec -T -u www-data nextcloud occ user:setting "$USERID" files quota "$QUOTA"
  exit 0
fi

if [[ -n "$PASSWORD" ]]; then
  docker compose exec -T -u www-data nextcloud occ user:add \
    --display-name="$DISPLAY" \
    --password-from-env \
    "$USERID" <<< "OC_PASS=$PASSWORD"
else
  docker compose exec -T -u www-data nextcloud occ user:add \
    --display-name="$DISPLAY" \
    --generate-password \
    "$USERID"
fi

docker compose exec -T -u www-data nextcloud occ user:setting "$USERID" files quota "$QUOTA"
echo "Provisioned: $USERID quota=$QUOTA"
