#!/bin/sh
#
#
# This script reads the changelog of a subversion repository
# and outputs FTP commands to mirror the changes on a remote
# directory.
# You will need to have lftp installed to use this scripts.
# 

# The name of the bookmark to use in lftp
BOOKMARK_NAME="$1"

# Working copy to use to transfert the files
WC_DIR="$2"

# The local repository directory (as passed to the hook script)
REPOS="$3"
# The repository version (as passed to the hook script)
REV="$4"


## Configuration
#

# Mirror this directory in the repository (relative to /)
REPOS_DIR="trunk/"

# Explicitly set HOME for use by lftp (to enable it to locate its bookmarks file)
export HOME="/home/reivax"

# The name of the file the FTP commands will temporarely be written to.
CMD_FILE="$HOME/svn/tmp/${BOOKMARK_NAME}-$(date +%Y%m%d%H%M%S)"

# Keep a copy of the commands in a log file. Log nothing if no file is given.
LOG_FILE="$HOME/svn/log/${BOOKMARK_NAME}.log"

#
## End of configuration


# Check script arguments
if [ -z "$REPOS" -o -z "$REV" ]; then
  echo "Usage: $(basename $0) REPOSITORY REVISION"
  exit 1
fi

# Redirect output to $CMD_FILE and errors to $LOG_FILE.err
exec >> $CMD_FILE 2> $LOG_FILE.err

echo -n "# " && date
echo "open $BOOKMARK_NAME"


# Now we look at what changed in the latest version of the repository 
# and generate the matching FTP command.

svnlook changed -r "$REV" "$REPOS" | \
while read a f
do

  f=$(echo "$f" | sed -e "s|^$REPOS_DIR||")

  case $a in

    A|U)
	# add or update file or directory
	if expr "$f" : '.*/$' > /dev/null
        then
	  # the file is a directory
	  echo "mkdir $f"
	else
	  # the file is a regular file
	  echo "put $f -o $f"
	fi
	;;

    D) 
	# remove
	echo "rm $f" 
	;;

    *) 
	# we don't know this action, so we ignore it verbosely
	echo "unknown action $a on file $f" >&2
	;;

  esac

done

# End of command list
echo "exit"

# Execution des commandes FTP
cd "$WC_DIR"
lftp -f $CMD_FILE

# Copie des commandes dans le fichier de log
if [ -n "$LOG_FILE" ]; then
  cat $CMD_FILE >> $LOG_FILE
fi

# Suppression du fichier des commandes FTP
rm -f $CMD_FILE

