#!/bin/sh

set -e

PACKAGE="hplip"
[ -n "${REPACK_SUFFIX}" ] || REPACK_SUFFIX="dfsg0"

VERSION=${VERSION:-$2}
VERSION_REPACKED="${VERSION}+${REPACK_SUFFIX}"

Debian_TARBALL_IN="../${PACKAGE}_${VERSION}.orig.tar.xz"
Debian_TARBALL_OUT="../${PACKAGE}_${VERSION_REPACKED}.orig.tar.xz"

TMPDIR=`mktemp -d /tmp/kk.XXXXXX`
target_DIR="${TMPDIR}/${PACKAGE}-${VERSION_REPACKED}"

echo "Repacking ${Debian_TARBALL_IN} to ${Debian_TARBALL_OUT}" >&2
# Not using --strip-components=1, so renaming code below fails if
# upstream structure changes, making us aware of it.
tar -xJf "${Debian_TARBALL_IN}" -C "${TMPDIR}"

# Rename "${PACKAGE}-${VERSION}" upstream parent dir to "${PACKAGE}-${VERSION_REPACKED}"
mv "${TMPDIR}/${PACKAGE}-${VERSION}" "${target_DIR}"

# --- > Debian changes start
( cd "${target_DIR}" &&
  find . -regextype posix-extended -iregex '.*\.(ldl|ppd|pdf|ps|pcl)\.gz' | xargs gunzip -f
  # Files in comment below are removed by uscan after Files-Excluded:
  # in debian/copyright. Leave this as a reminder.
  # rm -f locatedriver prnt/plugins/*.so prnt/hpcups/*.so
)
# --- > Debian changes end
fakeroot tar --sort=name  --xform 's:^\./::' -cf - -C "${TMPDIR}" . | xz -6e > "${Debian_TARBALL_OUT}"

# Some actions that may go after this download

cat <<EOF >&2
  ### Actions that may go after successful download and repack: ###
    $ git checkout debian/main
    $ gbp import-orig --pristine-tar --no-merge --upstream-branch=upstream/latest ${HPLIP_GBP_IO_OPTS} ${Debian_TARBALL_OUT}
    $ git debrebase new-upstream ${VERSION_REPACKED}
EOF
