#!/usr/bin/env bash

set -o pipefail

CHECKPOINT_FILENAME="latest-success-commit"
RIOT_PATTERN=${1}
DDTRACE_FLAG=$([ -v _CI_DD_API_KEY ] && echo '--ddtrace')
GIT_MESSAGE_LOWERCASE=$(git log -1 --pretty=%B | tr "[:upper:]" "[:lower:]")
if [[ $GIT_MESSAGE_LOWERCASE == *"itr:noskip"* ]]; then
    COLLECT_COVERAGE=true
else
    if [[ -v CIRCLE_PULL_REQUEST ]]; then
        COLLECT_COVERAGE=false
    else
        echo "Getting coverage for non-PR branch"
        COLLECT_COVERAGE=true
    fi
fi
COVERAGE_FLAG=$([[ "${2:-false}" == false && $COLLECT_COVERAGE == false ]] && echo '--no-cov')
DDTEST_CMD=$([[ ${3} == "1" ]] && echo "./scripts/ddtest")

RIOT_HASHES=( $(riot list --hash-only $RIOT_PATTERN | sort) )
echo "Found ${#RIOT_HASHES[@]} riot hashes: ${RIOT_HASHES[@]}"
if [[ ${#RIOT_HASHES[@]} -eq 0 ]]; then
    echo "No riot hashes found for pattern: $RIOT_PATTERN"
    if [[ -v CIRCLECI ]]; then
        circleci step halt
    fi
    exit 1
fi

if [[ -v CIRCLECI ]]; then
    # circleci tests splits expects one test per line
    RIOT_HASHES=( $( printf '%s\n' "${RIOT_HASHES[@]}"  | circleci tests split) )
    if [[ ${#RIOT_HASHES[@]} -eq 0 ]]; then
        echo "No riot hashes found after split, halting."
        circleci step halt
        exit 0
    fi
    echo "${#RIOT_HASHES[@]} hashes split for CircleCI: ${RIOT_HASHES[@]}"
fi



set -e

if ! [[ -v CIRCLECI && $CIRCLE_BRANCH =~ main ]]; then
    if [[ -f "$CHECKPOINT_FILENAME" ]]; then
        latest_success_commit=$(cat $CHECKPOINT_FILENAME)
        if ! hatch run scripts:needs_testrun $CIRCLE_JOB --sha $latest_success_commit; then
            echo "The $CIRCLE_JOB job succeeded at commit $latest_success_commit."
            echo "None of the changes on this branch since that commit affect the $CIRCLE_JOB job."
            echo "Skipping this job."
            circleci step halt
        fi
    fi
fi

for hash in ${RIOT_HASHES[@]}; do
    echo "Running riot hash: $hash"
    ($DDTEST_CMD riot -P -v run --exitfirst --pass-env -s $hash $COVERAGE_FLAG $DDTRACE_FLAG)
    exit_code=$?
    if [ $exit_code -ne 0 ] ; then
        if [[ -v CIRCLECI ]]; then
            circleci step halt
        fi
        exit $exit_code
    fi
done

rm -f $CHECKPOINT_FILENAME
echo $CIRCLE_SHA1 > $CHECKPOINT_FILENAME
echo "All tests passed. Saved $CIRCLE_SHA1 as the latest successful commit for job $CIRCLE_JOB"

./scripts/check-diff \
    ".riot/requirements/" \
    "Changes detected after running riot. Consider deleting changed files, \
    running scripts/compile-and-prune-test-requirements and committing the result."

./scripts/check-diff \
    "ddtrace/contrib/integration_registry/registry.yaml" \
    "Registry YAML file (ddtrace/contrib/integration_registry/registry.yaml) was modified. Please run: \
    \`python scripts/integration_registry/update_and_format_registry.py\` and commit the changes."
