#!/bin/bash

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

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

venv() {
    env_dir=./third_party/env/coremltools
    [ -d "${env_dir}" ] || ${python} -m venv ${env_dir}
    case "${env_dir}" in
        msys*) source ${env_dir}/Scripts/activate;;
        *) source ${env_dir}/bin/activate;;
    esac
    ${python} -m pip install --quiet --upgrade pip
}

clean() {
    echo "coreml clean"
    rm -rf "./third_party/source/env/coremltools"
    rm -rf "./third_party/source/coremltools"
}

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

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

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