#!/bin/bash
#
# $Id$
#
# PBA gitrelease prepare tool
#
# (C) ITEG IT-Engineers GmbH 2010-2021
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# pba-gitrelease-prepare releaseVersion nextVersion [changelog message]
#
# Stores the specified versions and changelog message in .pba-gitrelease,
# and calls pba-raiseversion -b relVersion changelogMessage
# 

# params

RELVER="$1"
shift

if [ -z "${RELVER}" ] ; then
  echo "FATAL: No release version specified as \$1"
  echo ""
  echo "The versions in eventual debian*/changelog spec-*/*.spec and are:"
  if [ -n "$(ls -1d debian*/changelog 2>/dev/null)" ] ; then
    head -1 debian*/changelog 2>/dev/null
  fi
  if [ -n "$(ls -1d spec*/*.spec 2>/dev/null)" ] ; then
    egrep "^(Version|Release)" spec-*/*.spec 2>/dev/null
  fi
  exit 1
fi

NEXTVER="$1"
shift

if [ -z "${NEXTVER}" ] ; then
  echo "FATAL: No next development version specified as \$2"
  exit 2
fi

PROJDIR=$(pwd)

SRCNAME=""
DEBCL=$(ls -1d debian*/changelog 2>/dev/null |head -1)
if [ -n "${DEBCL}" ] ; then
  SRCNAME=$(head -1 ${DEBCL} |cut -f1 -d' ')
fi
if [ -z "${SRCNAME}" ] ; then
  SPEC=$(ls -1d spec*/*.spec 2>/dev/null |head -1)
  if [ -n "${SPEC}" ] ; then
    SRCNAME=$(cat ${SPEC} |egrep "^Name" |head -1 |cut -f2 -d' ')
  fi
fi
if [ -z "${SRCNAME}" ] ; then
  SRCNAME=$(basename $(pwd))
fi

CLMESSAGE="$*"
if [ -z "${CLMESSAGE}" ] ; then
  CLMESSAGE="Releasing ${SRCNAME} ${RELVER} to repos"
fi


if [ -e ".pba-gitrelease" ] ; then
  echo "FATAL: There already is a file .pba-gitrelease"
  echo "If you are sure this is obsolete remove it"
  exit 1
fi

echo 'SRCNAME="'"${SRCNAME}"'"' >.pba-gitrelease
echo 'RELVER="'"${RELVER}"'"' >>.pba-gitrelease
echo 'NEXTVER="'"${NEXTVER}"'"' >>.pba-gitrelease
echo 'CLMESSAGE="'"${CLMESSAGE}"'"' >>.pba-gitrelease

echo "INFO: Preparing pba-gitrelease with these params:"
cat .pba-gitrelease
echo ""

echo "INFO: Calling pba-raiseversion -b ${RELVER} ${CLMESSAGE}"
pba-raiseversion -b ${RELVER} ${CLMESSAGE} || exit 11
echo ""

if [ -n "$(ls -1d debian*/changelog 2>/dev/null)" ] ; then
  echo "INFO: Calling git add debian*/changelog"
  git add debian*/changelog
fi
if [ -n "$(ls -1d spec*/*.spec 2>/dev/null)" ] ; then
  echo "INFO: Calling git add spec*/*.spec"
  git add spec*/*.spec
fi

echo "INFO: Calling git status"
git status

exit 0
