#!/bin/sh -e
#
# Build a remotefilelog debian package from the current repo

if [ ! -d .hg ]; then
    echo 'You are not at the repository root!' 1>&2
    exit 1
fi

cp -r contrib/debian debian

version=$(hg log -r . -T'{latesttag}+{latesttagdistance}-{node|short}')

# Remove "hg_" from start of $version so it starts with a digit, which makes it
# a valid version string.
version=${version/#hg_/}

control=debian/control
changelog=debian/changelog
# This looks like sed -i, but sed -i behaves just differently enough
# between BSD and GNU sed that I gave up and did the dumb thing.
sed "s/__VERSION__/$version/" < $changelog > $changelog.tmp
date=$(date --rfc-2822)
sed "s/__DATE__/$date/" < $changelog.tmp > $changelog
rm $changelog.tmp

if [ ! -z "${DEBPREPONLY}" ] ; then
  exit 0
fi
trap "rm -r '$PWD/debian'" EXIT

debuild -us -uc -b || exit 1
OUTPUTDIR=${OUTPUTDIR:=packages/debian-unknown}
mkdir -p $OUTPUTDIR
find ../remotefilelog*.deb ../remotefilelog_*.build \
      ../remotefilelog_*.changes -type f -newer $control -print0 | \
  xargs -Inarf -0 mv narf "$OUTPUTDIR"
echo "Built packages for $version:"
find "$OUTPUTDIR" -type f -newer $control -name '*.deb'
