#!/usr/bin/env bash
set -x

WEBDIR=$SA_WEBDIR
test -n "$WEBDIR"  || WEBDIR=$HOME/site

if [ ! -d $WEBDIR ] ; then
	echo "WARNING: $WEBDIR does not exist" 1>&2
	echo 1>&2
fi

GPGSIGN=$SA_GPGSIGN
test -x "$GPGSIGN" || GPGSIGN=$HOME/sabuildtools/bin/gpgsign

MD5SUM=md5sum
# test -x "$MD5SUM" || MD5SUM=md5	# odd output fmt
test -x "$MD5SUM" || MD5SUM=perl_md5sum

SHA1SUM=sha1sum
test -x "$SHA1SUM" || SHA1SUM=perl_sha1sum

DEVDIR=$WEBDIR/devel
RELDIR=$WEBDIR/released
mkdir -p $DEVDIR $RELDIR

DISTNAME=Mail-SpamAssassin

rm -rf $DISTNAME-*               # otherwise make will fail

make distclean
perl Makefile.PL < /dev/null || exit $?

make version.env || exit $?
. version.env

# $VERSION will be x.y.z for released not marked $IS_DEVEL_BUILD, else
# x-y-latest while $DIST_VERSION is always the x.y.z variant.
VERSION=`echo $FULL_VERSION | perl -pe 's/\.\d+(-.*)-r\d+$/-dev/'`

DISTDNAME=$DISTNAME-$DIST_VERSION
DISTVNAME=$DISTNAME-$VERSION

# delete old CVS files
find . -name '.#*' -print | xargs rm -f

make || exit $?

make text_html_doc
make distcheck

echo $VERSION > $WEBDIR/latest_version

rm -f $DISTVNAME.*

make distdir || exit $?
tar -cWvf   $DISTVNAME.tar $DISTDNAME         || exit $?

gzip  -f9vc $DISTVNAME.tar > $DISTVNAME.tar.gz  || exit $?
bzip2 -f9vc $DISTVNAME.tar > $DISTVNAME.tar.bz2 || exit $?
zip   -rv - $DISTDNAME     > $DISTVNAME.zip     || exit $?


perl_md5sum () {
  perl -e 'use Digest::MD5 qw(md5_hex); print md5_hex(`cat $ARGV[0]`)."  ".$ARGV[0]."\n";' $*
}
perl_sha1sum () {
  perl -e 'use Digest::SHA1 qw(sha1_hex); print sha1_hex(`cat $ARGV[0]`)."  ".$ARGV[0]."\n";' $*
}

for ext in tar.bz2 tar.gz zip ; do
  cp $DISTVNAME.$ext $DEVDIR

  $MD5SUM  $DISTVNAME.$ext > $DEVDIR/$DISTVNAME.$ext.md5  || exit $?
  $SHA1SUM $DISTVNAME.$ext > $DEVDIR/$DISTVNAME.$ext.sha1 || exit $?

  rm -f $DISTVNAME.$ext.asc*
  if [ -x "$GPGSIGN" ]; then
    $GPGSIGN $DISTVNAME.$ext                           || exit $?
    mv $DISTVNAME.$ext.asc $DEVDIR/$DISTVNAME.$ext.asc || exit $?
  fi

  rm -f $DISTVNAME.$ext
done

test -f Makefile && make distclean

# ( cd $DEVDIR && svn add *SpamAssassin* )

ls -l $DEVDIR

