#!/bin/bash

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

src_dir=./third_party/source/coremltools

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

clean() {
    echo "coreml clean"
    rm -rf "${src_dir}"
}

sync() {
    echo "coreml sync"
    if [ ! -d "${src_dir}" ]; then
        git clone --quiet --depth=1 --branch main --single-branch https://github.com/apple/coremltools.git "${src_dir}"
    else
        git -C "${src_dir}" fetch --quiet --depth=1 origin main
        git -C "${src_dir}" reset --quiet --hard FETCH_HEAD
        git -C "${src_dir}" gc --quiet --prune=all
    fi
}

schema() {
    echo "coreml schema"
    [[ $(grep -U $'\x0D' ./source/coreml-proto.js) ]] && crlf=1
    node ./tools/protoc.js --binary --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
