#!/bin/bash

# @(#) Release the dist/dev files which were created by Nexus2DistDev

# This script is intended to be run from the tag directory where the release was built
# It creates a script file for use by svnmucc

# Extract a property value from the pom
function scrapePom() {
  sed -n -e "s!.*<$1>\(.*\)</$1>.*!\1!p" pom.xml
}

# Assume the gid/aid/ver are second in the file (i.e. after the parent)
GID=$(scrapePom groupId | sed -n -e '2p' | tr '.' '/')
AID=$(scrapePom artifactId | sed -n -e 2p)
VER=$(scrapePom version | sed -n -e 2p)

echo $VER | fgrep -q -- '-SNAPSHOT' && { echo "Invalid (SNAPSHOT) version: $VER"; exit 1; }

# Extract the SVN dir name - this is also used for dist/dev tree
# TODO How to get this for Git-based projects?
SVNDIR=$(scrapePom developerConnection | sed -n -e 's!.*/proper/\(.*\)/tags.*!\1!p')

test -z "$SVNDIR" && { echo Could not extract SVNDIR; exit 1; }

RC=$(scrapePom commons.rc.version)

TAGNAMERC="${VER}_$RC"

DISTBASE=https://dist.apache.org/repos/dist

echo Checking if dev/commons/$SVNDIR/$TAGNAMERC exists
curl --head -f -sS $DISTBASE/dev/commons/$SVNDIR/$TAGNAMERC >/dev/null || exit
echo Found dev/commons/$SVNDIR/$TAGNAMERC

SVNMUCC=/tmp/${TAGNAMERC}.svnmucc

doMove() {
    echo "mv"
    echo "dev/commons/$SVNDIR/$TAGNAMERC/$1"
    echo "release/commons/$SVNDIR/$2$1"
}
doRemove() {
    echo "rm"
    echo "release/commons/$SVNDIR/$2$1"
}
handle() {
    NAME=${AID}-${VER}-$1.$2$3
    doMove $NAME $SUBDIR
}

{
SUBDIR=source/
for typ in src bin
do
    if [ $typ == 'bin' ]
    then
        SUBDIR=binaries/
    fi
    for arc in zip tar.gz
    do
        for suff in '' .asc .sha1 .md5
        do
            handle $typ $arc $suff || exit
        done
    done
done

# remove RN if already present
curl --head -f -sS $DISTBASE/release/commons/$SVNDIR/RELEASE-NOTES.txt >/dev/null 2>&1 && doRemove RELEASE-NOTES.txt

curl --head -f -sS $DISTBASE/dev/commons/$SVNDIR/$TAGNAMERC/RELEASE-NOTES.txt >/dev/null 2>&1 && doMove RELEASE-NOTES.txt

} > $SVNMUCC

cat<<EOD
svnmucc --no-auth-cache --message "Release $VER from $RC" \
--root-url ${DISTBASE} \
--extra-args $SVNMUCC
EOD
echo Review the $SVNMUCC file and commit it using the above command line