#!/bin/sh

set -e

SVN_URL="https://josm.openstreetmap.de/svn/trunk/native/linux"

CURDIR=$(readlink -f "$(dirname "$0")")
TMPDIR=$(mktemp -d)

trap 'rm -rf "${TMPDIR}"; exit $?' INT TERM EXIT

cd "${TMPDIR}" || exit 1

LOCAL_REVISION=$(dpkg-parsechangelog -S Version -l "${CURDIR}/debian/changelog" | awk -F'+svn' '{print $2}' | awk -F'~' '{print $1}')

REMOTE_REVISION=$(svn info "${SVN_URL}" --show-item last-changed-revision)

if [ -n "${LOCAL_REVISION}" ] && [ -n "${REMOTE_REVISION}" ] && [ "${REMOTE_REVISION}" -eq "${LOCAL_REVISION}" ]; then
    echo "No newer revision, already at r${REMOTE_REVISION}"
    exit 0
fi

if [ -z "${REMOTE_REVISION}" ]; then
    echo "Error: No remote revision retrieved from: ${SVN_URL}" >&2
    exit 1
fi

svn export -q "${SVN_URL}" linux -r "${REMOTE_REVISION}"

set +e
diff -ruNq "${CURDIR}/linux" linux
rc=$?
set -e

MESSAGE="Updated linux directory to r${REMOTE_REVISION}."

if [ $rc -eq 1 ]; then
    rsync -aq --delete linux/ "${CURDIR}/linux/"

    echo "${MESSAGE}"
fi

PKG_VERSION=$(dpkg-parsechangelog -S Version -l "${CURDIR}/debian/changelog" | awk -F'+svn' '{print $1}')

if [ -n "${PKG_VERSION}" ]; then
    CHANGELOG="${CURDIR}/debian/changelog" dch -v "${PKG_VERSION}+svn${REMOTE_REVISION}" -m "${MESSAGE}"
fi

cd "${CURDIR}" || exit 1

rm -rf "${TMPDIR}"
trap - INT TERM EXIT
exit 0
