#!/bin/bash

set -e

root=$(cd $(dirname ${0})/..; pwd)
build=${root}/build
node_modules=${root}/node_modules
src=${root}/src
tools=${root}/tools
third_party=${root}/third_party

python=${python:-python}
pip=${pip:-pip}

identifier=tensorflow
repository=https://github.com/tensorflow/${identifier}.git

mkdir -p ${third_party}

if [ -d "${third_party}/${identifier}" ]; then
    git -C "${third_party}/${identifier}" fetch -p
    git -C "${third_party}/${identifier}" reset --hard origin/master
else
    echo "Clone ${repository}..."
    git -C "${third_party}" clone --recursive ${repository}
fi

echo "Generate '../src/tf.js'"
${node_modules}/protobufjs/bin/pbjs -t static-module -w closure -r tf -o ${src}/tf.js \
    ${third_party}/${identifier}/tensorflow/core/protobuf/saved_model.proto \
    ${third_party}/${identifier}/tensorflow/core/protobuf/meta_graph.proto \
    ${third_party}/${identifier}/tensorflow/core/protobuf/saver.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/graph.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/op_def.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/tensor_shape.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/types.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/node_def.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/versions.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/function.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/attr_value.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/tensor.proto \
    ${third_party}/${identifier}/tensorflow/core/framework/resource_handle.proto \

export PYTHONUSERBASE=${build}/third_party/pypi/${identifier}
export PATH=$PATH:${PYTHONUSERBASE}/bin
echo $PYTHONUSERBASE
rm -rf ${PYTHONUSERBASE}
${pip} install --user protobuf

echo "Generate '../src/tf-metadata.json'"
protoc --proto_path ${third_party}/${identifier} tensorflow/core/framework/attr_value.proto --python_out=${tools}
protoc --proto_path ${third_party}/${identifier} tensorflow/core/framework/tensor.proto --python_out=${tools}
protoc --proto_path ${third_party}/${identifier} tensorflow/core/framework/types.proto --python_out=${tools}
protoc --proto_path ${third_party}/${identifier} tensorflow/core/framework/tensor_shape.proto --python_out=${tools}
protoc --proto_path ${third_party}/${identifier} tensorflow/core/framework/resource_handle.proto --python_out=${tools}
protoc --proto_path ${third_party}/${identifier} tensorflow/core/framework/api_def.proto --python_out=${tools}
protoc --proto_path ${third_party}/${identifier} tensorflow/core/framework/op_def.proto --python_out=${tools}
touch ${tools}/tensorflow/__init__.py
touch ${tools}/tensorflow/core/__init__.py
touch ${tools}/tensorflow/core/framework/__init__.py
pushd ${tools} > /dev/null
${python} tf-metadata.py
popd > /dev/null
rm -rf ${tools}/tensorflow
