#!/bin/bash
#
# Persist Unity Library/ cache to persistent storage
#
# Environment variables:
#   UNITY_CACHE_PLATFORM - Platform identifier (e.g., "mac", "windows")
#                          Defaults to "mac" if not set
#
# Note: Library/Bee/ is excluded because it contains DAG files with hardcoded
# file paths that become stale when project files change. This prevents
# "Data at the root level is invalid" XML errors from stale references.

set -uxo pipefail

PLATFORM="${UNITY_CACHE_PLATFORM:-mac}"
CACHE_DIR="/tmp/eagle0/Library-${PLATFORM}"

/bin/echo "persist Library/ to $CACHE_DIR (excluding Bee/)"

# rsync may exit with code 23 ("partial transfer due to error") if Unity's
# temporary files vanish during the copy. This is acceptable for a cache.
/usr/bin/rsync -rtlDvq --exclude='Bee/' src/main/csharp/net/eagle0/clients/unity/eagle0/Library/ "$CACHE_DIR/"
rsync_exit=$?

if [ $rsync_exit -eq 0 ]; then
    exit 0
elif [ $rsync_exit -eq 23 ]; then
    echo "Warning: rsync exited with 23 (some files vanished during copy). This is expected for Unity temp files."
    exit 0
else
    echo "Error: rsync failed with exit code $rsync_exit"
    exit $rsync_exit
fi