#!/bin/sh

#  Copyright 2010 Intel Corp.
# 
#  Authors: Yi Yang <yi.y.yang@intel.com>
# 
#  This program is free software; you can redistribute it and/or modify it
#  under the terms and conditions of the GNU Lesser General Public License,
#  version 2.1, as published by the Free Software Foundation.
# 
#  This program is distributed in the hope it will be useful, but WITHOUT ANY
#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
#  more details.
# 
#  You should have received a copy of the GNU Lesser General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
#

##########################################################
#                                                        #
# Usage: vc [-m changelogs] [-s specfile] [-h]           #
#                                                        #
# -m option can add change log by command line parameter,#
# if you have multiple change logs, you can use "\n" as  #
# seperator, for example:                                #
#                                                        #
#     vc -m "Rebase source package\nFix a fatal error"   #
#                                                        #
# added chanage log looks like:                          #
#                                                        #
# * Thu Aug 07 2008 Yi Yang <yi.y.yang@intel.com> 1.3.12 #
# - Rebase source package                                #
# - Fix a fatal error                                    #
#                                                        #
# -s option is used to specify .spec file name           #
# -m and -s are optional, you can run vc without any arg #
# , in that case, vc will search .spec file from current #
# directory, you must ensure current work directory is   #
# root patch of package source code including source tar #
# package, patches and .spec file.                       #
#                                                        #
# If you run vc without any arg, vc will ask you input   #
# change logs in vi editor, one line is for a change, you#
# should input multiple lines if you do several changes. #
#                                                        #
# You must creat .vcrc under your home directory before  #
# running vc. It's format is:                            #
#                                                        #
#      username="Your Name"                              #
#      email="Your Email Address"                        #
#                                                        #
# Notes: there isn't any whitespace before or after every#
# line. vc must be run under source tree of a package,   #  
# all stuff including source tar package, patches and    #
# .spec file should under the same directory, the commnad#
# "osc importsrcpkg <srcpkgname>" will do that way.      #
#                                                        #
# For example:                                           #
#     osc importsrcpkg gzip                              #
#     cd gzip                                            #
#     vc                                                 #
#                                                        #
##########################################################

changelogs=""
specfile=""
while getopts "m:s:h" opt
do	case "$opt" in
	m)	changelogs="$OPTARG";;
	s)	specfile="$OPTARG";;
	h)	echo -e "Usage: vc [-m changelogs] [-s specfile] [-h]\n\t[-m changelogs]\tAppend change log by command line parameter\n\t[-s specfile]\tSpecify .spec file\n\t[-h]\t\tPrint this help";exit 1;;
	[?])
		;;
	esac
done
shift $((OPTIND-1))

if [ -f ~/.vcrc ] ; then
	. ~/.vcrc
else
    if [ -z "$mailaddr" -o -z "$username" ]; then
        echo "FIXME: missing .vcrc file, you must create a .vcrc in your home directory with followling two lines before using me"
        echo "username=\"YOUR NAME\""
        echo "email=\"your.email@company.com\""
        exit 1
    else
        email=$mailaddr
    fi
fi

if [ ! -z "$specfile" ] ; then
	if [ ! -f "$specfile" ] ; then
		echo "Error: $specfile doesn't exist."
		exit 1
	fi
	packagename="${specfile%\.spec}"
	if [ "${specfile:${#packagename}:5}" == ".spec" ] ; then
		specnum=1
	else
		specnum=90
	fi
else
	specnum=`ls *.spec 2>/dev/null | wc -l`
fi

if [ $specnum -eq 1 ] ; then
	if [ -z "$specfile" ] ; then
		specfile=`ls *.spec 2>/dev/null`
	fi
elif [ $specnum -ge 2 ] ; then
	echo "Sorry, i found $specnum .spec files:"
	ls *.spec 2>/dev/null
	echo -n "Please input your spec file name ? "
	while read specfile
	do
		if [ -f "$specfile" ] ; then
			break
		else
			echo -n "Incorrect, please re-input your spec file name ? "
		fi
	done
else
	echo "Sorry, please run me under your rpm source tree or specify .spec file explicitly."
	echo ""
	echo -e "Usage: vc [-m changelogs] [-s specfile] [-h]\n\t[-m changelogs]\tAppend change log by command line parameter\n\t[-s specfile]\tSpecify .spec file\n\t[-h]\t\tPrint this help"
	exit 1
fi

rpm -q --specfile $specfile > /dev/null 2>&1
if [ $? -ne 0 ] ; then
	echo "Error: $specfile has errors."
	rpm -q --specfile $specfile
	exit 1
fi

sed 's/^%prep/%prep\necho %{version}\nexit\n/' $specfile > .tmpvc.spec
version=`rpmbuild -bp --nodeps --force .tmpvc.spec --define '_topdir .' --define '_builddir .' --define '_sourcedir .' --define '_rpmdir .' --define '_specdir .' --define '_srcrpmdir .' 2>&1 | grep "echo " | cut -d " " -f 3`
rm -f .tmpvc.spec
if [ -z "$version" ] ; then
	echo "Error: $specfile is an invalid .spec file or current directory isn't source root path of pckage ${specfile%\.spec}"
	exit 1
fi

datestring=`date +"%a %b %d %Y"`
changeheader="* $datestring $username <$email> - $version"

changesfile="${specfile%\.spec}.changes"
if [ ! -f "$changesfile" ] ; then
	echo "WARNING: $changesfile doesn't exist, i'll create a empty $changesfile"
	touch $changesfile
fi

if [ ! -z "$changelogs" ] ; then
	{
		echo "$changeheader"
		echo -e "$changelogs" | sed 's/^\([^-]\)/- \1/g'
		echo ""
		cat $changesfile
	} >> .tmpchanges.$$
	mv -f .tmpchanges.$$ $changesfile
	exit
fi

# Assure the file is removed at program termination
# or after we received a signal:
tmpfile="${TMPDIR:=/tmp}/.vc.changes.$$"
trap 'rm -f "$tmpfile" >/dev/null 2>&1;rm -f ".tmpchanges.$$"' 0
trap "exit 2" 1 2 3 13 15

EXINIT="set ignorecase nowrapscan readonly"
export EXINIT


{
	echo "$changeheader"
	echo ""
	echo ""
	cat $changesfile
} >> .tmpchanges.$$

cp -f .tmpchanges.$$ $tmpfile
${EDITOR:-vi} -c ":2" "$tmpfile"
diff -purN .tmpchanges.$$ $tmpfile > /dev/null
if [ $? -eq 0 ] ; then
	echo "Your change log isn't added into .changes, please run me again and save your change log with :wq"
	exit 1
else
	cp -f $tmpfile $changesfile
	rm -f .tmpchanges.$$ $tmpfile
fi
