#!/bin/bash
# $Id: vc 38 2009-03-15 16:33:53Z lrupp $
#
FILE="$1"
COMMENT_FILE=$(basename $FILE .spec).changes
tmpfile=$(mktemp changelog-XXXXXX)
TIMESTAMP=$(LC_ALL=POSIX TZ=Europe/Berlin date)
DOMAIN=$(hostname -d)
USERNAME=$USER
EMAIL="$USERNAME@$DOMAIN"
SEPARATOR="-------------------------------------------------------------------"
config=~/.vc

function cleanup_and_exit() {
    test -f $tmpfile && rm $tmpfile
    exit $1
}

# overwrite values with own config file
if [ -r "$config" ]; then
. "$config"
fi
# some help output
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echo "Usage: $(basename $0) specfile.spec"
	echo 
	echo "       This script creates a valid openSUSE .changes file"
	echo "       for your specfile."
	echo "       Please use only this new .changes file to add changes"
	echo "       - the lines after %changelog in your original specfile"
	echo "       will be overwritten."
	echo 
	echo "       You can create your own config file $config"
	echo "       to overwrite some default values like EMAIL"
	echo "       $config should look like:"
	echo "       EMAIL=user@name.org"
	echo "       TIMESTAMP=\$(LC_ALL=POSIX TZ=Europe/Berlin date)"
	echo "       EDITOR=/usr/bin/vim"
	cleanup_and_exit 0
fi

{
    echo "$SEPARATOR"
    echo "$TIMESTAMP - $EMAIL"
    echo
    echo "- "
    echo
    if [ -n "$COMMENT_FILE" ]; then
      if [ -f "$COMMENT_FILE" ]; then
        cat $COMMENT_FILE
      fi
    fi
} >> $tmpfile || cleanup_and_exit 1

if [ -z "$COMMENT_FILE" ]; then
    lines=1
    CHKSUM_BEFORE=$(md5sum $tmpfile | awk '{print $1}')
else
    lines=$(wc -l $COMMENT_FILE | awk '{print $1}')
    CHKSUM_BEFORE=has_changed
fi
if [ -z "$EDITOR" ]; then
  if [ -x /usr/bin/vi ]; then
    export EDITOR="/usr/bin/vi"
  else
    echo "No suitable editor found."
    echo "Please add something like EDITOR=<path_to_your_editor> in $config"
    cleanup_and_exit 1
  fi
fi
$EDITOR +$((4+lines)) $tmpfile

if [ "$CHKSUM_BEFORE" = "$(md5sum $tmpfile | awk '{print $1}')" ]; then
    cleanup_and_exit 1
fi
cat $tmpfile > $COMMENT_FILE
cleanup_and_exit 0
