#!/bin/bash
# svn helper functions for bash
#
# usage:
# invoke this script from your .bashrc to set up helper functions for working
# with subversion on openlaszlo. 
# See README.txt in this directory. 
# author: benjamin shine
# last modified: 2006-05-04

export EDITOR=${EDITOR:-"vim"}

# Start the process off with an empty change description file. This file is
# created in /tmp, and you can copy it where ever you want. Leave it in /tmp
# at your own risk; files in /tmp are sometimes deleted. 
function empty-change-description() {
    TMPFILE=`mktemp /tmp/change-description.XXX`
    cat << EOF > $TMPFILE
Summary: <enter description here>

New Features:
Bugs Fixed:
Technical Reviewer: (pending)
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details: 
Tests:
EOF
    chmod ugo+r $TMPFILE
    echo "$TMPFILE"
    export OL_CHANGE_DESCRIPTION=$TMPFILE
}

function svn-editchange() {
    $EDITOR $OL_CHANGE_DESCRIPTION
}

function svn-makechangepackage() {
    PATCHDIR=`mktemp -d /tmp/patchdir.XXXX`
    THEDIFF=${PATCHDIR}/difffile
    THEFILELIST=${PATCHDIR}/filelist.txt    
    THEAPPLYSCRIPT=${PATCHDIR}/apply.sh
    CURDIR=`pwd`
    THETAR=`mktemp ${CURDIR}/patch.tar.XXXX`
    
    # Append a list of the currently changed files to the change description
    echo "====== Affected files =======" > ${THEFILELIST}
    svn status -q >> ${THEFILELIST}
    # Create a patch which exactly describes the local changes to the files
    svn diff > ${THEDIFF}
    # Create a script which will apply the patch
    echo "patch -bu -p0 -i `basename ${THEDIFF}`" > ${THEAPPLYSCRIPT}
    chmod ugo+x $THEAPPLYSCRIPT
    
    # Make an archive with the apply script, the change description, and the patch itself. 
    cd ${PATCHDIR}
    tar --preserve -cf ${THETAR} `basename ${THEAPPLYSCRIPT}` `basename ${THEFILELIST}` $OL_CHANGE_DESCRIPTION `basename ${THEDIFF}` 
    
    # Go back to the directory we started from
    cd ${CURDIR}
    echo "Created ${THETAR}"
}


# Compose review mail for a change
# Arguments: [changedescriptionfile]
# If no arguments are specified, it uses $OL_CHANGE_DESCRIPTION
function svn-review()
{
    change=${1:-$OL_CHANGE_DESCRIPTION}
    tmp=`mktemp tmp-desc.XXX`
    cat $change > ${tmp}
    echo "Files: " >> ${tmp}
    svn status -q >> ${tmp}
    mailto=`cat $tmp | perl ${LZ_TOOLS_HOME}/svn/review-mail.pl`
    # mac specific, use your platform's url opener
    # --- explodes on long urls
    # open $mailto
    case `uname` in
	"Darwin") 
	    open "${mailto}" ;;
	* )
	    echo "Paste the following message into your mail program:"
	    echo ${mailto}
	    ;;
    esac
}


function svn-unapplychangepackage() {
    patch -p0 -R -i difffile
}

# List the status of locally changed files
function svn-changed() {
    svn status | grep "[:space:]*[MDACR\!-][:space:]*" 
}

function svn-needs-update() {
   svn status -u | grep "[:space:]*\*[:space:]*"
}
