#!/bin/bash

# build script for CMSimple_XH
# creates RELEASE.zip in the root of the working copy
# version $Id$

# exit on error
set -e

# define the relevant files
README_FILES="CITAJ.txt CTIMNE.txt LAESMIG.txt LIESMICH.txt README.txt README_RU.txt"
VI_FILES="\
    cmsimple/adm.php\
    cmsimple/cms.php\
    cmsimple/functions.php\
    cmsimple/login.php\
    cmsimple/mailform.php\
    cmsimple/search.php\
    plugins/index.php\
    plugins/filebrowser/admin.php\
    plugins/pluginloader/page_data/index.php\
    plugins/pluginloader/page_data/page_data_model.php\
    plugins/pluginloader/page_data/page_data_router.php\
    plugins/pluginloader/page_data/page_data_views.php\
    plugins/tinymce/admin.php\
    $README_FILES"

# display usage info and exit with error
function usage {
    echo "usage: $0 [options] version"
    echo "options:"
    echo "  -b build    : daily build number (defaults to 01)"
    echo "  -o filename : name of the created zip file (defaults to RELEASE.zip)"
    exit 1
}

# process command line arguments
build=01
ofile=RELEASE
while getopts ":b:o:" opt; do
  case $opt in
    b)
        build=$OPTARG
        ;;
    o)
        ofile=$OPTARG
        ;;
    \?)
      echo "invalid option: -$OPTARG" >&2
      usage
      ;;
  esac
done
version=${*:$OPTIND}
if [ "$version" = '' ]
then
    echo "version missing"
    usage
fi

# export working copy
echo "exporting working copy..."
svn export -q . cmsimplexh/

# fix version info
echo "fixing version info..."
CMSIMPLE_XH_VERSION="CMSimple_XH $version"
CMSIMPLE_XH_BUILD=`date +%Y%m%d`$build
CMSIMPLE_XH_DATE=`date +%Y-%m-%d`
for i in $VI_FILES; do
    sed -i "s/\\\$CMSIMPLE_XH_VERSION\\\$/$CMSIMPLE_XH_VERSION/" cmsimplexh/$i
    sed -i "s/\\\$CMSIMPLE_XH_BUILD\\\$/$CMSIMPLE_XH_BUILD/" cmsimplexh/$i
    sed -i "s/\\\$CMSIMPLE_XH_DATE\\\$/$CMSIMPLE_XH_DATE/" cmsimplexh/$i
done

# remove files that shouldn't be included in release
rm cmsimplexh/build

# create zip file
echo "zipping..."
ff=""
for f in $README_FILES; do
    ff="$ff cmsimplexh/$f"
done
echo $ff
zip -rq $ofile cmsimplexh/ -x $ff
zip -jlq $ofile $ff

# clean up
echo "cleaning up..."
rm -r cmsimplexh/

# finish
echo "ready!"
