#!/usr/bin/env bash
# Install Nextcloud stack on target VM (Spec 034)
set -euo pipefail

STACK_DIR="${STACK_DIR:-/opt/vm116-nextcloud}"
REPO_SRC="${REPO_SRC:-$(cd "$(dirname "$0")/.." && pwd)}"

if [[ ! -f "$REPO_SRC/docker-compose.yml" ]]; then
  echo "docker-compose.yml not found in $REPO_SRC" >&2
  exit 1
fi

mkdir -p "$STACK_DIR"
rsync -a --delete \
  --exclude '.env' \
  "$REPO_SRC/" "$STACK_DIR/"

cd "$STACK_DIR"
if [[ ! -f .env ]]; then
  cp .env.example .env
  echo "Created $STACK_DIR/.env — edit NC_ADMIN_PASSWORD and POSTGRES_PASSWORD before continuing."
  exit 1
fi

docker compose --env-file .env pull
docker compose --env-file .env up -d

sleep 15
docker compose exec -T -u www-data nextcloud occ status
docker compose exec -T -u www-data nextcloud occ config:system:set overwritehost --value="${NC_DOMAIN:-cloud.ligbox.com.br}"
docker compose exec -T -u www-data nextcloud occ config:system:set overwriteprotocol --value="https"
docker compose exec -T -u www-data nextcloud occ config:system:set trusted_proxies 0 --value="10.10.10.114"
docker compose exec -T -u www-data nextcloud occ app:enable provisioning_api 2>/dev/null || true

echo "Nextcloud OK — http://127.0.0.1:${NC_HTTP_PORT:-8080}/status.php"
