#!/bin/bash
# Copybara runner script for syncing demo apps
# This script runs Copybara via Gradle, which downloads it from Maven Central
#
# Usage: tools/copybara/run [copybara arguments]
#
# This mimics the Bazel-based approach from Treehouse where:
# 1. Copybara is fetched from Maven Central (similar to Bazel's @com_github_google_copybara//jar)
# 2. Runs from the repository root (similar to run_in_workspace_root_binary)
# 3. Executes com.google.copybara.Main as a Java binary

set -e

# Get the directory where this script lives
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Navigate to repository root (two levels up from tools/copybara/)
REPO_ROOT="$( cd "$SCRIPT_DIR/../.." && pwd )"

# Change to repository root to match Bazel's run_in_workspace_root behavior
cd "$REPO_ROOT"

# Export REPO_ROOT so copybara config can use it if needed
export COPYBARA_REPO_ROOT="$REPO_ROOT"

# Build the arguments string for Gradle
# Join all arguments with spaces, and add --config-root if not already present
COPYBARA_ARGS="$*"
if [[ "$COPYBARA_ARGS" != *"--config-root"* ]]; then
    COPYBARA_ARGS="$COPYBARA_ARGS --config-root=$REPO_ROOT"
fi

# Run Gradle task with arguments passed via -PcopybaraArgs
# Disable configuration cache to avoid warnings about copybara tasks
exec ./gradlew :tools:runCopybara --console=plain --quiet --no-configuration-cache -PcopybaraArgs="$COPYBARA_ARGS"
