#!/bin/sh

NEWS=NEWS
CHANGELOG=debian/upstream-changelog

if [ ! -e "${NEWS}" ]; then
  echo "unable to find (input) ${NEWS}." 1>&2
  exit 1
fi
if [ ! -e "${CHANGELOG}" ]; then
  echo "unable to find (output) ${CHANGELOG}." 1>&2
  exit 1
fi

if command -v iconv >/dev/null; then
 iso2utf() {
  iconv -f "ISO-8859-15" -t "UTF-8"
 }
else
 iso2utf() {
  cat
 }
fi

make_news() {
  # new changelog entry, without trailing-newlines and with missing LF at EOL
  sed -e 's| *$||' -e '$a\' "${NEWS}" | iso2utf
  # separator
  echo
  echo "==============================================================================="
  echo
  # old changelog
  cat "${CHANGELOG}"
}

TMPFILE=$(mktemp)
make_news > "${TMPFILE}"
cat "${TMPFILE}" > "${CHANGELOG}"
rm -f "${TMPFILE}"


echo "updated ${CHANGELOG} from ${NEWS}!" 1>&2
