#!/bin/bash -l

# David Strubbe, March 2012, UC Berkeley
# Script to automagically backport a commit from trunk to a branch.
# Usage (from checked-out version of branch): sh backport.sh revision#
# Has been tested for svn versions 1.6, 1.7, 1.8

if [ $# -ne 1 ]; then
    echo "Usage: $0 revision"
    exit
fi

# Without this, svn 1.8 may give an error such as:
#svn: E195020: Cannot merge into mixed-revision working copy [5751:5752]; try updating first
svn update

#Sample output from svn info with subversion 1.6
#Path: .
#URL: https://civet.berkeley.edu/svn/BerkeleyGW/trunk
#Repository Root: https://civet.berkeley.edu/svn/BerkeleyGW
#Repository UUID: f37f1971-f941-45b3-b7f3-995b68ab9ef1
#Revision: 5160
#Node Kind: directory
#Schedule: normal
#Last Changed Author: dstrubbe
#Last Changed Rev: 5160
#Last Changed Date: 2013-02-23 11:57:20 -0500 (Sat, 23 Feb 2013)

#Sample output from svn info with subversion 1.7 -- as above, except after Path comes also:
#Working Copy Root Path: /Users/dstrubbe/Software/BerkeleyGW

#Sample output from svn info with subversion 1.8 -- as above, except after URL comes also:
#Relative URL: ^/trunk

# e.g. https://civet.berkeley.edu/svn/BerkeleyGW
Root=`svn info | grep "Repository Root" | awk '{print $3}'`
# e.g. https://civet.berkeley.edu/svn/BerkeleyGW/branches/1.0.x
URL=`svn info | grep URL | awk '{print $2; exit}'`
# e.g. branches/1.0.x
Branch=${URL#$Root/}

echo "svn merge -c $1 $Root/trunk ."
svn merge -c $1 $Root/trunk . --accept postpone --quiet

# Common/svninfo.90 will always be in conflict.
# --accept postpone avoids an interactive query of what to do
# --quiet suppresses any output about that fact.
# Now we resolve that file. Any other conflicts will be left alone
# for the user to decide what to do, however, and shown below.
svn revert Common/svninfo.f90 --quiet

# Make our own change to svninfo.f90
sed "s/! Modify text here before making a commit -->.*/! Modify text here before making a commit --> r$1 is decommissioned/" < Common/svninfo.f90 > tmp
mv tmp Common/svninfo.f90

# We will accumulate annoying and useless merge tracking properties otherwise
svn revert . --quiet

echo
echo "Compiling with make all ..."
make all
echo "===== svn status ====="
svn status

echo "Backport of $1 to $Branch:" > svn-commit.tmp
svn log $Root -r $1 >> svn-commit.tmp

echo
echo "===== log message ====="
cat svn-commit.tmp

echo
echo "Ok to commit? [y/n]"
read response

if [ "$response" = "y" ]; then
# remove temporary file, but only if commit succeeds
  svn commit --file=svn-commit.tmp && rm -f svn-commit.tmp
else
  echo "Not committing."
fi
