#!/bin/sh
# 2010 (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 changelog"
	echog "Usage: rpmlog [-r|-s|-v] [-l|-t] [SPEC] [TAG]"
	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

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 releasr"
	FROMTAG="$VERSION-$RELEASE"
fi

# TODO: найти параметр для упрощения истории. пока - sort?
# Делает первую букву маленькой, убирает точку в конце строки
CHANGELOG="`git log $FROMTAG..HEAD --simplify-merges --dense --pretty="- %s" | sort -u | 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
if [ "$INCREMENTMODE" = "-r" ] ; then
	inc_release $SPECNAME
elif [ "$INCREMENTMODE" = "-s" ] ; then
	inc_subrelease $SPECNAME
elif [ "$INCREMENTMODE" = "-v" ] ; then
	set_release $SPECNAME
	inc_version $SPECNAME
fi

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

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