#!/bin/bash
set -o xtrace

# The proto folder is generated by the following script
# and then manually cleaning the output from useless stuff

echo "Cleaning up tmp and output directory"
rm -rf tmp
rm -rf proto

echo "Creating tmp directory"
mkdir -p tmp/proto

echo "Entering tmp..."
cd tmp

echo "Cloning all submodules of git@github.com:tensorflow/tensorboard.git"
git clone --recurse-submodules git@github.com:tensorflow/tensorboard.git

echo "Cloning all submodules of git@github.com:tensorflow/tensorflow.git"
git clone --recurse-submodules git@github.com:tensorflow/tensorflow.git

echo "Copy from tmp/tensorboard to tmp/proto only proto files, keeping folder structure"
rsync -zarvm --include="*/" --include="*.proto" --exclude="*" tensorboard/ proto

echo "Copy from tmp/tensorflow to tmp/proto only proto files, keeping folder structure"
rsync -zarvm --include="*/" --include="*.proto" --exclude="*" tensorflow/ proto

# Tensorboard has a file named struct.proto which conflicts with google's stdlib struct.proto,
# so we rename it to struct_tb.proto to avoid the conflict
mv proto/tensorboard/compat/proto/struct.proto proto/tensorboard/compat/proto/struct_tb.proto

# find and replace usages "compat/proto/struct.proto" with "compat/proto/struct.proto"
if [[ $(uname) == "Darwin" ]]; then
	echo "Workaround for sed on macos."
	LC_ALL=C
fi
grep -rl "compat/proto/struct.proto" . | xargs sed -i '' -e 's+compat/proto/struct\.proto+compat/proto/struct_tb\.proto+g'

cd ..
mv tmp/proto proto
rm -rf tmp
