#!/bin/bash

set -e

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

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

identifier=onnx
repository=https://github.com/onnx/${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 "Install ONNX"
export PYTHONUSERBASE=${build}/third_party/pypi/${identifier}
export PATH=$PATH:${PYTHONUSERBASE}/bin
rm -rf ${PYTHONUSERBASE}
export ONNX_ML=1
export ONNX_NAMESPACE=onnx
${pip} install --user ${third_party}/${identifier}

echo "Generate '../src/onnx-metadata.json'"
pushd ${tools} > /dev/null
${python} onnx-metadata.py
popd > /dev/null

echo "Generate '../src/onnx.js'"
sed 's/package ONNX_NAMESPACE/package onnx/g' <${third_party}/${identifier}/onnx/onnx-ml.proto >${tools}/onnx-ml.proto
${node_modules}/protobufjs/bin/pbjs -t static-module -w closure -r onnx -o ${src}/onnx.js ${tools}/onnx-ml.proto
rm ${tools}/onnx-ml.proto
