#!/bin/bash
#
# Build the monit.tar.gz package
#

clean_up() 
{
 rm -f $CONFIGURE_OBJS
 rm -f $MAN_OBJS
 rm -f pod2* 
 rm -fr ./autom4te*
 rm -f log
}

# Get version from the configure.ac file
VERSION=`perl -ne 'if(/AC_INIT.*\[(\w)([\.\w]+)\]/){print"$1$2\n";}' configure.ac`
# Get current dir. must be named monit
WORKDIR=`basename $PWD`
# The relase string
RELEASE="${WORKDIR}-${VERSION}"
# The tar.gz file name
TARGET=$RELEASE.tar.gz

# Objects created by configure
CONFIGURE_OBJS="Makefile config.cache config.log config.h config.h.in \
		confdefs.h config.status configure"

# Man-file objects
MAN_OBJS="*.1"

# Create the Makefile
autoconf
./configure 

# -------------------------
# Create html documentation
# -------------------------
rm -f doc/api-docs/*
perl -pi.bak -e 's/\@VERSION\@/'$VERSION'/' doxygen.cfg
make doc
mv doxygen.cfg.bak doxygen.cfg

# Create the monit man html file in doc
pod2html monit.pod > doc/monit.html

# Copy the the examples file to doc.
cp web/examples.html doc/
chmod 644 doc/examples.html

# Cleanup before build
rm -f *.tar.gz
make devclean
clean_up

# -----------------------------
# Set standard file permissions
# -----------------------------
chmod 600 monitrc

# -------------
# Build package
# -------------
./make_man     # man files
./autogen.sh   # configure, config.h.in
make distclean # Keep only the relevant files

# Build the dist file using current version in filename
cd ..
mv $WORKDIR $RELEASE # Rename the monit dir to include the version number
tar zcvfX ${TARGET} $RELEASE/exclude $RELEASE # Create the tar file
mv $RELEASE $WORKDIR # Rename the work dir. back to monit
mv $TARGET $WORKDIR # Move the tar.gz package into work dir.
cd $WORKDIR

# cleanup
clean_up
