#!/bin/sh
#
# do-debian-release
#
# Simple helper to automate more of the release process for LAVA
# Debian packages:
#
# * Update the debian/changelog for the new release
#
# Takes some of the same options as dch would, but this is much more
# limited and only intended to deal with release changes.
#
# Copyright (C) 2019 Linaro Limited
#
# Author: Steve McIntyre <steve.mcintyre@linaro.org>

tmpch=""

usage() {
    echo "Usage: $0 <-v VERSION> [-t <OLD TAG>] [-m <MESSAGE>]" 1>&2
    echo 1>&2
    echo "The new version VERSION must be supplied." 1>&2
    echo "If no OLD TAG is supplied, we will use the most recent tag as" 1>&2
    echo "the base for changes." 1>&2
    echo "If no MESSAGE is supplied, the default of " 1>&2
    echo "\"LAVA Software VERSION release\" will be used." 1>&2
    exit 1
}

output() {
    echo "$@" >> $tmpch
    echo "$@"
}

VERSION=""
OLDTAG=""
MESSAGE=""
OUT=""

set -e

while getopts "v:t:m:" o; do
    case "${o}" in
        v)
            VERSION=${OPTARG}
	    OUT="$OUT -v $VERSION"
            ;;
        t)
            OLDTAG=${OPTARG}
            ;;
        m)
            MESSAGE=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ "$VERSION"x = ""x ]; then
    echo "No VERSION specified, abort."
    exit 1
fi

if [ "$MESSAGE"x = ""x ]; then
    MESSAGE="LAVA Software $VERSION release"
fi

if [ "$OLDTAG"x = ""x ]; then
    # Work out the most recent tag
    OLDTAG=$(git describe --abbrev=0)
fi

echo "Updating debian/changelog"

if [ ! -r debian/changelog ]; then
    echo "Can't read debian/changelog, abort"
    exit 1
fi

SRCPKG=$(dpkg-parsechangelog -S Source)
tmpch=$(mktemp)
output "$SRCPKG (${VERSION}-1) unstable; urgency=medium"
output ""
output "  * $MESSAGE"
git log --no-merges --oneline $OLDTAG..HEAD | \
    awk '{printf("ZZZZ%s\n", $0)}' | \
    fmt -s -w 71 -u | \
    awk '/^ZZZZ/ { gsub("^ZZZZ","    "); print $0; next};
                 { printf("              %s\n",$0);}' >> $tmpch
NUM_LINES=$(git log --no-merges --oneline $OLDTAG..HEAD | wc -l)
echo "... $NUM_LINES log lines added"
DATE=$(LC_ALL=C date -u +"%a, %d %b %Y %H:%M:%S +0000")
output ""
output " -- $DEBFULLNAME <$DEBEMAIL>  $DATE"
output ""
cat debian/changelog >> $tmpch
cat $tmpch > debian/changelog
rm -f $tmpch
