#!/bin/bash
#
# Make the SWI-Prolog source archives by running this script. Before
# you start:
#
#	* Update VERSION
#	* Run ./newversion, which creates a GIT tag VN.N.N
#	* Run ./make-src-tape
#
# This script requires GNU-tar!

COREMODULES="bench packages/chr packages/clpqr packages/inclpr packages/jpl"
COREMODULES+=" packages/xpce packages/odbc packages/protobufs packages/windows"
COREMODULES+=" packages/sgml packages/clib packages/http packages/plunit"
COREMODULES+=" packages/pldoc packages/RDF packages/semweb packages/ssl"
COREMODULES+=" packages/zlib packages/tipc packages/table packages/ltx2htm"
COREMODULES+=" packages/nlp packages/cpp packages/PDT packages/utf8proc"
COREMODULES+=" packages/archive packages/swipl-win packages/pengines"
COREMODULES+=" packages/cql packages/bdb packages/readline packages/libedit"
COREMODULES+=" packages/pcre packages/yaml packages/paxos"

if [ -r modules ]; then
  SUBMODULES="`cat modules`"
else
  SUBMODULES="$COREMODULES"
fi

name=swipl
namesep=-
version=`cat VERSION`
compress=gzip
me=`basename $PWD`
quiet=false

TAG="V$version"

usage()
{ cat << _EOM_
Usage: $(basename $0) [option ...]
Options:
  --tag=Tag
    Create archive for the given version
  --version=Version
    Create archive for the given version
  --name=Name [default $name]
    Create archive for the given version
  --sep=Sep [default $namesep]
    Separator between name and version
  --submodule=Module
    Add an additional module (can be repeated)
  --quiet
    Work silently
  --help
    Print this message
_EOM_
}

while [ x"$1" != x"" ]; do
  case "$1" in
      --tag=*)
	  TAG=`echo $1 | sed 's/--[^=]*=//'`
	  shift
	  ;;
      --submodule=*)
	  SUBMODULES+=" $(echo $1 | sed 's/--[^=]*=//')"
	  shift
	  ;;
      --name=*)
	  name=`echo $1 | sed 's/--[^=]*=//'`
	  shift
	  ;;
      --sep=*)
	  namesep=`echo $1 | sed 's/--[^=]*=//'`
	  shift
	  ;;
      --version=*)
	  version=`echo $1 | sed 's/--[^=]*=//'`
	  shift
	  ;;
      --quiet)
	  quiet=true
	  shift
	  ;;
      --help)
	  usage
	  exit 0
	  ;;
      --*)
	  usage
	  exit 1
	  ;;
      *)
  esac
done

if ! git diff --quiet; then
    echo "Fatal: directory is dirty"
    exit 1
fi

prefix=$name$namesep$version
out=$prefix.tar

# core SWI-Prolog snapshot from GIT
git archive --format=tar --prefix=$prefix/ "$TAG" > ../$out

#add the submodules
for sm in `git submodule status $SUBMODULES | awk '{printf "%s:%s\n", $1, $2}'`; do
    sha1=`echo $sm | awk -F: '{print $1}'`
    path=`echo $sm | awk -F: '{print $2}'`
    [ $quiet = true ] || echo -n "adding module $path at $sha1 ... "
    git --git-dir $path/.git archive --format=tar --prefix=$prefix/$path/ $sha1 > tmp.tar
    tar -Af ../$out tmp.tar
    rm tmp.tar
    [ $quiet = true ] || echo ok
done

cd ..
ln -s $me $prefix

# cleanup
rm $prefix

# compress the result
rm -f $out.gz
$compress $out

