#!/bin/bash

mkdir -p ../third_party

repository=git@github.com:onnx/onnx.git

if [ -d "../third_party/onnx" ]; then
    pushd "../third_party/onnx" > /dev/null
    echo "Fetch ${repository}..."
    git fetch -p
    echo "Reset ${repository}..."
    git reset --hard origin/master
    popd > /dev/null
else
    echo "Clone ${repository}..."
    pushd "../third_party" > /dev/null
    git clone --recursive ${repository}
    popd > /dev/null
fi

export ONNX_ML=1
export ONNX_NAMESPACE=onnx

pushd "../third_party/onnx" > /dev/null
python ./setup.py build --build-lib ./build/lib
popd > /dev/null

echo "Generate '../src/onnx-operator.json'"
PYTHONPATH=../third_party/onnx/build/lib python onnx-operator-json.py

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