#!/bin/sh

set -ex

# This is based on code from https://bugs.debian.org/748474

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
# This makes it more robust for newer uupdate in future
SPKG=$(dpkg-parsechangelog -SSource)
cd ..
# Now ${SPKG}_${NEW_VERSION}.orig.tar.xz is upstream tarball
new_package="${SPKG}-${NEW_VERSION}"
rm -f ${SPKG}_${NEW_VERSION}.orig.tar.*

echo "Cloning ${SPKG} version ${NEW_VERSION}"
git clone \
    --branch ${NEW_VERSION} \
    https://github.com/PacificBiosciences/FALCON-integrate.git $new_package

export PATH="$PATH:$PWD/$new_package/git-sym"

cd $new_package
git describe --tags
make init
cd FALCON-examples && make setup-synth0 && cd ..
find FALCON-examples/run/synth0 -type l \
    | xargs -I{} sh -c 'cp -rL {} {}.actual && rm -rf {} && mv {}.actual {}'
# Get rid of absolute symlinks
find FALCON-examples -type l \
    | xargs -I{} sh -c 'perl -e "\"$(readlink {})\" =~ /^\//" && rm {}'
rm -f FALCON-examples/scripts/git-sym
find -name ".git*" -exec rm -rf {} +
rm -rf git-sym
cd ..

tar --xz -cf ${SPKG}_${NEW_VERSION}.orig.tar.xz ${new_package}
rm -rf ${new_package}
