#!/bin/sh

# Recently upstream shipped:
# - source folders of many former versions in the source tarball;
# - some files at the root, other ones in a jmol-... subdir.
# Here we remove all but one such folders and put the contents of the subdir
# at the root.

while [ "$1" ]; do
    case $1 in
    --upstream-version|-v)
        shift; NEW_VERSION="$1"
        ;;
    --force-bad-version|-b|--find|-f)
        :
        ;;
    esac
    shift
done
# ignore <path> and rely on ../ being the path to the orig.tar.xz
# using source package name $SPKG from debian/changelog
SPKG=$(dpkg-parsechangelog -SSource)
SRC_DIR=${PWD}
tgz="$(readlink -f ../${SPKG}_${NEW_VERSION}.orig.tar.xz)"
tmpDir=$(mktemp -d)

cd "${tmpDir}"
tar --xz -xf "$tgz"
mv -f "$tgz" "$tgz.orig"
# Removing extra folders with old versions, putting everything else at the root.
ls | grep "jmol-" | sort | head --lines=-1 | xargs rm -rf
remainingFolder=$(ls | grep "jmol-")
mv ${remainingFolder}/* .
rmdir "$remainingFolder"

tar --xz -cf "$tgz" *
cd ${SRC_DIR}

#We could call original uupdate now, not necessary when using git-buildpackage
#uupdate --upstream-version ${NEW_VERSION} "$tgz"
