#!/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=pytorch
repository=https://github.com/pytorch/pytorch.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/caffe2.js'"
${node_modules}/protobufjs/bin/pbjs -t static-module -w closure -r caffe2 -o ${src}/caffe2.js ${third_party}/pytorch/caffe2/proto/caffe2.proto

echo "Install Caffe2"
if [ "$(uname -s)" == "Darwin" ] && [ "$(which brew)" != "" ]; then
brew bundle --file=- <<-EOS
brew "automake"
brew "cmake"
brew "gflags"
brew "glog"
EOS
fi
export PYTHONUSERBASE=${build}/third_party/pypi/${identifier}
export PATH=$PATH:${PYTHONUSERBASE}/bin
rm -rf ${PYTHONUSERBASE}
${pip} install --user future leveldb numpy protobuf pydot python-gflags pyyaml scikit-image setuptools six hypothesis
pushd "${third_party}/pytorch" > /dev/null
git submodule update --init
${python} setup_caffe2.py develop --user
popd > /dev/null

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