#!/bin/bash

set -euf -o pipefail

# Hardcoded in this script with the job workspace.
ws=/home/tcwg-buildslave/workspace/tcwg_kernel_0
current_project=$1

rev=$(git -C $current_project rev-parse HEAD)

if git -C $current_project bisect log | grep "^git bisect bad $rev\$" >/dev/null; then
  exit 1
elif git -C $current_project bisect log | grep "^git bisect skip $rev\$" >/dev/null; then
  exit 125
elif git -C $current_project bisect log | grep "^git bisect good $rev\$" >/dev/null; then
  exit 0
fi


# Restore known-good baseline state.
rsync -a --del --exclude /bisect/ --exclude /artifacts/ --exclude /gcc/ $ws/bisect/baseline/ $ws/

( cd $ws && ./jenkins-scripts/tcwg_kernel-build.sh   ^^ false   %%rr[top_artifacts] artifacts/build-$rev   @@ artifacts/build-parameters/manifest.sh   ==rr[mode] bisect   ==rr[update_baseline] ignore   ==rr[gcc_git] "git+ssh://linaroci@gcc.gnu.org/git/gcc.git#$rev"   --verbose "true" ) &
res=0 && wait $! || res=$?

git -C $current_project reset -q --hard

if [ x"$res" != x"0" ]; then
  if [ -f $ws/artifacts/build-$rev/trigger-build-gcc ]; then
    exit 1
  else
    # The build failed due to an uninteresting problem -- a prerequisite
    # failed to build or benchmarking harness went down.  We mark such
    # revisions "skipped", but up to a point.  If we skip more revisions
    # in a row, than half the number of tests necessary to finish the bisect,
    # then we mark such "skipped" revision as "bad".

    # Number of "git bisect skip" in a row
    n_skips=$(git -C $current_project bisect log | awk '
BEGIN { n_skips=0 }
/git bisect skip/ { n_skips++; next }
/git bisect/ { n_skips=0 }
END { print n_skips }
')
    if [ $n_skips = 0 ]; then
      exit 125
    fi

    revs_left=$(git -C $current_project bisect view --pretty=%H | wc -l)
    # Half the number of steps to finish the bisect
    n_steps_2=$(echo "n_steps=l($revs_left)/l(2); scale=0; n_steps/2" | bc -l)
    if [ $n_steps_2 -lt 2 ]; then
      # Avoid skipping revisions at the end of the bisect.
      n_steps_2=2
    fi
    if [ $n_skips -le $n_steps_2 ]; then
      exit 125
    else
      # We had several skips in a row and still have many revisions to bisect.
      # Mark this one "bad" to progress the bisect.
      exit 1
    fi
  fi
else
  exit 0
fi
