#!/bin/sh

OUTFILE=debian/upstream_changelog

error() {
  echo "$@" 1>&2
}

fatal() {
  error "$@"
  exit 1
}

UNTIL=$1
UNTIL=$((UNTIL+0))

if [ "x${UNTIL}" = "x0" ]; then
  UNTIL=$(dpkg-parsechangelog -SVersion | sed -e 's|.*svn\([0-9]*\)-.*|\1|')
fi

FROM=$(cat "${OUTFILE}"  | egrep "\* \[r[0-9]+\]" | sed -e 's|].*||' -e 's|.*\[r||' | sort -n  | tail -1)
if [ "x${FROM}" = "x" ]; then
  FROM=1
fi

error "fetching Changelog from ${FROM} until ${UNTIL}"
if [ ${UNTIL} -le ${FROM} ]; then
 error "Changelog is already up-to-date (${UNTIL} <= ${FROM})"
 exit 0
fi

which svn2cl || fatal "svn2cl is not installed"


clfile=$(mktemp)
svn2cl --output "${clfile}" --strip-prefix=":::" -i -r ${UNTIL}:${FROM} https://svn.code.sf.net/p/pure-data/svn/trunk/externals/mrpeach

if [ -s "${clfile}" ]; then
  cat  "${OUTFILE}" >> "${clfile}"
  cat "${clfile}" > "${OUTFILE}"
fi

rm "${clfile}"
