#!/bin/sh
# Called from uscan with parameters:
# --upstream-version <release> <path-to-upstream.orig.tar.gz>
#
# Require svn
set -e

# We build the orig tarball from upstream SVN repository because their
# dist tarball includes many generated files:
# - doxygen docs
# - flex + bison C modules
# - gettext object files
# and misses some files needed to rebuild everything from source.

UPSTREAM_VERSION="$2"
UPSTREAM_VERSION_SVN="$UPSTREAM_VERSION+svn"
UPSTREAM_SVN_TAG=V"$(echo "$UPSTREAM_VERSION" | sed 's/\./_/g')"
UPSTREAM_SVN_URI="http://code-saturne.org/svn/saturne/tags/$UPSTREAM_SVN_TAG"
PACKAGE=$(basename "$3" "_$UPSTREAM_VERSION.orig.tar.gz")

SOURCE_DIR="$PACKAGE-$UPSTREAM_VERSION"
DEBIAN_SOURCE_DIR="$PACKAGE-$UPSTREAM_VERSION_SVN"
TAR="../${PACKAGE}_$UPSTREAM_VERSION_SVN.orig.tar.gz"
CPPLUS_RM_NAME=cpplus_RM

# SVN export
echo "-- Exporting from SVN tag $UPSTREAM_SVN_TAG:"
/usr/bin/svn export "$UPSTREAM_SVN_URI" "$SOURCE_DIR"

# ChangeLog (snippet from Makefile.am)
CLDATE=$(LANG=C svn info "$UPSTREAM_SVN_URI" | awk '/^Last Changed Date:/{print $4}')
today=`date -d "$CLDATE" +%F`
start=`date -d "$CLDATE" +%Y`-01-01
/usr/bin/svn2cl --reparagraph --include-rev --include-actions \
  --authors=${SOURCE_DIR}/extras/changelog/authors.xml \
  --output=${SOURCE_DIR}/ChangeLog \
  "$UPSTREAM_SVN_URI" --revision {"${today} 23:59"}:{"${start} 00:00"}

# rename upstream source dir
# excluding files matched by debian/orig-tar.exclude
tar c -X debian/orig-tar.exclude "$SOURCE_DIR" | tar x --transform "s,^$SOURCE_DIR,$DEBIAN_SOURCE_DIR,"

# remove empty directories
find "$DEBIAN_SOURCE_DIR" -type d -empty -delete

# repack into orig.tar.gz
tar -c -z -f "$TAR" "$DEBIAN_SOURCE_DIR/"
rm -rf "$SOURCE_DIR" "$DEBIAN_SOURCE_DIR"

echo "$PACKAGE: downloaded upstream release $2 from SVN and renamed archive to $(basename "$TAR")"
