#!/bin/bash -e

# After the Mac and Windows Release builds have been built, this
# script creates the releasable .zip version of the project.  

VERSION="2.0"

PRGLOC="`cd $(dirname $0)/../..;pwd`"

echo "Updating project and getting revision number..."

# If we have a subversion working directory in pregex/project, update
# and get the latest revision number in pregex_rev_number.txt

# This script will refuse to run if svn status is not clean (though
# this file itself can be under development -- that's just a warning).

REVNUMFILE="$PRGLOC/xtras/pregex_rev_number.txt"
(cd "$PRGLOC/project"; svn update || true)		## OK to fail if we are offline
(cd "$PRGLOC/project"; svn status | grep -v make_dist.bash | \
    perl -0777 -ne 'die "FAILURE: Refusing to build because svn status is not clean.\n" if m{\w}') || exit 1
(cd "$PRGLOC/project"; svn status | grep make_dist.bash | \
    perl -0777 -ne 'warn "WARNING: Remember to check in make_dist.bash before doing final distribution build!\n" if m{\w}') || true
(cd "$PRGLOC/project"; svn info ./source/re_main.cpp || true) | \
    perl -mIO::File -ne "IO::File->new(qq{>$REVNUMFILE})->print(sprintf('%04d', \$1)) if m{Revision: (\d+)}"

# Whether we just retrieved it successfully or not, get the
# best/latest one we have.

if [ ! -f "$REVNUMFILE" ]; then echo "FAILURE: Could not find or create rev number file '$REVNUMFILE'"; exit 1; fi
REVNUM=`cat "$PRGLOC/xtras/pregex_rev_number.txt"`

echo "Making a distribution directory..."

mkdir -p "$PRGLOC/build_dist/pregex/xtras/"
mkdir -p "$PRGLOC/build_dist/pregex/project/"

rsync -ra --delete "$PRGLOC/.DS_Store"   "$PRGLOC/build_dist/pregex/xtras/.DS_Store" || true
rsync -ra --delete "$PRGLOC/xtras/"      "$PRGLOC/build_dist/pregex/xtras/"
rsync -ra --delete "$PRGLOC/project/"    "$PRGLOC/build_dist/pregex/project/" \
    --exclude="*.svn*" \
    --exclude="*.ncb" --exclude="*.suo" \
    --exclude="*.pbxuser" --exclude="*.mode1v3" \
    --exclude="*~" --exclude="*#" \
    --delete-excluded

TIMESTAMP=`perl -e 'use POSIX; print strftime("%Y%m%d", localtime())'`
ZIPNAME="pregex-v$VERSION-rev-$REVNUM-$TIMESTAMP.zip"

echo "Creating zip file..."

(cd "$PRGLOC/build_dist"; rm -vf $ZIPNAME; zip -qq -r -o "$ZIPNAME" pregex)

echo "Created '$PRGLOC/build_dist/$ZIPNAME'"

echo "Revealing in Finder..."
open "$PRGLOC/build_dist"
