#!/usr/bin/env bash
# This script formats all changed files from the last mergebase.
# You are encouraged to run this locally before pushing changes for review.

# The base branch to find the merge_base and run the diff against. Change as per the current branch
BASE_BRANCH="master"

# Cause the script to exit if a single command fails
set -eo pipefail

# this stops git rev-parse from failing if we run this from the .git directory
builtin cd "$(dirname "${BASH_SOURCE:-$0}")"

ROOT="$(git rev-parse --show-toplevel)"
builtin cd "$ROOT" || exit 1

# Add the upstream remote if it doesn't exist
# Sometimes, an "upstream" remote might be set but may not have been fetched
# 1. First check for previously fetched upstream (this should be quick)
if ! [[ -e "$ROOT/.git/refs/remotes/upstream" ]]; then
    # 2. Check if "upstream" is set/exists (this may take a few seconds)
    if ! git ls-remote upstream > /dev/null; then
        git remote add 'upstream' 'git@github.com:praveen-palanisamy/macad-gym.git'
    fi
fi

# Only fetch $BASE_BRANCH since that's the branch we're diffing against.
git fetch upstream ${BASE_BRANCH}

YAPF_FLAGS=(
    '--style' '{based_on_style:pep8, column_limit:79}'
    '--recursive'
    '--parallel'
)

YAPF_EXCLUDES=(
    '--exclude' 'src/macad_gym/carla/PythonAPI/*'
)

# Format specified files
format() {
    yapf --in-place "${YAPF_FLAGS[@]}" -- "$@"
}

# Format files that differ from base branch. Ignores dirs that are not slated
# for autoformat yet.
format_changed() {
    # The `if` guard ensures that the list of filenames is not empty, which
    # could cause yapf to receive 0 positional arguments, making it hang
    # waiting for STDIN.
    #
    # `diff-filter=ACM` and $MERGEBASE is to ensure we only format files that
    # exist on both branches.
    MERGEBASE="$(git merge-base upstream/${BASE_BRANCH} HEAD)"

    if ! git diff --diff-filter=ACM --quiet --exit-code "$MERGEBASE" -- '*.py' &>/dev/null; then
        git diff --name-only --diff-filter=ACM "$MERGEBASE" -- '*.py' | xargs -P 5 \
             yapf --in-place "${YAPF_EXCLUDES[@]}" "${YAPF_FLAGS[@]}"
        if which flake8 >/dev/null; then
            git diff --name-only --diff-filter=ACM "$MERGEBASE" -- '*.py' | xargs -P 5 \
                 flake8 --max-line-length 80 --exclude=./src/macad_gym/carla/PythonAPI/*,.git,.tox,__pycache__,./build/* #\
                    #--ignore=C408,E121,E123,E126,E226,E24,E704,W503,W504,W605
        fi
    fi
}


# Run flake8 check on all files and report the result
check_all() {
if which flake8 >/dev/null; then
    flake8 --max-line-length 80 --exclude=./src/macad_gym/carla/PythonAPI/*,.git,.tox,__pycache__,./build/*
fi

}


# Format all files, and print the diff to stdout for the CI log.
format_all() {
    yapf --diff "${YAPF_FLAGS[@]}" "${YAPF_EXCLUDES[@]}" src
}

# This flag formats individual files. --files *must* be the first command line
# arg to use this option.
if [[ "$1" == '--files' ]]; then
    format "${@:2}"
    # If `--all` is passed, then any further arguments are ignored and the
    # entire python directory is formatted.
elif [[ "$1" == '--all' ]]; then
    format_all
elif [[ "$1" == '--check' ]]; then
    check_all
else
    # Format only the files that changed in last commit.
    format_changed
fi

if ! git diff --quiet &>/dev/null; then
    echo 'Reformatted changed files. Please review and stage the changes.'
    echo 'Files updated:'
    echo

    git --no-pager diff --name-only

    exit 1
fi
