#!/bin/bash
#
# Set a `git describe` like version for the latest changelog entry
# Copyright (C) 2014-2015 Daniel Gollub
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

DSC_TAG_ID="XBS-Git-Id"
DSC_TAG_BRANCH="XS-Git-Repo"

source /etc/dch_git_describe.conf 2> /dev/null || true

[ ! -f debian/changelog ] && exit 1
[ ! -d .git ] && [ -z "$GBP_GIT_DIR" ] && [ -z "$GIT_DIR" ] && exit 1

#
# Write GIT commit information to debian/control
#
GIT_COMMIT_ID=$(git --git-dir $GBP_GIT_DIR log -1 --pretty=format:%H)
GIT_REMOTE_URL=$(git --git-dir $GBP_GIT_DIR config remote.origin.url)
GIT_REPO=$( echo $GIT_REMOTE_URL | sed -e 's/ssh:\/\///g' -e 's,^[^\/]*/,,' )
if [ -f debian/control ] ; then
    sed -i "0,/^\s*$/s//${DSC_TAG_ID}: ${GIT_COMMIT_ID}\n/" \
       debian/control
    sed -i "0,/^\s*$/s##${DSC_TAG_REPO}: ${GIT_REPO}\n#" \
       debian/control
fi

PACKAGE=$(dpkg-parsechangelog | grep -E '^Source:'  | awk '{ print $2 }')
VERSION=$(dpkg-parsechangelog | grep -E '^Version:' | awk '{ print $2 }')
DIST=$(dpkg-parsechangelog | grep -E '^Distribution:' | awk '{ print $NF }')

[ -z "$PACKAGE" ] && [ -z "$VERSION" ] && exit 1

GIT_CMD="git"
[ -n "$GBP_GIT_DIR" ] && GIT_CMD="$GIT_CMD --git-dir $GBP_GIT_DIR" 

$GIT_CMD log -1 &> /dev/null || exit 1

# Get the epoch from current changelog entry.
# git-buildpackage git tags doesn't hold the epoch.
EPOCH=""
if [ -n "$DCH_GIT_DESCRIBE_EPOCH" ]; then
	EPOCH="$DCH_GIT_DESCRIBE_EPOCH:"
elif echo $VERSION | grep -Eq '^[0-9]+:.*'; then
	EPOCH=$( echo $VERSION | sed 's/^\([0-9]*:\).*/\1/g' )
fi

$GIT_CMD describe --tags --match "debian/*"
GIT_DESCRIBE=$( $GIT_CMD describe --tags --match "debian/*" --long |
                sed 's,debian/,,' |
                sed "s/$PACKAGE\_\(.*\)/\1/g" |
                sed 's/\(.*\)-\(.*\)-\(g.*\)$/\1+\2+\3/g' |
                sed 's/^[0-9]*%//' |
                sed 's/_/~/g' )

TIMESTAMP=$($GIT_CMD log -1 --pretty=format:%ct)

if [ "${DIST}" = "UNRELEASED" ]; then
	GIT_ABBREV_HASH=$( $GIT_CMD log -1 --pretty=format:%h )
	NEW_VERSION="${VERSION}~0+${TIMESTAMP}+g${GIT_ABBREV_HASH}"
elif [ -n "${GIT_DESCRIBE}" ]; then
	NEW_VERSION="${EPOCH}${GIT_DESCRIBE}"
else
	NEW_VERSION="${VERSION}+${TIMESTAMP}"
fi

sed -i "s/${PACKAGE} (${VERSION})/${PACKAGE} (${NEW_VERSION})/" \
    debian/changelog

