#!/bin/bash

PROGDIR=$(dirname $(readlink -f $0))

export JAVA_HOME=/opt/java
export PATH="$JAVA_HOME/bin:$VIRTUAL_ENV/bin:/bin:/usr/bin:/usr/local/bin:$PROGDIR"
export LANG=en_GB.UTF-8

typeset -i VERSION
typeset -i MIN_VERSION

while getopts "d:" c
do
	case $c in
	d) SNAPDIR=$OPTARG;;
	esac
done
shift $[OPTIND-1]

PRODUCT=$1
if [ "$PRODUCT" = "" ]; then
	echo Usage: "mksnapbranches [-d dir] [-r vers] <product>"
	exit
fi

source mksnapfuncs

export LANG=en_GB.UTF-8

SVN=http://svn.mkgmap.org.uk/$PRODUCT
SNAPDIR=${SNAPDIR:-$HOME/www/mkgmap.org.uk/docroot/download}

# Get the commit time of the given path
svn_get_time() {
	typeset time
	time=$(svn log --xml --limit 1 $SVN/$1 2> /dev/null | sed \
		-n -e 's/<date>\(.*\)<\/date>/\1/;s/T/ /;s/Z/+0000/p'
		)
	date -d"$time" +%s
}

# We ignore all branches older than 90 days
MIN_TIME=$(svn_get_time trunk)
((MIN_TIME=MIN_TIME - 3600*24*90))

BRANCHES=$(svn ls $SVN/branches)
for branch in $BRANCHES
do
	BRANCH=${branch%/}
	BRANCH_TIME=$(svn_get_time branches/$BRANCH)

	if [ $BRANCH_TIME -lt $MIN_TIME ]; then
		echo Too old ignoring $BRANCH
		continue
	fi

	echo Building $BRANCH
	redis-cli lpush svn:build build:$PRODUCT:$BRANCH:
done
