#!/usr/bin/env bash

# Runs PCP-CI on the current git SHA and the specified base-branch. When both
# runs are complete, a comparison report is generated and a link to it is
# displayed and saved to a temporary file (where text wrapping won't break
# up the URL).
#
# Usage:
#   ./experimental/jake/run_pcp_ci_pair.sh \
#       <base-branch> \
#       <unique-experiment-name>

source $wcd/scripts/shell/zooxrc.sh

BASE_BRANCH=$1
EXPERIMENT_NAME=$2

CURRENT_COMMIT=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
CURRENT_COMMIT_BRANCH="tmp/$CURRENT_COMMIT/$EXPERIMENT_NAME"
CURRENT_COMMIT_BRANCH=${CURRENT_COMMIT_BRANCH/master/mastar}

BASE_COMMIT=$(git merge-base $CURRENT_COMMIT $BASE_BRANCH)
BASE_COMMIT_BRANCH="tmp/$BASE_BRANCH/$EXPERIMENT_NAME"
BASE_COMMIT_BRANCH=${BASE_COMMIT_BRANCH/master/mastar}

echo "CREATING BRANCHES $BASE_COMMIT_BRANCH AND $CURRENT_COMMIT_BRANCH"
git branch $BASE_COMMIT_BRANCH $BASE_COMMIT
git branch $CURRENT_COMMIT_BRANCH $CURRENT_COMMIT

git push origin \
    +$BASE_COMMIT_BRANCH:$BASE_COMMIT_BRANCH \
    +$CURRENT_COMMIT_BRANCH:$CURRENT_COMMIT_BRANCH

echo "RUNNING PCP-CI on $BASE_COMMIT_BRANCH"
brun -c opt --config=cuda //lidar/metrics:run_perception_ci -- \
    --dm \
    --use-ftrace \
    --timing-only \
    --tag="control-for-${EXPERIMENT_NAME}" \
    --branch=$BASE_COMMIT_BRANCH

echo "RUNNING PCP-CI on $CURRENT_COMMIT_BRANCH"
brun -c opt --config=cuda //lidar/metrics:run_perception_ci -- \
    --dm \
    --use-ftrace \
    --tag="${EXPERIMENT_NAME}" \
    --branch=$CURRENT_COMMIT_BRANCH \
    --timing-only

PB_FILE="comparison_timing_stats.pb"
RESULTS=/mnt/sun-pcp01/perception_ci/results

function base_path() {
    local TIMESTAMP=$(ls $RESULTS/$BASE_COMMIT_BRANCH 2>/dev/null)
    BASE_PATH=$(echo $RESULTS/$BASE_COMMIT_BRANCH/$TIMESTAMP/timing_c2r_turing)
}

function current_path() {
    local TIMESTAMP=$(ls $RESULTS/$CURRENT_COMMIT_BRANCH 2>/dev/null)
    CURRENT_PATH=$(echo $RESULTS/$CURRENT_COMMIT_BRANCH/$TIMESTAMP/timing_c2r_turing)
}

base_path
current_path
while [[ ! -e $BASE_PATH || ! -e $CURRENT_PATH ]]; do
    echo Waiting for experiments to finish.
    sleep 600
    base_path
    current_path
done

BASE_PB_FILE=$BASE_PATH/$PB_FILE
CURRENT_PB_FILE=$CURRENT_PATH/$PB_FILE
while [[ ! -e $BASE_PB_FILE || ! -e $CURRENT_PB_FILE ]]; do
    echo Waiting for files to exist.
    sleep 600
    BASE_PB_FILE=$BASE_PATH/$PB_FILE
    CURRENT_PB_FILE=$CURRENT_PATH/$PB_FILE
done

URL="$(brun //base/report:compare_reports -- \
    --candidate $CURRENT_PATH/$PB_FILE \
    --control $BASE_PATH/$PB_FILE \
    --output_html $CURRENT_PATH/timing_comparison_with_merge_base.html \
    --output_pb $CURRENT_PATH/timing_comparison_with_merge_base.pb \
    --allow_y_count_diff | grep "View report at ")"
URL=${URL#*View report at }

echo
echo $URL
echo
