#!/bin/bash
#
# PBA maven fetchbundles tool
#
# (C) ITEG IT-Engineers GmbH 2010-2024
#
# 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-npm2pkg-raiseversion
#   Detects version from ../${NPM_DIR}/package.json (or ../package.json),
#   computes the according debian version and calls pba-raisversion -b accordingly.
#   If the package version contains 'SNAPSHOT' or 'beta' the debian version is 
#   postfixed with '~' + timestamp (in snapshot nameing fashion) + '0beta0'.
#   Otherwise it is postfixed with '-1' only.

PKGDIR=$(pwd)

export PKGJSON=""
if [ -n "${NPM_DIR}" ] ; then
  echo "INFO: \$NPM_DIR set, using ../${NPM_DIR}/package.json"
  PKGJSON="../${NPM_DIR}/package.json"
else
  echo "INFO: \$NPM_DIR not set, using ../package.json"
  PKGJSON="../package.json"
fi

if [ ! -f "${PKGJSON}" ] ; then
  echo "ERROR: No ${PKGJSON} in $(pwd)."
  exit 1
fi

# check for debian*/changelog
DEBCHANGELOG=$(ls -1dt debian*/changelog 2>/dev/null |head -1)
if [ -z "${DEBCHANGELOG}" ] ; then
  echo "ERROR: No debian*/changelog in $(pwd)"
  exit 11
fi
OLDDEBVER=$(head -1 ${DEBCHANGELOG} |sed -e 's/^.*(//' |sed -e 's/).*$//')

PKGVER=$(jq .version ${PKGJSON} |tr -d '"')

if [ -z "${PKGVER}" ] ; then
  echo "ERROR: Unable to parse package version from ${PKGJSON}"
  exit 12
fi

export NEWDEBVER=""
CLMSGFILE="clmessage_$$.txt"

if [ -n "$(echo $PKGVER |grep -E -- '-SNAPSHOT$')" ] ; then
  PKGBASEVER=$(echo $PKGVER |sed -e 's/-SNAPSHOT$//' -e 's/-?beta//')
  NEWDEBVER="${PKGBASEVER}~$(date -u +%Y%m%d.%H%M%S)-0beta0"
  echo "CI Beta Release" >${CLMSGFILE}
  echo "INFO: ${PKGJSON} has SNAPSHOT version ${PKGVER}, new debian beta version is ${NEWDEBVER}" 
else
  NEWDEBVER="${PKGVER}-1"
  echo "CI Production Release" >${CLMSGFILE}
  echo "INFO: ${PKGJSON} has prod version ${PKGVER}, new debian beta version is ${NEWDEBVER}" 
fi

if [ "${OLDDEBVER}" = "${NEWDEBVER}" ] ; then
  echo "INFO: Debian version already at ${NEWDEBVER}, not doing anything."
  exit 0
fi


echo "INFO: Raising debian version to ${NEWDEBVER}."
test -n "$CI" && pba-gitlab-ci-infos >>${CLMSGFILE}
pba-raiseversion -b ${NEWDEBVER} -f ${CLMSGFILE} || exit 31
rm -f ${CLMSGFILE}

exit 0

