#!/bin/bash --

set -e

. /usr/share/maven-repo-helper/mh_lib.sh

syntax()
{
   echo -e "Usage: mh_patchpoms [option]..."
   echo -e "Reads the file debian/\$package.poms and tranform each POM file"
   echo -e "listed in the .poms file into a POM file using the Debian versions"
   echo -e "of the libraries. Also keeps a backup of each POM file which can"
   echo -e "be restored with mh_unpatchpoms"
   echo -e ""
   echo -e "Options:"
   echo -e "\t-h --help: show this text"
   echo -e "\t-V --version: show the version"
   echo -e "\t-p<package> --package=<package>: package to act on "
   echo -e "\t-r<rules> --rules=<rules>: gives the location of the rules file for"
   echo -e "\t  special properties. Optional, the default location is"
   echo -e "\t  debian/maven.rules"
   echo -e "\t-u<rules> --published-rules=<rules>: path to the file containing the"
   echo -e "\t  extra rules to publish in the property debian.mavenRules in the cleaned POM"
   echo -e "\t  Optional, the default location is debian/maven.publishedRules"
   echo -e "\t-i<rules> --ignore-rules=<rules>: path to the file containing the"
   echo -e "\t  extra rules use to remove certain dependencies from the cleaned POM"
   echo -e "\t  Optional, the default location is debian/maven.ignoreRules"
   echo -e "\t-s --no-rules: don't apply any rules for converting versions,"
   echo -e "\t  do not even convert versions to the default 'debian' version"
   echo -e "\t-k --keep-pom-version: keep the original version of the POMs but, "
   echo -e "\t  convert all other versions in dependencies and plugins"
   echo -e "\t-v --verbose: show more information while running"
   echo -e "\t-n --no-act: don't actually do anything, just print the results"
   exit 1
}

ARGS="p package r rules u published-rules i ignore-rules s no-rules k keep-pom-version v verbose n no-act" parseargs "$@"

RULES=$(getarg r rules)
PUBLISHED_RULES=$(getarg u published-rules)
IGNORE_RULES=$(getarg i ignore-rules)
NORULES=$(getarg s no-rules)
KEEP_POM_VERSION=$(getarg k keep-pom-version)
PACKAGE=$(getarg p package)
PACKAGE=${PACKAGE:?"Package parameter (-p) is mandatory"}
VERBOSE=$(getarg v verbose)
NOACT=$(getarg n no-act)

if [ -z "$RULES" ]; then
    if [ -f debian/maven.rules ]; then
        RULES="debian/maven.rules"
    fi
fi

DH_OPTS="${VERBOSE:+-v}"
MH_ARGS="--package=${PACKAGE} ${RULES:+--rules=$RULES} ${KEEP_POM_VERSION:+--keep-pom-version} ${PUBLISHED_RULES:+--published-rules=$PUBLISHED_RULES} ${IGNORE_RULES:+--ignore-rules=$IGNORE_RULES} ${NORULES:+--no-rules}"

if [ -z "$NOACT" ]; then
    cat debian/$PACKAGE.poms | while read POM OPT1 OPT2; do
        if [ ! -z "$POM" ]; then
            cp $POM $POM.save
        fi
    done
    java -cp $CLASSPATH $JAVA_OPTIONS org.debian.maven.repo.POMTransformer $DH_OPTS $MH_ARGS
fi

