#!/bin/bash

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

case "${OSTYPE}" in
    msys*) python="winpty python";;
    *) python=python3;;
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
}

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

clean() {
    bold "coreml clean"
    rm -rf "./third_party/src/env/coremltools"
    rm -rf "./third_party/src/coremltools"
}

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

schema() {
    bold "coreml schema"
    [[ $(grep -U $'\x0D' ./src/coreml-proto.js) ]] && crlf=1
    npx pbjs -t static-module -w closure --no-encode --no-delimited --no-comments --no-convert --no-verify --no-create --keep-case -r coreml -o ./src/coreml-proto.js ./third_party/src/coremltools/mlmodel/format/Model.proto
    node ./tools/update_pbjs.js array ./src/coreml-proto.js floatValue float 2
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./src/coreml-proto.js ./src/coreml-proto.js
    fi
}

convert() {
    bold "coreml convert"
    venv
    ${python} -m pip install --quiet --upgrade six numpy protobuf
    ${python} -m pip install --quiet ./third_party/src/coremltools
    ${python} -m pip install --quiet onnx
    ${python} -m pip install --quiet sklearn
    ${python} ./tools/coreml-script.py convert ${1}
    deactivate
}

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