#!/bin/bash

set -e
pushd $(cd $(dirname ${0})/..; pwd) > /dev/null

case "${OSTYPE}" in
    msys*) python="winpty python";;
    *) python="python";;
esac

clean() {
    echo "pytorch clean"
    rm -rf "./third_party/source/pytorch"
}

sync() {
    echo "pytorch sync"
    [ -d "./third_party/source/pytorch" ] || git clone --quiet https://github.com/pytorch/pytorch.git "./third_party/source/pytorch"
    git -C "./third_party/source/pytorch" pull --quiet --prune
}

schema() {
    echo "caffe2 schema"
    [[ $(grep -U $'\x0D' ./source/caffe2-proto.js) ]] && crlf=1
    node ./tools/protoc.js --text --root caffe2 --out ./source/caffe2-proto.js ./third_party/source/pytorch/caffe2/proto/caffe2.proto
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./source/caffe2-proto.js ./source/caffe2-proto.js
    fi
}

metadata() {
    echo "pytorch metadata"
    [[ $(grep -U $'\x0D' ./source/pytorch-metadata.json) ]] && crlf=1
    ${python} ./tools/pytorch_metadata.py
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./source/pytorch-metadata.json ./source/pytorch-metadata.json
    fi
}

while [ "$#" != 0 ]; do
    command="$1" && shift
    case "${command}" in
        "clean") clean;;
        "sync") sync;;
        "metadata") metadata;;
    esac
done
