#!/bin/bash


RHOME=$PWD

PROJ=geronimo
BIN_DIR=${2:-modules/assembly/target}
DIST=${3:-$RHOME/dist}

export SVN_URL='http://svn.apache.org/repos/asf/geronimo'
export REPO_USER=dblevins
export REPO_DIR=/www/cvs.apache.org/repository
export REPO=apache.org
export VN='1.0'
export RELEASE_DIR=/www/cvs.apache.org/dist/geronimo

SVN_VERSION=$(wget -q -O - $SVN_URL/trunk | grep title | sed 's/[^0-9]//g')
VERSION="$VN-$SVN_VERSION"
RELEASE_ID="$PROJ-$VERSION"
VERSION_DIR="$RELEASE_DIR/unstable/$VERSION"

echo "RELEASE $RELEASE_ID"
    
### Utility functions ########
function shash { openssl $1 < $2 > $2.$1 ;}
function fail () { echo $1 >&2; exit 1;}
function package () { 
    DEST=$1; SOURCE=$2
    tar czf $DEST.tar.gz $SOURCE
    zip -9rq $DEST.zip $SOURCE
}
function sign {
    archive=$1
    {
	perl -ne 'print unpack("u30", $_);'| 
	gpg --passphrase-fd 0 --armor --output $archive.asc --detach-sig $archive
    } < $HOME/.gnupg/.phrase
    gpg --verify $archive.asc $archive
}
function replace_version { # VERSION, PROJ
    local PROJ=${1?Must specify a project name}
    local VERSION=${2?Must specify a new version name}

    perl -i.bak -pe "s/(${PROJ}_version)=.*/\$1=${VERSION}/" etc/project.properties
    perl -i.bak -pe "s/<(currentVersion)>[^<]*<\/currentVersion>.*/<\$1>${VERSION}<\/\$1>/" plugins/maven-geronimo-plugin/project.xml

}
##############################

svn checkout --revision $SVN_VERSION $SVN_URL/trunk $RELEASE_ID
find $RELEASE_ID -name '.svn' -exec rm -rf {} \;
( cd $RELEASE_ID && replace_version $PROJ $VERSION )

###############
# checkout tag to dir named geronimo-1.0-M4
# svn export 

##############################
# SOURCE DISTRO
package $DIST/${RELEASE_ID}-src $RELEASE_ID || fail "Unable to create source binaries"

##############################
# BUILD DISTRO
( cd $RELEASE_ID && maven -o -Dmaven.test.skip=true -Dmaven.itest.skip=true) || fail "Build failed"
( cd $RELEASE_ID/$BIN_DIR && package $DIST/${RELEASE_ID} $RELEASE_ID ) || fail "Unable to make binary archives"

##############################
# MAKE WARM FUZZIES
for archive in $DIST/*.{zip,tar.gz}; do
    echo $archive
    sign $archive 
    shash md5 $archive
#    shash sha $archive
done || fail "Unable to sign or hash release archives"

##############################
# MAKE DIR FOR RELEASE

REPO_URL=$REPO_USER@$REPO
VERSION_DIR=$RELEASE_DIR/unstable/$VERSION

echo "Making dir $VERSION_DIR"

(ssh $REPO_URL  mkdir $VERSION_DIR ) || fail "Unable to create the release dir $VERSION_DIR"

##############################
# UPLOAD RELEASE 
(scp $DIST/${RELEASE_ID}* $REPO_URL:$VERSION_DIR) || fail "Unable to upload the binaries to release dir $VERSION_DIR"

cd $RELEASE_ID || fail "Cannot enter release dir $RELEASE_DIR"

# jar:deploy