#!/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: mvchangelog <specfile>                          #
#                                                        #
#        <specfile> is a .spec file from which you'll    #
#        remove change log, both relative path and full  #
#        path are ok.                                    #
#                                                        #
# mvchangelog will move change log from .spec file to    #
# .changes file if .changes doesn't exist, otherwise, it #
# just removes change log from .spec file and doesn't    #
# touch .changes.                                        #
#                                                        #
##########################################################

if [ $# -ne 1 ] ; then
	echo "Usage: $0 <spec file name>"
	exit
fi

specfile=${1}
package=${specfile%\.spec}
suffixstart=${#package}
if [ "${specfile:$suffixstart:5}" != ".spec" ] ; then
	echo "$specfile isn't a spec file"
	exit 1
fi

changelogstart=`sed -n '/^%changelog/=' $specfile`
if [ ! -z $changelogstart ] ; then
	totallines=`cat $specfile | wc -l`
	changelogstart=$((changelogstart+1))
	if [ ! -e $package.changes ] ; then
		sed -n "${changelogstart},${totallines}"p $specfile > $package.changes
	else
		echo "$package.changes has existed"
	fi
	changelogstart=$((changelogstart-2))
	sed -n "1,${changelogstart}"p $specfile > $$.spec
	mv -f $$.spec $specfile
	echo "Changelog in $specfile has been removed successfully, it was put into $package.changes"
else
	echo "$specfile hadn't any change log"
	if [ ! -e $package.changes ] ; then
		touch $package.changes
	fi
fi
