#!/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/keras
    [ -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 setuptools
}

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

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

install() {
    bold "keras install"
    case "${OSTYPE}" in
        msys*) [ ! -z "$(choco list --local-only --exacty --limit-output vcredist140)" ] || $(choco install -yes vcredist140) > /dev/null;;
    esac
    venv
    ${python} -m pip install --quiet --upgrade tensorflow
    ${python} -m pip install --quiet ./third_party/src/keras
    deactivate
}

metadata() {
    bold "keras metadata"
    [[ $(grep -U $'\x0D' ./src/keras-metadata.json) ]] && crlf=1
    venv
    export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
    ${python} ./tools/keras-script.py metadata
    deactivate
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./src/keras-metadata.json ./src/keras-metadata.json
    fi
}

zoo() {
    bold "keras zoo"
    venv
    export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
    ${python} ./tools/keras-script.py zoo
    deactivate
}

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