#!/bin/sh

set -e

PKG_NAME=`dpkg-parsechangelog | awk '/^Source:/ {print $2}'`
PKG_VERSION=`dpkg-parsechangelog | awk '/^Version:/ {print $2}'`
UP_VERSION=`dpkg-parsechangelog | \
    awk '/^Version:/ {gsub(/\+dfsg.*/, "", $2); print $2}'`
DFSG=`dpkg-parsechangelog | \
    awk '/^Version:/ {gsub(/.*\+dfsg/, "+dfsg", $2); gsub(/-.*/, "", $2); print $2}'`
ORIG_DIR="$PKG_NAME-$UP_VERSION$DFSG.orig"
ORIG_NAME="${PKG_NAME}_$UP_VERSION$DFSG.orig"
UP_DIR="`pwd`/../tarballs"
UP_DISTDIR="$UP_DIR/$PKG_NAME"
UP_SITE="http://ftp.gnu.org/gnu/mdk/v$UP_VERSION/"
UP_DISTVER="$UP_VERSION"
UP_DISTNAME="$PKG_NAME-$UP_DISTVER"
UP_TARBALL="$UP_DISTNAME.tar.gz"
RM_FILES='doc'

# Fetch the upstream tarball if needed
echo "up $UP_TARBALL site $UP_SITE orig $ORIG_NAME"
mkdir -p "$UP_DIR"
if [ ! -f "$UP_DIR/$UP_TARBALL" ]; then
	echo "Fetching upstream tarball $UP_DIR/$UP_TARBALL"
	(cd "$UP_DIR" && wget -nv -c "$UP_SITE$UP_TARBALL")
else
	echo "Upstream tarball $UP_DIR/$UP_TARBALL exists";
fi

# Extract it
rm -rf "$UP_DIR/$UP_DISTNAME" "$UP_DIR/$ORIG_DIR"
(cd "$UP_DIR" && tar zxf "$UP_TARBALL")

# Do our magic
(cd "$UP_DIR/$UP_DISTNAME" && rm -rfv $RM_FILES)
mv "$UP_DIR/$UP_DISTNAME" "$UP_DIR/$ORIG_DIR"

# Create the repackaged tarball
(cd "$UP_DIR" && tar -cf - "$ORIG_DIR" | bzip2 -c9 > "$ORIG_NAME.tar.bz2")
echo "The repackaged source is at $UP_DIR/$ORIG_NAME.tar.bz2"
