#!/bin/sh
# 2010, 2012 (c) Etersoft http://etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>

# Script for update changelog or increment release

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/functions/common

load_mod spec rpm git etersoft

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echog "rpmlog - update version/release and changelog"
	echog "Usage: rpmlog [-r|-s|-v] [-l|-t] [SPEC] [fromTAG] [toTAG]"
	echo
	echog "Options:"
	echog "   -v  increment version"
	echog "   -r  increment release"
	echog "   -s  increment subrelease"
	echog "   -l  add changelog from git log (since last release tag or TAG)"
	echog "   -t  test run (without change files and repo)"
	exit 0
fi

is_gear || fatal "rpmlog usable only with gear repo"

INCREMENTMODE=""
if [ "$1" = "-r" ] || [ "$1" = "-s" ] || [ "$1" = "-v" ]; then
	INCREMENTMODE=$1
	shift
fi

CHANGELOGUPDATE=
if [ "$1" = "-l" ] ; then
	CHANGELOGUPDATE=$1
	shift
fi

TESTRUN=
if [ "$1" = "-t" ] ; then
	TESTRUN=$1
	shift
fi

if [ -n "${1/*.spec/}" ] || [ -z "$1" ] ; then
	SPECNAME=$(get_gear_spec)
	echo "Using autodetected spec $SPECNAME..."
else
	SPECNAME=$1
	shift
fi

FROMTAG=
if [ -n "$1" ] ; then
	FROMTAG="$1"
	shift
fi

TOTAG=HEAD
if [ -n "$1" ] ; then
	TOTAG="$1"
	shift
fi

if [ ! -r "$SPECNAME" ] ; then
	fatal "Spec $SPECNAME does not found"
fi

[ -n "$CHANGELOGUPDATE$TESTRUN" ] || fatal "Run with -t param for test or with -h for help"

if [ -z "$FROMTAG" ] ; then
	build_rpms_name $SPECNAME
	[ -n "$VERSION" ] || fatal "Can't get package version"
	[ -n "$RELEASE" ] || fatal "Can't get package release"
	FROMTAG="$VERSION-$RELEASE"
	# FIXME: if don't exists, use last tag?
fi

# TODO: найти параметр для упрощения истории. пока - sort?
# Делает первую букву маленькой, убирает точку в конце строки
CHANGELOG="`git log $FROMTAG..$TOTAG --simplify-merges --dense --pretty="- %s" | sed -e "s|\.\$||g" | sed -e "s|- \([A-Z]\)|- \l\1|g" | sed -e "s|%||g"`"
[ -n "$CHANGELOG" ] || fatal "git log was failed"

if [ -n "$TESTRUN" ] ; then
	INCREMENTMODE=""
fi

# increment release
case "$INCREMENTMODE" in
        "-r")
                inc_release $SPECNAME
                ;;
        "-s")
                inc_subrelease $SPECNAME
                ;;
        "-v")
                set_release $SPECNAME
                inc_version $SPECNAME
                ;;
        *)
                fatal "unknown increment mode $INCREMENTMODE"
esac

NEWREV=$(get_version $SPECNAME)-$(get_release $SPECNAME)
echo "Add changelog to $NEWREV:"
echo "$CHANGELOG"

if [ -n "$TESTRUN" ] ; then
	exit
fi

add_changelog_helper "$CHANGELOG" $SPECNAME || fatal "add_changelog failed, do not commit anything"

# TODO: use gear-commit ?
git_commit_ignore_nothing $SPECNAME -m "new build $NEWREV (with rpmlog script)"
