#!/bin/bash

set -e

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

bold() {
    echo "$(tty -s && tput bold)$1$(tty -s && tput sgr0)" 
}

clean() {
    bold "caffe clean"
    rm -rf "./third_party/src/caffe"
}

sync() {
    bold "caffe sync"
    [ -d "./third_party/src/caffe" ] || git clone --quiet https://github.com/BVLC/caffe.git "./third_party/src/caffe"
    pushd "./third_party/src/caffe" > /dev/null
    git pull --quiet --prune
    popd > /dev/null
}

schema() {
    bold "caffe schema"
    [[ $(grep -U $'\x0D' ./src/caffe-proto.js) ]] && crlf=1
    sed 's/required float min = 1;/optional float min = 1;/g;s/required float max = 2;/optional float max = 2;/g' < ./third_party/src/caffe/src/caffe/proto/caffe.proto >./tools/caffe.proto
    npx pbjs -t static-module -w closure --no-encode --no-delimited --no-comments --no-convert --no-verify --no-create --keep-case --decode-text -r caffe -o ./src/caffe-proto.js ./tools/caffe.proto
    rm ./tools/caffe.proto
    node ./tools/update_pbjs.js array ./src/caffe-proto.js data float 1
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./src/caffe-proto.js ./src/caffe-proto.js
    fi
}

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