#!/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

if [[ "$1" == "-v" ]]
then
  OUTPUT=${2:-findccb.log}
  basebranch=origin/master
  prbranch=HEAD
else
  OUTPUT=/dev/null
  basebranch=${2:-origin/master}
  prbranch=${1:-HEAD}
fi

prevcwd=$(pwd)
cd $ZOOX_WORKSPACE_ROOT
echo $(date) starting 'git fetch' to make sure all the possible pieces are here | tee -a $OUTPUT
git fetch >>$OUTPUT 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 > $OUTPUT 2>&1
#  git pull origin $basebranch > $OUTPUT 2>&1
#fi
#if [[ $prbranch != "HEAD" ]] then
#  echo ... insuring $prbranch is checked out locally and current with origin
#  git checkout origin/$prbranch > $OUTPUT 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) finished branch syncing -- start finding changed files | tee -a $OUTPUT
filelist="$(git diff --name-only $prbranch $(git merge-base $prbranch $basebranch) 2>>$OUTPUT)"
filecount="$(echo $filelist | wc -w)"
if [[ $filecount -eq 0 ]]; then
  echo $(date) there were $filecount changed files. skipping the rest of the process | tee -a $OUTPUT
else
  echo $(date) finished finding $filecount changed files -- start getting bazel targets | tee -a $OUTPUT
  trimmedfilelist="$(bazel query "set(${filelist})" --keep_going 2>>$OUTPUT)"
  echo $(date) finished getting bazel targets -- start evaluating dependencies | tee -a $OUTPUT
  bazelout=$(bazel query "allpaths(//vehicle:l3_ccb_regulated_package, set($trimmedfilelist))" 2>>$OUTPUT)
  echo $(date) finished evaluating dependencies | tee -a $OUTPUT
  ccbfiles=""
  echo These files trigger CCB: | tee -a $OUTPUT
  for fnm in $trimmedfilelist
  do
    if [[ $(echo $bazelout | grep -c $fnm) -gt 0 ]]
    then
      echo $fnm
      ccbfiles+=" $fnm"
    fi
  done
  echo $(date) start generating dependency graph | tee -a $OUTPUT
  bazel query "allpaths(//vehicle:l3_ccb_regulated_package, set($trimmedfilelist))" --output=graph 2>>$OUTPUT | dot -Tpng > ccb_files.png
  echo $(date) a picture of the dependency graph can be found in $(pwd)/ccb_files.png | tee -a $OUTPUT
fi
cd $prevcwd
