#!/bin/bash
#
# PBA maven fetchbundle tool
#
# (C) ITEG IT-Engineers GmbH 2010-2022
#
# 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.
#

# See https://gitlab.intra.iteg.at/pba/pba/-/issues/2
#
# pba-mvn2pkg-fetchbundle
#   fetches the bundle (jar) of a single module project into downloads/
#
# Bundle version is computed from debian version in latest debian-*/changelog,
# a warning is print if an eventual ../pom.xml specifies an unexpected version.
#
# groupId and artifactId are taken from ../pom.xml using pba-mvn-pomparser -q -c,
# unless pba-mvn2pkg-settings.sh overrides them, see below. 
# 
# Maven repository URLs are taken from pba-mvn2pkg-settings.sh 
# which must set the following environment variable:
#   MVN_REPO="http://maven.foobar/"
#
# Optionally pba-mvn2pkg-settings.sh can set the repository access:
#   MVN_SNAPSHOTREPO="http://maven.foobar/"
#   MVN_REPOUSER="myuser"
#   MVN_REPOPASSWORD="mySeCrEt"
#
# To work without ../pom.xml pba-mvn2pkg-settings.sh can also set these:
#   MVN_GROUPID="org.clazzes.foobar"
#   MVN_ARTIFACTID="foo-bar"


PKGDIR=$(pwd)


if [ ! -x pba-mvn2pkg-settings.sh ] ; then
  echo "ERROR: No executable pba-mvn2pkg-settings.sh in $(pwd)"
  echo "Please create a pba-mvn2pkg-settings.sh that sets MVN_REPO at least."
  exit 1
fi

export MVN_REPO=""
export MVN_SNAPSHOTREPO=""
export MVN_REPOUSER=""
export MVN_REPOPASSWORD=""
export MVN_GROUPID=""
export MVN_ARTIFACTID=""

. ./pba-mvn2pkg-settings.sh

if [ -z "$MVN_REPO" ] ; then
  echo "ERROR: pba-mvn2pkg-settings.sh in $(pwd) did not set MVN_REPO"
  exit 2
fi

#if [ -z "$MVN_SNAPSHOTREPO" ] ; then
#  echo "ERROR: pba-mvn2pkg-settings.sh in $(pwd) did not set MVN_SNAPSHOTREPO"
#  exit 3
#fi

export WGETAUTH=""
if [ -n "$MVN_REPOUSER" ] ; then
  WGETAUTH="${WGETAUTH} --http-user=${MVN_REPOUSER}"
fi
if [ -n "$MVN_REPOPASSWORD" ] ; then
  WGETAUTH="${WGETAUTH} --http-password=${MVN_REPOPASSWORD}"
fi


if [ ! -e ../pom.xml ] ; then
  if [ -z "${MVN_GROUPID}" -a -z "${MVN_ARTIFACTID}" ] ; then
    echo "ERROR: No ../pom.xml in $(pwd) and not both MVN_GROUPID and MVN_ARTIFACTID set in pba-mvn2pkg-settings.sh."
    exit 4
  else
    echo "NOTICE: No ../pom.xml in $(pwd) but both MVN_GROUPID and MVN_ARTIFACTID set in pba-mvn2pkg-settings.sh, OK then."
  fi
fi



# find first debian*/changelog, parse version

if [ -z "$(ls -1d debian*/changelog 2>/dev/null)" ] ; then
  echo "ERROR: No debian*/changelog in $(pwd)"
  exit 11
fi

# For snapshot/beta-releases the Debian version is constructed from the following parts:
# maven-version (without -SNAPSHOT) + "~" + something containing 'beta', usually timestamp + "-0beta0"
# Modules' target directory is only used if Debian version contains '0beta0'
#
# For prod releases the debian version is constructed from the following parts:
# maven-version + "-[0-9]" + optional stuff
# always used dots ('.') for the maven version part!

DEBCHANGELOG=$(ls -1dt debian*/changelog 2>/dev/null |head -1)
DEBVER=$(head -1 ${DEBCHANGELOG} |sed -e 's/^.*(//' |sed -e 's/).*$//')
#echo "DEBUG: Parsed changelog ${DEBCHANGELOG} to deb version ${DEBVER}"

POMCOORDINATES=$(pba-mvn-pomparser -q -c ../pom.xml 2>/dev/null)
#echo "DEBUG: Parsed ../pom.xml to coordinates ${POMCOORDINATES}"

export POMGROUPID="${MVN_GROUPID}"
if [ -z "${POMGROUPID}" ] ; then
  echo "INFO: Trying to use groupId from ../pom.xml"
  POMGROUPID=$(echo "${POMCOORDINATES}" |cut -f1 -d',')
  #echo "DEBUG: Parsed ../pom.xml to groupId ${POMGROUPID}"
