#!/bin/sh

pkg=mrpeach
version=$1

# ${version} could be:
# - empty (""): get current SVN
# - a revision ("17615"): get named revision
# - a full version ("0.1~svn17615"): extract revision and get that
if [ "x${version}" != "x" ]; then
    revision=${version##*svn}
    revision=${revision%%-*}
    version=${version%svn*}
    version=${version%~}
fi
if [ "x${revision}" = "x" ]; then
    revision=$(curl "https://sourceforge.net/p/pure-data/svn/HEAD/log/?path=/trunk/externals/${pkg}" 2>/dev/null\
                     | grep "/tree/trunk/externals/${pkg}" \
                     | sed -e 's|.*/svn/\([0-9]*\)/tree/trunk/externals/.*|\1|' \
                     | sort -n \
                     | tail -1)
fi

echo "revision: ${revision}"

tempdir=$(mktemp -d)
echo "tempdir ${tempdir}"
pkgdir="${tempdir}/${pkg}-${revision}"

## clone revision
svn export "https://svn.code.sf.net/p/pure-data/svn/trunk/externals/${pkg}@${revision}" "${tempdir}/${pkg}"

if [ "x${version}" = "x" ]; then
    version=$(sed -n 's|^\#X text [0-9][0-9]* [0-9][0-9]* VERSION \(.*\);|\1|p' ${tempdir}/${pkg}/${pkg}-meta.pd)
fi

echo "version: ${version}"
if [  -d "${tempdir}/${pkg}" ]; then
    outfile="../${pkg}-${version}~svn${revision}.tar.gz"
    tar czf "${outfile}" -C "${tempdir}" "${pkg}"
fi

rm -rf "${tempdir}"

if [ "x${outfile}" != "x" ]; then
 echo "To import the new upstream version run something like: gbp import-orig ${outfile}"
 echo "To update the upstream changelog, please run: debian/mk-changelog.sh ${revision}"
fi
