#!/bin/bash
#
# PBA maven fetchbundles 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-fetchbundles
#   fetches bundles 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 is taken from ../pom.xml using pba-mvn-pomparser -q -c,
# unless pba-mvn2pkg-settings.sh overrides them, see below. 
#
# artifactIds are taken from each modules' pom.xml via pba-mvn-pomparser -q -c -m,
# 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_ARTIFACTIDS="foo-bar1 foo-bar2"

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_ARTIFACTIDS=""

. ./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_ARTIFACTIDS}" ] ; then
    echo "ERROR: No ../pom.xml in $(pwd) and not both MVN_GROUPID and MVN_ARTIFACTIDS set in pba-mvn2pkg-settings.sh."
    exit 4
  else
    echo "NOTICE: No ../pom.xml in $(pwd) but both MVN_GROUPID and MVN_ARTIFACTIDS 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
POMGROUPPATH=$(echo "${POMGROUPID}" |sed -e 's/\./\//g')
#echo "DEBUG: Parsed ../pom.xml to group path ${POMGROUPPATH}"

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

export ARTIFACTIDS="${MVN_ARTIFACTIDS}"
if [ -z "${ARTIFACTIDS}" ] ; then
  echo "INFO: Trying to use artifactIds from modules from ../pom.xml"
  # FIXME change to pba-mvn-pomparser -q -m
  ARTIFACTIDS=$(pba-mvn-pomparser -q -c -m ../pom.xml 2>/dev/null |cut -f2 -d',')
else
  echo "INFO: Using artifactIds from \$MVN_ARTIFACTIDS"
fi
if [ -z "${ARTIFACTIDS}" ] ; then
  echo "ERROR: Unable to compute artifactIds in $(pwd)"
  exit 13
fi

mkdir -pv downloads
cd downloads

for ARTIFACTID in $ARTIFACTIDS ; do
  echo "INFO: Working ARTIFACTID $ARTIFACTID"
  DLJAR="${ARTIFACTID}-${JARVER}.jar"
  #echo "DEBUG: Retrieving ${DLJAR}"
  if [ -f "${DLJAR}" ] ; then
    echo "INFO: Already have ${DLJAR} in $(pwd):"
    ls -ld ${DLJAR}
    continue
  fi
  # beta? search module's target directory
  if [ -n "${DEBVERBETA}" ] ; then
    if [ -f "../../${ARTIFACTID}/target/${ARTIFACTID}-${JARVER}.jar" ] ; then
      #echo "INFO: Using locally built module jar in assumed CI environment ('beta' in debian version)" 
      cp -va ../../${ARTIFACTID}/target/${ARTIFACTID}-${JARVER}.jar ${DLJAR}
      continue
    else
      echo "ERROR: No ../../${ARTIFACTID}/target/${ARTIFACTID}-${JARVER}.jar in $(pwd)"
      echo "HINT:  For SNAPSHOT fetching module subdirectories must match artifactIds."
      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} && continue
  echo "ERROR: Failed to wget ${WGETURL}"
  exit 31
done
cd ..

exit 0
