#!/usr/bin/env bash

# Automatically generated by nengo-bones, do not edit this file directly

NAME=$0
COMMAND=$1
STATUS=0  # used to exit with non-zero status if any command fails

exe() {
    echo "\$ $*";
    # remove empty spaces from args
    args=( "$@" )
    for i in "${!args[@]}"; do
      [ -n "${args[$i]}" ] || unset "args[$i]"
    done
    "${args[@]}" || { echo -e "\033[1;31mCOMMAND '${args[0]}' FAILED\033[0m"; STATUS=1; }
}

if [[ ! -e nengo_spa ]]; then
    echo "Run this script from the root directory of this repository"
    exit 1
fi


shopt -s globstar

if [[ "$COMMAND" == "install" ]]; then
    exe pip install "flake8"

    exe pip install "jupyter>=1.0.0" "pylint>=2.5.1" "codespell>=1.12.0" "gitlint>=0.1.2" "collective.checkdocs>=0.2" "flake8>=3.7.7"
elif [[ "$COMMAND" == "before_script" ]]; then
    :
elif [[ "$COMMAND" == "script" ]]; then

    exe pylint nengo_spa --jobs=0
    exe flake8 nengo_spa
    exe bones-format-notebook docs --verbose --check
    if [[ "$(python -c 'import sys; print(sys.version_info >= (3, 6))')" == "True" ]]; then
        exe black --check nengo_spa
    fi
    exe codespell -q 3 \
        --skip="./build,*/_build,*-checkpoint.ipynb,./.eggs,./.git,*/_vendor" \
        --ignore-words-list="ba"
    exe shellcheck -e SC2087 .ci/*.sh
    # undo single-branch cloning
    git config --replace-all remote.origin.fetch +refs/heads/*:refs/remotes/origin/*
    git fetch origin master
    N_COMMITS=$(git rev-list --count HEAD ^origin/master)
    for ((i=0; i<N_COMMITS; i++)) do
        git log -n 1 --skip "$i" --pretty=%B \
            | grep -v '^Co-authored-by:' \
            | gitlint -vvv || STATUS=1
    done
    exe python setup.py checkdocs

    exe flake8 -v nengo_spa
elif [[ "$COMMAND" == "before_cache" ]]; then
    :
elif [[ "$COMMAND" == "after_success" ]]; then
    :
elif [[ "$COMMAND" == "after_failure" ]]; then
    :
elif [[ "$COMMAND" == "before_deploy" ]]; then
    :
elif [[ "$COMMAND" == "after_deploy" ]]; then
    :
elif [[ "$COMMAND" == "after_script" ]]; then
    :
elif [[ -z "$COMMAND" ]]; then
    echo "$NAME requires a command like 'install' or 'script'"
else
    echo "$NAME does not define $COMMAND"
fi

if [[ "$COMMAND" != "script" && -n "$TRAVIS" && "$STATUS" -ne "0" ]]; then
    travis_terminate "$STATUS"
fi
exit "$STATUS"
