#!/usr/bin/env bash

DRY=0
if [[ $1 == "--dry-run" ]]; then
  DRY=1
elif [[ "$1" != "" ]]; then
  echo "Invalid option: $1"
  echo "Did you mean '--dry-run'?"
  exit
fi

do_go_on() {
read -p "Continue? "
if [[ $REPLY != "y" ]]; then
  echo "Exiting..."
  exit
fi
}

git() {
  REALGIT=$(which git)
  if [[ $DRY -eq 1 ]]; then
    echo git $*
  else
    $REALGIT $*
  fi
}

set_m1_10kph_config="a4a1b37a8a5add5fcf56e04c3a06e47dfaeb7b15"
set_m1_14kph_config="a77c3423c2dbfb5209f90f027e86b5954f608006"
set_m1_22kph_config="d467ac9f91c271a37639611b9acb08c1e2d9e4e9"
set_m1_30kph_config="f324bf992c6332f16380d4bd8ee19bdaa7eeec2e"
set_m2_estop_margins="9572842ac19d0592532cbd0428e3aa268ae4fa2e"
set_increased_follow_distance_config="7c3a3f66f816ee7cfe2f6211e377254c3a3d7a58"

scenario=(
  "there is no scenario zero"
  "$set_m1_10kph_config"
  "$set_m1_14kph_config"
  "$set_m1_22kph_config"
  "$set_m1_30kph_config $set_m2_estop_margins $set_increased_follow_distance_config"
  "$set_m2_estop_margins $set_increased_follow_distance_config"
)

echo Cleaning up release/21.18
git fetch origin release/21.18
git checkout origin/release/21.18
git checkout -B release/21.18

for idx in 1 2 3 4 5; do
  echo Executing scenario $idx ...
  git branch -D rfagen/21.18_scenario_$idx
  git checkout release/21.18
  git checkout -b rfagen/21.18_scenario_$idx
  for commit in ${scenario[$idx]}; do
    git cherry-pick -x --rerere-autoupdate $commit
    if [[ $? -ne 0 ]]; then
      echo "resolve the conflict, execute 'git cherry-pick --continue' and exit"
      bash --norc
    fi
  done
  git push origin --set-upstream rfagen/21.18_scenario_$idx
  echo Scenario $idx complete.
  #do_go_on
done

timestamp=$(date +%s)
showlog="cherry-show.${timestamp}.log"
difflog="cherry-diff.${timestamp}.log"
for idx in 1 2 3 4 5; do
  echo ==============================================>> $difflog
  echo Scenario $idx>> $difflog
  echo ==============================================>> $difflog
  echo ==============================================>> $showlog
  echo Scenario $idx>> $showlog
  echo ==============================================>> $showlog
  echo ________________________________ >> $showlog
  echo git show ${scenario[$idx]} >> $showlog
  echo ________________________________ >> $showlog
  git show ${scenario[$idx]} >>  $showlog
  echo ________________________________ >> $difflog
  echo git diff rfagen/21.18_scenario_$idx origin/release/21.18 >> $difflog
  echo ________________________________ >> $difflog
  git diff rfagen/21.18_scenario_$idx origin/release/21.18 >> $difflog
done

diff -y *${timestamp}* > cherry-diff-show-${timestamp}.log
less cherry-diff-show-${timestamp}.log
