#!/bin/bash -e

MH_VERSION=$(ls /usr/share/maven-repo/org/debian/maven/maven-packager-utils/ | sed 's|/||')
. /usr/share/maven-repo-helper/mh_lib.sh

syntax()
{
   echo -e "Usage: mh_make [option]..."
   echo -e "Generate the Debian packaging by reading the information"
   echo -e "from the Maven POM."
   echo -e ""
   echo -e "Options:"
   echo -e "\t-h --help: show this text"
   echo -e "\t-V --version: show the version"
   echo -e "\t-s<svn url> --from-svn=<svn url>: download the source code from"
   echo -e "\t the SVN repository before building the Debian packaging. Use a tagged"
   echo -e "\t branch of the source code, for example"
   echo -e "\t http://svn.apache.org/repos/asf/felix/releases/org.osgi.core-1.2.0/"
   echo -e "\t-p<package> --package=<package>: name of the source package"
   echo -e "\t-b<package> --bin-package=<package>: name of the binary package"
   echo -e "\t-t<true|false> --run-tests=<true|false>: include or not the tests"
   echo -e "\t-d<true|false> --javadoc=<true|false>: include or not the javadoc"
   echo -e "\t  during the build"
   echo -e "\t-a --ant: use Ant for the packaging instead of Maven"
   echo -e "\t-v --verbose: show more information while running"
   echo -e ""
   echo -e "To have mh_make working properly, you need first to install on your system"
   echo -e "as many dependencies for your project as possible. Those dependencies should"
   echo -e "also contain the required Maven metadata (POM files and jars in the"
   echo -e "/usr/share/maven-repo repository)"
   echo -e ""
   echo -e "Environment variables:"
   echo -e "\tDEBFULLNAME - your full name, e.g. John Doe"
   echo -e "\tDEBEMAIL - your packager email address"
   echo -e "\tDEBLICENSE - the license for the files under the debian/ directory"
   echo -e "\t  must be one of GPL2, GPL3, LGPL2.1, Apache-2.0, BSD or any license"
   echo -e "\t  short name defined in http://dep.debian.net/deps/dep5/"
   exit 1
}

ARGS="p package b bin-package t run-tests d javadoc a ant v verbose s from-svn" parseargs "$@"

if [ -z "$DEBFULLNAME" ]; then
  echo "Please define the environment variable DEBFULLNAME, e.g."
  echo "export DEBFULLNAME=\"John Doe\""
  return;
fi

if [ -z "$DEBEMAIL" ]; then
  # Fall back on EMAIL when DEBEMAIL is not defined
  DEBEMAIL=$EMAIL
fi

if [ -z "$DEBEMAIL" ]; then
  echo "Please define the environment variable DEBEMAIL, e.g."
  echo "export DEBEMAIL=\"john.doe@where.no\""
  return;
fi

if [ -z "$DEBLICENSE" ]; then
    echo "Environment variable DEBLICENSE not set, using GPL-3+ by default"
    DEBLICENSE="GPL-3+"
fi

PACKAGE=$(getarg p package)
BIN_PACKAGE=$(getarg b bin-package)
RUN_TESTS=$(getarg t run-tests)
GEN_JAVADOC=$(getarg d javadoc)
ANT=$(getarg a ant)
FROM_SVN=$(getarg s from-svn)
VERBOSE=$(getarg v verbose)

if [ "$FROM_SVN" == "true" ]; then
	echo "The syntax for the --from-svn option is --from-svn=<url>, please try again"
	exit 1
fi

if [ -z "$PACKAGE" ]; then
    PACKAGE="$(basename $(pwd) | sed 's/-[0-9\.].*//')"
    if [ -n "$FROM_SVN" ]; then
	PACKAGE=$(echo "$FROM_SVN" | sed 's/-[0-9].*//')
        PACKAGE=$(echo "$PACKAGE" | sed 's|.*/||' )
    fi
    echo
    echo "Enter the name of the new Debian source package. If empty, it will defaults to $PACKAGE"
    read -p ">" USER_PACKAGE
    if [ -n "$USER_PACKAGE" ]; then
        PACKAGE=$USER_PACKAGE
    fi
fi

if [ -z "$BIN_PACKAGE" ]; then
    PKG=$PACKAGE
    if [ -z "${PKG##lib*-java}" ]; then
        BIN_PACKAGE="${PACKAGE}"
    else
        BIN_PACKAGE="lib${PACKAGE}-java"
    fi
	echo
    echo "Enter the name of the binary package. If empty, it will defaults to $BIN_PACKAGE"
    read -p ">" USER_PACKAGE
    if [ -n "$USER_PACKAGE" ]; then
        BIN_PACKAGE=$USER_PACKAGE
    fi
fi

