
# get_deps function has to be executed
# example to run from driving: get_deps_for_topic //vehicle/common/proto perception_obstacles2 $DESTINATION_PATH
function get_deps_for_topic {

  local PROTO_LOCATION=$1
  local PROTO_NAME=$2
  local DESTINATION_PATH=$3
  local DEST_FILENAME=${4:-proto_deps}
  local DRIVING_PATH=${5:-.}
  local APPEND=${6:-false}
  local INITIAL_WD=$(pwd)

  cd $DRIVING_PATH

  local DESTINATION_FILE=$DESTINATION_PATH\/$DEST_FILENAME\.txt

  # get deps for protos
  # append to the $DESTINATION_FILE if $APPEND is true
  if [[ $APPEND = "true" ]]
  then
    bazel query "kind('source file', deps("$PROTO_LOCATION":"$PROTO_NAME"))" | \
      grep ^//.*\.proto$ | \
      sed "s/:/\//g;s/\/\//\.\//g;"  \
      >> $DESTINATION_FILE
  else
    bazel query "kind('source file', deps("$PROTO_LOCATION":"$PROTO_NAME"))" | \
      grep ^//.*\.proto$ | \
      sed "s/:/\//g;s/\/\//\.\//g;"  \
      > $DESTINATION_FILE
  fi

  cd $INITIAL_WD
}

function move_file_to_new_path {
  local FILE_TO_MOVE=$1
  local DESTINATION=$2
  local DRIVING_PATH=${3:-.}

  local FILE_DIR=$(dirname "$FILE_TO_MOVE" | sed "s/\.//g")
  local FILE_NAME=$(basename "$FILE_TO_MOVE")

  local FILE_DESTINATION=$(echo "$DESTINATION$FILE_DIR" | sed "s/\/\//\//g")

  [ ! -d $FILE_DESTINATION ] && mkdir -p $FILE_DESTINATION

  cp $DRIVING_PATH$FILE_DIR\/$FILE_NAME "$FILE_DESTINATION/$FILE_NAME"
}

function update_driving_repo {
  local DRIVING_PATH=$1; shift
  local BRANCH=$1; shift
  local CP_BRANCH=$1; shift
  local CHERRYPICK_COMMITS=("$@")
  local INITIAL_WD=$(pwd)

  cd $DRIVING_PATH

  git status
  echo "====================== UPDATING STATE OF DRIVING REPO ======================="
  git pull origin $BRANCH

  echo "======= ENSURING THAT LATEST VERSION OF SETUP SCRIPT FOR BAZEL IS RAN ========"
  ./scripts/setup/setup.sh dev --tags bazel --no-ask-pass

  git config --global user.email "data-team@zoox.com"
  git config --global user.name "Data Team"

  echo "====== CHERRY PICKING COMMITS REQUIRED FOR HANDLING INCOMPATIBLE PROTOS ======"
  git fetch origin $CP_BRANCH
  for i in "${CHERRYPICK_COMMITS[@]}"; do
    git cherry-pick $i
  done

  echo "======================= UPDATE OF DRIVING IS COMPLETED ======================="

  cd $INITIAL_WD
}
