#!/bin/bash

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

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

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

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

clean() {
    bold "tflite clean"
    rm -rf "./third_party/env/tflite"
    rm -rf "./third_party/src/tensorflow"
}

sync() {
    bold "tflite sync"
    [ -d "./third_party/src/tensorflow" ] || git clone --quiet --recursive https://github.com/tensorflow/tensorflow.git "./third_party/src/tensorflow"
    pushd "./third_party/src/tensorflow" > /dev/null
    git pull --quiet --prune
    git submodule sync --quiet
    git submodule update --quiet --init --recursive
    popd > /dev/null
}

schema() {
    bold "tflite schema"
    case "${OSTYPE}" in
        linux*)
            flatc_version=$(curl -s https://api.github.com/repos/google/flatbuffers/releases/latest | grep tag_name | cut -f 2 -d : | cut -f 2 -d '"')
            flatc_dir=./third_party/bin/flatbuffers/${flatc_version}
            if [ ! -f "${flatc_dir}/flatc" ]; then
                mkdir -p "${flatc_dir}"
                pushd "${flatc_dir}" > /dev/null
                curl -sL https://github.com/google/flatbuffers/archive/${flatc_version}.tar.gz | tar zx --strip-components 1
                cmake -G "Unix Makefiles" . &> /dev/null
                make > /dev/null
                popd > /dev/null
            fi
            export PATH=${flatc_dir}:${PATH}
            ;;
        darwin*)
            brew list flatbuffers > /dev/null 2>&1 || brew install flatbuffers > /dev/null
            ;;
        msys*)
            [ -x "$(command -v flatc)" ] || $(choco install flatc) > /dev/null
            ;;
    esac
    [[ $(grep -U $'\x0D' ./src/tflite-schema.js) ]] && crlf=1
    sed 's/namespace tflite;/namespace TFLITE;/g' < ./third_party/src/tensorflow/tensorflow/lite/schema/schema.fbs > ./tools/tflite.schema.fbs
    flatc --no-js-exports --js ./tools/tflite.schema.fbs
    rm ./tools/tflite.schema.fbs
    mv ./tflite.schema_generated.js ./src/tflite-schema.js
    cat <<EOT >> ./src/tflite-schema.js
if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  module.exports = TFLITE;
}
EOT
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./src/tflite-schema.js ./src/tflite-schema.js
    fi
}

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