#!/usr/bin/env bash

set -euo pipefail

if [[ $# != 1 ]]; then
    echo 'USAGE: continuum_integration_test.bash <DRIVING-BRANCH>'
    exit 1
fi

DRIVING_BRANCH=$1

TIME=$(date +%s)
DRIVING_TEST_BRANCH=$DRIVING_BRANCH-driving-$TIME
CONTINUUM_TEST_BRANCH=$DRIVING_BRANCH-continuum-$TIME

tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/$(basename $0).XXXXXXXX")
trap "rm -rf \"${tmpdir}\"" EXIT
pushd $tmpdir

eval $(ssh-agent)
ssh-add

git clone git@git.zooxlabs.com:zooxco/driving.git
pushd driving
git fetch origin $DRIVING_BRANCH develop/continuum-submodule-staging
git checkout -b $DRIVING_TEST_BRANCH origin/develop/continuum-submodule-staging
set +e
git merge origin/$DRIVING_BRANCH
success=$?
set -e
if [[ $success != 0 ]]; then
    echo
    echo 'Handle any merge conflicts, commit, then call "exit".'
    echo
    bash
fi
git push origin $DRIVING_TEST_BRANCH
popd

git clone git@git.zooxlabs.com:zooxco/continuum.git
pushd continuum
git submodule update --init --recursive
git checkout -b $CONTINUUM_TEST_BRANCH
cd Engine/Source/ThirdParty/Zoox/driving
git pull origin $DRIVING_TEST_BRANCH
cd ../driving_build
./regenerate_build_files_from_bazel.sh
git add ./ ../driving
git commit -m "Continuum-Driving integration test of $DRIVING_BRANCH"
git push origin $CONTINUUM_TEST_BRANCH
echo
echo 'Navigate to http://bamboo.zooxlabs.com/browse/CTN-COPR'
echo 'Log in then click Run -> Run customized...'
echo 'and use the following for "revision":'
git rev-parse HEAD
popd
