#!/bin/bash

set -euxo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
UNITY_ROOT="$REPO_ROOT/src/main/csharp/net/eagle0/clients/unity/eagle0"
OUTPUT_DIR="$UNITY_ROOT/Assets/GeneratedProtos"

# All C# protobuf generation targets
TARGETS=(
    "//src/main/protobuf/net/eagle0/common:common_csharp_proto_srcs"
    "//src/main/protobuf/net/eagle0/shardok/storage:storage_csharp_proto_srcs"
    "//src/main/protobuf/net/eagle0/shardok/common:common_csharp_proto_srcs"
    "//src/main/protobuf/net/eagle0/shardok/api:api_csharp_proto_srcs"
    "//src/main/protobuf/net/eagle0/eagle/common:common_csharp_proto_srcs"
    "//src/main/protobuf/net/eagle0/eagle/views:views_csharp_proto_srcs"
    "//src/main/protobuf/net/eagle0/eagle/api:api_csharp_proto_srcs"
    "//src/main/protobuf/net/eagle0/eagle/api:api_csharp_grpc_srcs"
    "//src/main/protobuf/net/eagle0/eagle/api/command/util:util_csharp_proto_srcs"
)

# Subdirectory for each target (avoids filename collisions across packages)
SUBDIRS=(
    "net/eagle0/common"
    "net/eagle0/shardok/storage"
    "net/eagle0/shardok/common"
    "net/eagle0/shardok/api"
    "net/eagle0/eagle/common"
    "net/eagle0/eagle/views"
    "net/eagle0/eagle/api"
    "net/eagle0/eagle/api"
    "net/eagle0/eagle/api/command/util"
)

/bin/echo "Building C# protobuf sources..."
bazel build "${TARGETS[@]}"

/bin/echo "Syncing generated .cs files to $OUTPUT_DIR..."

# Stage new files in a temp directory, then rsync to preserve timestamps
# on unchanged files. This avoids triggering Unity reimport when protos
# haven't changed, saving ~7 minutes of script recompilation.
STAGING_DIR=$(mktemp -d)
trap "rm -rf '$STAGING_DIR'" EXIT

for i in "${!TARGETS[@]}"; do
    target="${TARGETS[$i]}"
    subdir="${SUBDIRS[$i]}"

    # Convert target label to bazel-bin path
    # //src/main/protobuf/net/eagle0/common:common_csharp_proto_srcs
    # -> bazel-bin/src/main/protobuf/net/eagle0/common/common_csharp_proto_srcs
    target_path="${target#//}"
    pkg="${target_path%%:*}"
    name="${target_path##*:}"
    bin_dir="$REPO_ROOT/bazel-bin/$pkg/$name"

    dest_dir="$STAGING_DIR/$subdir"
    mkdir -p "$dest_dir"
    find "$bin_dir" -name "*.cs" -exec cp {} "$dest_dir/" \;
done

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

/bin/echo "Done. Generated C# proto sources in $OUTPUT_DIR"
