#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
PLATFORM_REPO="$(cd -- "${SCRIPT_DIR}/../.." && pwd)"
NAS_ROOT="${NAS_ROOT:-/Volumes/docker/nodedc-platform}"
SSH_TARGET="${SSH_TARGET:-dctouch@100.109.216.21}"

RSYNC_METADATA_ARGS=()
if [[ "${RSYNC_PRESERVE_METADATA:-0}" != "1" ]]; then
  RSYNC_METADATA_ARGS=(--no-times --no-perms --no-owner --no-group)
fi

if [[ ! -d "${NAS_ROOT}" ]]; then
  echo "NAS_ROOT not found: ${NAS_ROOT}" >&2
  echo "Set NAS_ROOT=/path/to/nodedc-platform when the Synology share is mounted elsewhere." >&2
  exit 1
fi

if [[ ! -f "${PLATFORM_REPO}/infra/synology/docker-compose.platform-http.yml" ]]; then
  echo "Synology compose is missing in local repo." >&2
  exit 1
fi

if [[ ! -d "${PLATFORM_REPO}/services/ai-workspace-hub" ]]; then
  echo "AI Workspace Hub source is missing in local repo." >&2
  exit 1
fi

mkdir -p "${NAS_ROOT}/platform"

rsync -av "${RSYNC_METADATA_ARGS[@]}" \
  "${PLATFORM_REPO}/infra/synology/docker-compose.platform-http.yml" \
  "${NAS_ROOT}/platform/docker-compose.platform-http.yml"

rsync -av "${RSYNC_METADATA_ARGS[@]}" \
  "${PLATFORM_REPO}/infra/synology/apply-ai-hub-relay.sh" \
  "${NAS_ROOT}/platform/apply-ai-hub-relay.sh"

mkdir -p "${NAS_ROOT}/platform/ai-workspace-hub"
rsync -av "${RSYNC_METADATA_ARGS[@]}" --delete \
  --exclude='node_modules/' \
  --exclude='.env' \
  --exclude='.env.*' \
  "${PLATFORM_REPO}/services/ai-workspace-hub/" \
  "${NAS_ROOT}/platform/ai-workspace-hub/"

cat <<EOF

AI Hub relay files synced to NAS mount.

Apply only AI Workspace Hub on Synology:

ssh ${SSH_TARGET} 'cd /volume1/docker/nodedc-platform/platform && sudo bash apply-ai-hub-relay.sh'

EOF