if [ -z "$RUN_TESTS" ]; then
	echo
    echo "Run tests while building the package?"
    read -p "[y]/n > " RUN
    RUN_TESTS="true"
    if [ "$RUN" == "n" ]; then
        RUN_TESTS=
    fi
fi

if [ -z "$GEN_JAVADOC" ]; then
	echo
    echo "Generate the Javadoc while building the package?"
    read -p "[y]/n > " GEN
    GEN_JAVADOC="true"
    if [ "$GEN" == "n" ]; then
        GEN_JAVADOC=
    fi
fi

echo
echo "Checking that apt-file is installed and has been configured..."
if [ ! -x /usr/bin/apt-file ]; then
    echo "Error: apt-file is not available." >&2
    echo "Please install the 'apt-file' package and try again." >&2
    exit 1
else
    res="ok"
    apt-file search /usr/bin/mvnDebug | grep maven > /dev/null || res="failed"
    if [ $? != 0 ] || [ "$res" == "failed" ]; then
        echo "Warning: apt-file doesn't seem to be configured"
        apt-file update
    else
        echo '[ok]'
    fi
fi

echo
echo "Checking that licensecheck is installed..."
if [ ! -x /usr/bin/licensecheck ]; then
    echo "Error: licensecheck is not available." >&2
    echo "Please install the 'devscripts' package and try again." >&2
    exit 1
else
    echo '[ok]'
fi

if [ -n "$FROM_SVN" ]; then
	echo
	echo "Downloading the upstream sources..."
	SVN_OPTIONS=
	if [[ "$FROM_SVN" =~ https://.*\.dev\.java\.net/.* ]]; then
		echo "Press enter if a password is asked"
		SVN_OPTIONS="--username guest"
	fi
	svn export $FROM_SVN $PACKAGE $SVN_OPTIONS
	cd $PACKAGE
fi

if [ -e pom.xml.save ]; then
	mh_unpatchpoms -p$BIN_PACKAGE
fi

# Restore state after a brutal stop
if [ -f debian/$BIN_PACKAGE.poms ]; then
    mh_unpatchpoms -p$BIN_PACKAGE || true
fi
if [ -f debian/patches/series ]; then
    quilt pop -a || true
fi

# Apply existing quilt patchs as source 3(quilt) is used in the package
if [ -f debian/patches/series ]; then
    quilt push -a
fi

echo
java -cp /usr/share/java/maven-project.jar:/usr/share/java/maven-repo-helper.jar:/usr/share/java/maven-packager-utils.jar:/usr/share/maven2/lib/maven-debian-uber.jar org.debian.maven.packager.DependenciesSolver --verbose --package="$BIN_PACKAGE" ${ANT:+--ant} ${GEN_JAVADOC:+--generate-javadoc} ${RUN_TESTS:+--run-tests} ${VERBOSE:+--verbose} --maven-repo=/usr/share/maven-repo

if [ $? != 0 ]; then
    if [ -f debian/patches/series ]; then
        quilt pop -a
    fi
    exit 1
fi

eval $(cat debian/$BIN_PACKAGE.substvars | sed -e 's/maven\./maven_/' | grep maven_UpstreamPackageVersion)

mh_patchpoms ${VERBOSE:+--verbose} -p$BIN_PACKAGE -rdebian/maven.rules -idebian/maven.ignoreRules --keep-pom-version

mvn org.debian.maven:maven-packager-utils:$MH_VERSION:generate -Demail="$DEBEMAIL" -Dpackager="$DEBFULLNAME" -DpackagerLicense="$DEBLICENSE" -Dpackage="$PACKAGE" -Dbin.package="$BIN_PACKAGE" -DrunTests="$RUN_TESTS" -DgenerateJavadoc="$GEN_JAVADOC" -Dmaven.repo.local=/usr/share/maven-repo ${ANT:+-DpackageType=ant} ${FROM_SVN:+-DdownloadUrl=scm:svn:$FROM_SVN} --offline

if [ $? != 0 ]; then
    if [ -f debian/$BIN_PACKAGE.poms ]; then
        mh_unpatchpoms -p$BIN_PACKAGE
    fi
    if [ -f debian/patches/series ]; then
        quilt pop -a
    fi
    exit 1
fi

if [ ! -f debian/changelog ]; then
    debianVersion=$(echo ${maven_UpstreamPackageVersion} | sed -re's/-(alpha|beta)-?/~\1/')
    dch --create --newversion=${debianVersion}-1 --package=$PACKAGE "Initial release (Closes: #nnnn)  <nnnn is the bug number of your ITP>"
fi

if [ -f debian/$BIN_PACKAGE.poms ]; then
    mh_unpatchpoms -p$BIN_PACKAGE
fi
if [ -f debian/patches/series ]; then
    quilt pop -a
fi

rm -f debian/*.substvars
rm -f .debianVersion
rm -f velocity.log
