#!/bin/bash
set -o errexit
set -o nounset
set -o xtrace

source ./driving_utils.sh

CP_BRANCH=${CHERRYPICK_BRANCH:-$BRANCH}
update_driving_repo $DRIVING $BRANCH $CP_BRANCH $CHERRYPICK_COMMITS

"$DRIVING"/scripts/setup/setup.sh dev --tags bazel --no-ask-pass

get_deps_for_topic $PROTO_LOCATION $PROTO_NAME $DB_HOME $DEPS_FILE $DRIVING

if [[ $KAFKA_PROTO_NAME && $KAFKA_PROTO_LOCATION ]]; then
    echo "Append Kafka Topic dependent Protos into the Proto Destination";
    get_deps_for_topic $KAFKA_PROTO_LOCATION $KAFKA_PROTO_NAME $DB_HOME $DEPS_FILE $DRIVING true;
else
    echo "No Kafka proto file given, skip getting dependent protos for kafka topics";
fi

while read PROTO_DEF; do move_file_to_new_path $PROTO_DEF $PROTO_DESTINATION $DRIVING; done < $DEPS_FILE\.txt

cd $SBT_PROJECT_LOCATION

echo "========= CHECK IF PROTOS WERE SUCCESSFULLY COPIED OVER TO SBT PROJECT ========="
PROTO_FILES_COUNT=$(ls -lR $(pwd) | grep ".proto$" | wc -l)
echo "FOUND TOTAL OF $PROTO_FILES_COUNT FILES"

if [[ $PROTO_FILES_COUNT -eq 0 ]]; then
    echo "ABORT EXECUTION SINCE NO PROTO FILE IS FOUND";
    exit;
fi

sbt package

aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY

aws s3 cp $JAR_PATH\/$SOURCE_JAR_NAME $S3_DESTINATION_BUCKET\/$TARGET_JAR_NAME
