#!/bin/bash -exf

# Checks what doc build type to run.
# Generate:
# - 'pattern.txt' that lists the examples to build.
#   Its content is passed to sphinx_gallery_conf.filename_pattern via a PATTERN env variable.
# - 'build.txt' that contains the build type to run
#
# On the main branch, on tagged released or if requested in the commit message,
# this exits early and sets things for a full doc build.
# Otherwise it checks if any examples must be built
# (either because it was changed in the PR or requested in the commit message).
#
# Must be run after running build_tools/github/merge_upstream.sh
#

set -x -e

#  ----- Input checks

if ! [ -f gitlog.txt ]; then
    echo "gitlog.txt not found."
    echo "should have been generated by build_tools/github/merge_upstream.sh"
    exit 1
fi

if ! [ -f merge.txt ]; then
    echo "merge.txt not found."
    echo "should have been generated by build_tools/github/merge_upstream.sh"
    exit 1
fi

#  ----- Set missing variables

# If this is run locally,
# it uses the checked out branch as reference.
if [ -z ${CI+x} ]; then
    echo "Running locally";
    COMMIT_SHA=$(git log --format=format:%H -n 1)
    GITHUB_REF_TYPE="branch"
else
    echo "Running in CI";
fi

GITHUB_REF_NAME=$(cat merge.txt)
GITLOG=$(cat gitlog.txt)

# pattern.txt must be generated even if empty
touch pattern.txt;

# Check for full build
if [ "$GITHUB_REF_NAME" == "main" ] || [ "$GITHUB_REF_TYPE" == "tag" ] || [[ $GITLOG == *"[full doc]"* ]]; then
    echo "Doing a full build";
    echo html-strict > build.txt;
    exit 0
fi

# check if the build of some examples was requested in the commit message
# like:
# git commit -m '[example] plot_*atlas*.py'
EXAMPLE=""
if [[ $GITLOG == *"[example]"* ]]; then
    echo "Building selected example";
    COMMIT_MESSAGE=${GITLOG#*] };
    EXAMPLE="examples/*/$COMMIT_MESSAGE";
fi;

# generate examples.txt that will list
# - all the files modified in this PR
# - and the examples listed in the commit message
git diff --name-only "$(git merge-base $COMMIT_SHA upstream/main)" "$COMMIT_SHA" | tee examples.txt;
echo "$EXAMPLE" >> examples.txt

# Filter the list of files to only keep files
# that are of interest for sphinx_gallery
for FILENAME in $(cat examples.txt); do
    if [[ $(expr match "$FILENAME" "\(examples\)/.*plot_.*\.py") ]]; then
        echo "Checking example $FILENAME ...";
        PATTERN=$(basename "$FILENAME")"\\|"$PATTERN;
    fi;
done;
echo PATTERN="$PATTERN";

if [[ $PATTERN ]]; then
    # Remove trailing \| introduced by the for loop above
    PATTERN="\(${PATTERN::-2}\)";
    echo html-modified-examples-only > build.txt;
else
    echo ci-html-noplot > build.txt;
fi;

echo "$PATTERN" > pattern.txt;
