#!/bin/bash

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

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

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

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

schema() {
    bold "armnn 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/armnn-schema.js) ]] && crlf=1
    flatc --no-js-exports -o ./tools/. --js ./third_party/src/armnn/src/armnnSerializer/ArmnnSchema.fbs
    mv ./tools/ArmnnSchema_generated.js ./src/armnn-schema.js
    cat <<EOT >> ./src/armnn-schema.js
if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  module.exports = armnnSerializer;
}
EOT
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./src/armnn-schema.js ./src/armnn-schema.js
    fi
}

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