#!/bin/sh

set -e

set -x

z40=0000000000000000000000000000000000000000

while read local_ref local_sha remote_ref remote_sha; do
    echo "checking local ref $local_ref $remote_sha..$local_sha to $remote_ref..."

    # deleted branch
    if [ "$local_sha" = "$z40" ]; then
        continue
    fi

    # this basically finds "master" most of the time
    # https://stackoverflow.com/a/17843908
    parent_branch=$(git show-branch -a \
| sed "s/].*//" \
| grep "\*" \
| grep -v "$(git rev-parse --abbrev-ref HEAD)" \
| head -n1 \
| sed "s/^.*\[//")
    parent_sha=$(git merge-base "$parent_branch" "$local_ref")
    # new branch
    if [ "$remote_sha" = "$z40" ]; then
        remote_sha=$parent_sha
    fi
    range="$remote_sha..$local_sha"

    # remote_sha might not actually be present yet,
    if ! git cat-file -t "$remote_sha" ; then
        range="$parent_sha..$local_sha"
    fi
    changed_files=$(git diff --name-only "$range")

    if [ -z "$changed_files" ] ; then
        echo "no changed files found in ref $local_ref, not checking"
        continue
    fi
    echo "changed files on $local_ref: $changed_files"


    # when adding checks here, add them to .gitlab-ci.yml as well

    markdown_files=$(git diff --name-only "$range" | grep '\.md') || true
    if [ -n "$markdown_files" ]; then
        echo "markdown changes found, running md linters"
        bin_dir=${GIT_DIR:-.git}/../bin/
        $bin_dir/mdl-wrapper $markdown_files
        codespell $markdown_files
        $bin_dir/check_policy.py -v
        $bin_dir/reverse_check.py --gitlab doc.md doc
        $bin_dir/reverse_check.py --gitlab howto.md howto --ignore-regex='howto/upgrades/.*'
        $bin_dir/reverse_check.py --gitlab meeting.md meeting
        $bin_dir/reverse_check.py --gitlab roadmap.md roadmap
        $bin_dir/reverse_check.py --gitlab service.md service
    fi
    if git diff --name-only "$range" | grep '\.py'; then
        echo "python changes found, running tox"
        tox --current-env
    fi

    echo "done checking ref $local_ref"
done
