#!/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/scikit-learn
    [ -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
}

git_sync() {
    [ -d "./third_party/src/${1}" ] || git clone --quiet --recursive ${2} "./third_party/src/${1}"
    pushd "./third_party/src/${1}" > /dev/null
    git pull --quiet --prune
    git submodule sync --quiet
    git submodule update --quiet --init --recursive
    popd > /dev/null
}

clean() {
    bold "sklearn clean"
    rm -rf "./third_party/env/scikit-learn"
    rm -rf "./third_party/src/numpy"
    rm -rf "./third_party/src/scikit-learn"
    rm -rf "./third_party/src/lightgbm"
    rm -rf "./third_party/src/xgboost"
}

sync() {
    bold "sklearn sync"
    git_sync numpy https://github.com/numpy/numpy.git
    git_sync scikit-learn https://github.com/scikit-learn/scikit-learn.git
    git_sync lightgbm https://github.com/Microsoft/LightGBM.git
    git_sync xgboost https://github.com/dmlc/xgboost.git
}

install() {
    bold "sklearn install"
    venv
    ${python} -m pip install --quiet six cython pytest flake8 numpy scipy pylint astroid isort
    ${python} -m pip install --quiet --pre -f https://sklearn-nightly.scdn8.secure.raxcdn.com scikit-learn
    # ${python} -m pip install --quiet ./third_party/src/scikit-learn
    deactivate
}

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

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