#!/bin/bash
# $Id: tagversion 2061 2006-11-28 12:53:00Z mc $
usage () {
    echo "tagversion, tag version in subversion"
    echo "options:"
    echo "  -h, --help:    this help"
    echo "  -n, --echo:    don't tag, just echo tag name"
    echo "  -u, --echourl: don't tag, just echo tag url (Subversion only)"
}

if ! svn    --version &>/dev/null ; then
    echo "ERROR: Unable to find the 'svn' subversion command line client!" >&2
    echo "       Please install the subversion package and try again."     >&2
    exit 1
fi
if ! sed    --version &>/dev/null ; then
    echo "ERROR: Unable to find the (GNU) 'sed' utility!"                  >&2
    echo "       Please install the sed package and try again."            >&2
    exit 1
fi
if ! getopt --version &>/dev/null ; then
    echo "ERROR: Unable to find the (GNU) 'getopt' utility!"               >&2
    echo "       Please install the util-linux package and try again."     >&2
    exit 1
fi


OPTIONS=`getopt --name $0 --options hnu --longoptions help,echo,echourl -- "$@"` || { usage; exit 1; }
eval set -- "$OPTIONS"
while true; do
    case "$1" in
	--)
	    shift
	    break
	    ;;
	-h|--help)
	    usage
	    exit
	    ;;
	-n|--echo)
	    ECHO=1
	    ;;
	-u|--echourl)
	    ECHOURL=1
	    ;;
    esac
    shift
done

p=`cat RPMNAME 2>/dev/null`
v=`cat VERSION 2>/dev/null | tr "." "_"`
if [ -z "$p" -o -z "$v" ]; then
    echo "Cannot find RPMNAME or VERSION in current directory:" >&2
    echo -n "  " >&2 ; pwd >&2
    exit 1
fi

# sed -n -e 's///;T;p;q'
# means: print just the line on which the subst succeeded

# URLs don't contain spaces so it's safe to use them as delimiters
svn info | sed -n -e 's@^URL: \(.*\)/\(limal-head\|limal-branches/[^/]*\)/\(.*\)$@\1 \2 \3@;T;p;q' | {
# the pipe creates a subshell. the variables will be lost when it's left
# therefore the {braces}
read REPOSITORY BRANCH MODULE
    
b=`echo "$BRANCH" | sed -n -e 's@^limal-branches/\([^/]*\)-Branch$@\1@;T;p'`
if [ "$b" ]; then
        n=`echo "$b" | sed -n -e 's@^SuSE-\([^/]*\)$@\1@;T;p'`
        if [ "$n" ]; then
                t=branch-$n-$v
        else
                t=branch-$b-$v
        fi
else
	t=stable-$v
fi

URL_t=$REPOSITORY/limal-tags/$t
URL_m=$URL_t/$MODULE
if [ "$ECHO" ]; then
	echo "$t"
elif [ "$ECHOURL" ]; then
	echo "$URL_m"
else
	echo "$p $t"
	svn mkdir --message "Created tag $t" $REPOSITORY/limal-tags/$t

	# create parent directories
	# (they may exist already)
	case $MODULE in
	    */*) MODULEPARENT=${MODULE%/*} ;;
	    *) MODULEPARENT="" ;;
	esac
	MDIR=""
	# this will iterate thru directory components of MODULEPARENT
	OIFS="$IFS"; IFS="/"
	for DIR in $MODULEPARENT; do
	    MDIR="$MDIR$DIR/"
	    svn mkdir --message "Created tag $t for $MDIR" "$REPOSITORY/limal-tags/$t/$MDIR"
	done
	IFS="$OIFS"

        svn copy --message "Created tag $t for $MODULE" "$REPOSITORY/$BRANCH/$MODULE" "${URL_t}/${MODULEPARENT}"
fi
}

