#! /bin/bash

# Find comments related to the ticket potentially indicated by the branch name. The script never
# fails, it only warns the caller there are comments that are potentially worth checking.

# Testing notes:
# Different users have different structures in their development trees. When making changes to this
# script, please test a few different scenarios including: When there are multiple populated
# build directories, and when the Git repository is checkout out with the Jira ticket in the name
# of the repo, and the current branch name matches the Jira ticket as well.

# Retrieve the current branch name.
branch_name=$(git rev-parse --abbrev-ref HEAD 2>&1 || echo "BRANCH_NOT_FOUND")

# We expect the following syntax (case insensitive): wt-<digits>[-<alphanum>].
wt_ticket_regex="(wt|WT|wT|Wt)-[0-9]+(-[a-zA-Z0-9-]+)?"
if [[ ! $branch_name =~ ^$wt_ticket_regex ]]; then
    exit 0
fi

# Get what could be the ticket id.
ticket_id=$(echo "$branch_name" | cut -d "-" -f-2)

search_function="grep -Iinr --exclude-dir=.git"

# Find the name of the build folders WiredTiger has been compiled in.
# Users can name this folder anything, but it needs to be in the rootdir and to contain CMakeFiles
build_files=$(find ../ -maxdepth 2 -name CMakeFiles)
for build_dir in $build_files; do
    build_folder=$(basename $(dirname $build_dir))
    search_function="$search_function --exclude-dir=$build_folder"
done

search_function="$search_function $ticket_id ../ 2>&1"

# Check for comments related to the ticket.
if eval "$search_function >/dev/null" ; then
    echo "There are comments mentioning $ticket_id in the code, please check if they need to be \
resolved:"
    eval "$search_function"
fi

exit 0
