#!/usr/bin/env bash
if [[ "$1" == "-h" ]]
  then
    echo "usage: $0 prbranch [basebranch]"
    echo "where: prbranch   (default = HEAD) is the branch of the PR in question"
    echo "       basebranch (default = origin/master) is the branch the PR targets"
    exit 1
  fi

prevcwd=$(pwd)
cd $ZOOX_WORKSPACE_ROOT
basebranch=${2:-origin/master}
prbranch=${1:-HEAD}
echo $(date) start 'git fetch' to make sure all the possible pieces are here
git fetch >/dev/null 2>&1
#currhead=$(git rev-parse --abbrev-ref HEAD)
#if [[ $currhead == "HEAD" ]] then
#  currhead=$(git rev-parse HEAD)
#fi
#if [[ $basebranch != "origin/master" ]] then
#  echo ... insuring $basebranch is checked out locally and current with origin
#  git checkout $basebranch > /dev/null 2>&1
#  git pull origin $basebranch > /dev/null 2>&1
#fi
#if [[ $prbranch != "HEAD" ]] then
#  echo ... insuring $prbranch is checked out locally and current with origin
#  git checkout origin/$prbranch > /dev/null 2>&1
#fi
#latesthead=$(git rev-parse --abbrev-ref HEAD)
#latestsha=$(git rev-parse HEAD)
#if [[ $latesthead != $currhead && $latestsha != $currhead ]] then
#  git checkout $currhead
#fi
echo $(date) finish branch syncing -- start finding changed files
filelist="$(git diff --name-only $prbranch $(git merge-base $prbranch $basebranch) 2>/dev/null)"
filecount="$(echo $filelist | wc -w)"
echo $(date) finish finding $filecount changed files -- start getting bazel targets
trimmedfilelist="$(bazel query "set(${filelist})" --keep_going 2>/dev/null)"
echo $(date) finish getting bazel targets -- start evaluating dependencies
bazelout=$(bazel query "allpaths(//..., set($trimmedfilelist))" 2>/dev/null)
echo $(date) finish evaluating dependencies
runtargets=""
echo These files changed: $filelist
echo Producing these bazel targets: $bazelout
bazel test $bazelout
cd $prevcwd
