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

UPSTREAM_VERSION="$2"
MANGLED_UPSTREAM_VERSION="$(echo "$UPSTREAM_VERSION" | sed 's/-\(alpha\|pre\)/~\1/')+docs"
UPSTREAM_DOC_VERSION="${UPSTREAM_VERSION%-*}"
if [ "$UPSTREAM_DOC_VERSION" = 1.10.0 ]; then
  UPSTREAM_DOC_VERSION=1.10
fi
PACKAGE=$(basename "$3" "_$UPSTREAM_VERSION.orig.tar.gz")

SOURCE_DIR="$PACKAGE-$UPSTREAM_VERSION"
DEBIAN_SOURCE_DIR="$PACKAGE-$MANGLED_UPSTREAM_VERSION"
TAR="../${PACKAGE}_$MANGLED_UPSTREAM_VERSION.orig.tar.gz"
HTML_DIR="$DEBIAN_SOURCE_DIR/html"

# extract the upstream archive
tar xf $3

# get docs
/usr/bin/svn export https://svn.hdfgroup.uiuc.edu/hdf5doc/branches/hdf5_"$(echo "$UPSTREAM_DOC_VERSION" | sed 's/\./_/g')"/html "$SOURCE_DIR/html"

# 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 "$HTML_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" "$3"

echo "$PACKAGE: downloaded docs and renamed archive to $(basename "$TAR")"