else
  echo "INFO: Using groupId from \$MVN_GROUPID"
fi
if [ -z "${POMGROUPID}" ] ; then
  echo "ERROR: Unable to compute groupId in $(pwd)"
  exit 12
fi
#echo "DEBUG: Parsed ../pom.xml to groupId ${POMGROUPID}"
POMGROUPPATH=$(echo "${POMGROUPID}" |sed -e 's/\./\//g')
#echo "DEBUG: Parsed ../pom.xml to group path ${POMGROUPPATH}"

export ARTIFACTID="${MVN_ARTIFACTID}"
if [ -z "${ARTIFACTID}" ] ; then
  echo "INFO: Trying to use artifactId from ../pom.xml"
  ARTIFACTID=$(echo "${POMCOORDINATES}" |cut -f2 -d',')
  #echo "DEBUG: Parsed ../pom.xml to artifact ID ${ARTIFACTID}"
else
  echo "INFO: Using artifactId from \$MVN_ARTIFACTID"
fi
if [ -z "${ARTIFACTID}" ] ; then
  echo "ERROR: Unable to compute artifactId in $(pwd)"
  exit 13
fi

DEBVERBETA=$(echo "${DEBVER}" |grep "beta")
#POMVERSNAPSHOT=$(echo "$POMVER" |egrep -- "-SNAPSHOT$") 
if [ -z "${DEBVERBETA}" ] ; then
  rm -rf downloads
fi

export JARVER=""
if [ -n "${DEBVERBETA}" ] ; then
  echo "INFO: Debian version contains 'beta', using locally built SNAPSHOT jars in modules' target dirs" 
  JARVER=$(echo "${DEBVER}" |cut -f1 -d'~')"-SNAPSHOT"
else
  JARVER=$(echo "${DEBVER}" |sed -e 's/-[0-9].*//g')
  echo "INFO: Debian version without 'beta', using prod jars from ${MVN_REPO}/${POMGROUPPATH}/"
fi
#echo "DEBUG: Computed JAR version to ${JARVER}"

if [ -n "${POMCOORDINATES}" ] ; then
  POMVER=$(echo "${POMCOORDINATES}" |cut -f3 -d',')
  if [ "$POMVER" != "$JARVER" ] ; then
  	 echo "WARNING: Debian changelog version ${DEBVER} computed to JAR version ${JARVER}, but ../pom.xml specifies version ${POMVER}."
  else
  	 echo "INFO: Debian changelog version ${DEBVER} computed to JAR version ${JARVER}, this fits ../pom.xml version ${POMVER}."
  fi
else
  echo "INFO: Debian changelog version ${DEBVER} computed to JAR version ${JARVER}, no ../pom.xml version to compare against."
fi

mkdir -pv downloads
cd downloads

DLJAR="${ARTIFACTID}-${JARVER}.jar"
#echo "DEBUG: Retrieving ${DLJAR}"
if [ -f "${DLJAR}" ] ; then
  echo "INFO: Already have ${DLJAR} in $(pwd):"
  ls -ld ${DLJAR}
  exit 0
fi

# beta? search module's target directory
if [ -n "${DEBVERBETA}" ] ; then
  if [ -f "../../target/${ARTIFACTID}-${JARVER}.jar" ] ; then
    #echo "INFO: Using locally built module jar in assumed CI environment ('beta' in debian version)" 
    cp -va ../../target/${ARTIFACTID}-${JARVER}.jar ${DLJAR}
    exit 0
  else
    echo "ERROR: No ../../target/${ARTIFACTID}-${JARVER}.jar in $(pwd)"
    exit 21
  fi
fi
# snapshot?
#WGETURL=""
# names of deployed snapshot bundles contain an unpredictable timestamp,
# and we don't want to get and parse maven-metadata.xml
#if [ -n "$(echo ${JARVER} |egrep -- '-SNAPSHOT$')" ] ; then
#  WGETURL="${MVN_SNAPSHOTREPO}/${POMGROUPPATH}/${ARTIFACTID}/${JARVER}/${ARTIFACTID}-${JARVER}.jar"
#  echo "INFO: GETing SNAPSHOT jar from ${WGETURL}" 
#else
  WGETURL="${MVN_REPO}/${POMGROUPPATH}/${ARTIFACTID}/${JARVER}/${ARTIFACTID}-${JARVER}.jar"
  #echo "INFO: GETing prod jar from ${WGETURL}"
#fi 
#echo "DEBUG: wget --user-agent=Mozilla ${WGETURL}"
#-o ${DLJAR} 
echo "INFO: Retrieving ${WGETURL}"
wget -q ${WGETAUTH} --user-agent=Mozilla ${WGETURL} && exit 0
echo "ERROR: Failed to wget ${WGETURL}"
exit 31
