#!/bin/bash
# debian/repack
# Re-build the pristine upstream source to serve as the Debian upstream source

set -o errexit
set -o errtrace
set -o nounset

upstream_version="$2";
downloaded_file="$3";
package_name=$(dpkg-parsechangelog | sed -n -e 's/^Source: //p');

working_dir="$(mktemp -d -t)"

function cleanup_exit() {
	exit_status=$?
	trap - ERR EXIT SIGTERM SIGHUP SIGINT SIGQUIT

	printf "Cleaning up the temporary directory...\n";
	rm -rf "${working_dir}"

	printf "All done.\n\n";

	exit $exit_status
}
trap "cleanup_exit" ERR EXIT SIGTERM SIGHUP SIGINT SIGQUIT

upstream_filename="${package_name}_${upstream_version}.orig.tar.gz";
upstream_file="$(dirname "${downloaded_file}")/${upstream_filename}";
upstream_dirname="${package_name}-${upstream_version}.orig";

# Unpack the source
printf "Unpacking pristine upstream source ${downloaded_file} : \n";

tar -xzf "${downloaded_file}" --directory "${working_dir}"

upstream_source_dirname=$(ls -1 "${working_dir}")
upstream_source_dir="${working_dir}/${upstream_source_dirname}";

target_filename="${package_name}_${upstream_version}+dfsg.orig.tar.gz";
target_working_file="${working_dir}/${target_filename}";

target_file="$(dirname "${downloaded_file}")/${target_filename}"

repack_dir="${upstream_source_dir}.orig";

# Rename the upstream source directory
mv "${upstream_source_dir}" "${repack_dir}";

# List of the files to remove
files_to_remove=(
	res/DejaVuSans-Bold.ttf
	res/DejaVuSans.ttf
	)

# Remove the files:
for f in "${files_to_remove[@]}" ; do
	rm "${repack_dir}"/$f;
done

printf "Rebuilding DFSG-free upstream source tarball:\n";

# Re-zip
GZIP="--best" tar --directory "${working_dir}" -czf "${target_working_file}" "${upstream_dirname}"

rm -v ${downloaded_file};

# Set the correct name (including the +dfsg stanza
mv "${target_working_file}" "${target_file}";
