#!/bin/bash

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
UNITY_ROOT="$REPO_ROOT/src/main/csharp/net/eagle0/clients/unity/eagle0"
PLUGIN_DIR="$UNITY_ROOT/Assets/Plugins/Eagle0Protos"
GENERATED_SOURCES_DIR="$UNITY_ROOT/Assets/GeneratedProtos"
PROTO_DLL_TARGET="//src/main/csharp/net/eagle0/clients/unity/eagle0:eagle0_protos"
PROTO_DLL_OUTPUT="$REPO_ROOT/bazel-bin/src/main/csharp/net/eagle0/clients/unity/eagle0/eagle0_protos/netstandard2.1"

/bin/echo "Building C# protobuf DLL..."
bazel build "$PROTO_DLL_TARGET"

/bin/echo "Syncing generated protobuf DLL to $PLUGIN_DIR..."

STAGING_DIR=$(mktemp -d)
trap "rm -rf '$STAGING_DIR'" EXIT

cp "$PROTO_DLL_OUTPUT/Eagle0Protos.dll" "$STAGING_DIR/"
cp "$PROTO_DLL_OUTPUT/Eagle0Protos.xml" "$STAGING_DIR/"

# Sync only changed files and delete removed ones; --checksum compares
# content not timestamps so unchanged files keep their original mtime.
mkdir -p "$PLUGIN_DIR"
rsync -rc --delete --exclude "*.meta" "$STAGING_DIR/" "$PLUGIN_DIR/"

rm -rf "$GENERATED_SOURCES_DIR"

/bin/echo "Done. Generated C# proto DLL in $PLUGIN_DIR"
