#!/bin/bash
# Create the Mail::Box module.
# This scripts produces a module (sources) as can be transfered to CPAN,
# and an archive (raw) for the files where the manuals are created from:
# the raw input file.  The latter requires a MANIFEST.extra file which
# contain the additional filenames.

VERBOSE=$1

#### Synchronize these variables with those defined in mkdoc
DIST=/tmp/MailBox    # where the module's distribution is being built

#### Other constants
SOURCES=public_html/mailbox/source
RAW=public_html/mailbox/raw
HTML=public_html/mailbox/html

MANIFESTS="MANIFEST MANIFEST.extra"
EXAMPLE_OODOC=../OODoc/examples/mailbox.tar.gz

[ -d $DIST ] || mkdir $DIST || exit $?

#
# Produce mailbox example
#

[ -n "$VERBOSE" ] && echo "* Packaging Mail::Box setup as example for OODoc";
tar -czf $EXAMPLE_OODOC README.oodoc mkdist mkdoc html || exit $?

#
# Produce the manual pages using OODoc
#

./mkdoc $VERBOSE || exit $?

#
# Create a distribution
#

[ -n "$VERBOSE" ] && echo "* Run make to see if everything works"

( cd $DIST              || exit $?

  perl Makefile.PL      || exit $?
  make >/dev/null       || exit $?
  make test             || exit $?
  make dist >/dev/null  || exit $?
)

#
# Publish PRODUCED distribution on the private website
#

DISTNAME=$(cd $DIST; ls -rt *.tar.gz | tail -1)
[ -n "$VERBOSE" ] && echo "* Publishing $DISTNAME"

[ -d $SOURCES ] || mkdir $SOURCES || exit $?

if ! cp $DIST/$DISTNAME $SOURCES/
then ERROR=$?
     echo "Could not copy $DISTNAME from $DIST to $SOURCES: $ERROR" >&2
     exit $ERROR
fi

( cd $SOURCES
  [ -n "$VERBOSE" ] && ls -l $DISTNAME
  ln -sf $DISTNAME source-current.tar.gz || exit $?
)

#
# Publish the RAW module data (including the raw manual information) to
# the website
#

[ -d $RAW ] || mkdir $RAW || exit $?

RAWNAME=$(echo "$DISTNAME" | sed 's/\.tar\.gz/-raw.tar.bz2/')
[ -n "$VERBOSE" ] && echo "* Publishing $RAWNAME"

if ! tar -cjf $RAW/$RAWNAME $(cat $MANIFESTS)
then ERROR=$?
     echo "Could not create $RAWNAME in $RAW: $ERROR" >&2
     exit $ERROR
fi

( cd $RAW
  [ -n "$VERBOSE" ] && ls -l $RAWNAME
  ln -sf $RAWNAME raw-current.tar.bz2 || exit $?
)

#
# Publish the HTML as package
#

HTMLNAME="html-current.tar.gz"

( cd $HTML || exit $?
  [ -n "$VERBOSE" ] && echo "* Publishing $HTML/$HTMLNAME"
  tar -czf $HTMLNAME $(cat MANIFEST) || exit $?
)
  
[ -n "$VERBOSE" ] && ls -l $HTML/$HTMLNAME

#
# READY
#

[ -n "$VERBOSE" ] && echo "* Ready";

exit 0
