#!/usr/bin/bash
#
# Copyright (c) 2006 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
# Author: Greg Nichols

# Build an RHTS package from a CVS or Subversion working copy of the test

progname=$0
function usage () {
   cat <<EOF
Usage: $progname [-a] [-d directory] [-b] [-s testserver]
    Build an RHTS package of tests from the source tree "directory" 
    (e.g. a CVS working copy of the test).  If directory is not supplied, 
    the current directory is used.
    If testserver is supplied the resulting rpms will be submitted to the 
    testserver instead of being copied to the current working directory.
    By default it builds a noarch package; use -a to build an arch package
    -b says submit to beaker
EOF
   exit 0
}

SOURCE_DIR=`pwd`
UPLOAD_TO_BEAKER=""
ABI_OPTIONS=""
URL_OPTIONS=""

while getopts "d:s:bah" opt; do
   case $opt in

   d )  SOURCE_DIR=$OPTARG ;;
   s )  TESTSERVER=$OPTARG ;;
   b )  UPLOAD_TO_BEAKER=1 ;;
   a )  ABI_OPTIONS="--strict-abi" ;;
   h )  echo "found $opt" ; usage ;;
   \?)  usage ;;
   esac
done

shift $(($OPTIND - 1))

# This is currently hardcoded to create legacy package names
# due to task upgrade issues. See BZ1044913 for further details
# This can only be overridied with RHTS_RPM_NAME env var
NAME=`rhts-mk-get-test-package-name -d $SOURCE_DIR -l`
CURRENT_TAG=`rhts-mk-get-current-tag $SOURCE_DIR`

# Because of the need to use legacy names, we will be adding Provides for
# new style names. That way, when we do switch to not using legacy names,
# the "old" packages will have provides for the "new" packages.
NEW_PACKAGE_NAME=`rhts-mk-get-test-package-name -d $SOURCE_DIR`
provides="--provides $NEW_PACKAGE_NAME"
if [ -n "$RHTS_PROVIDES_PACKAGE" ]; then
    provides="--provides $RHTS_PROVIDES_PACKAGE $provides"
fi
# Unless we have passed in an RPM name, use the one decided
# for us
if [ -z "$RHTS_RPM_NAME" ]; then
    RHTS_RPM_NAME=$NAME
fi

VERSION=`rhts-mk-get-version-info -v $CURRENT_TAG`
RELEASE=`rhts-mk-get-version-info -r $CURRENT_TAG`
URL=`rhts-mk-get-test-package-url`
if [ -n "$URL" ] ; then
    URL_OPTIONS="--url $URL"
fi

echo "           CURRENT_TAG: $CURRENT_TAG"
echo "                  NAME: $RHTS_RPM_NAME"
echo "               VERSION: $VERSION"
echo "               RELEASE: $RELEASE"
echo "                   URL: $URL"
echo "            SOURCE_DIR: $SOURCE_DIR"

# if we are in git, we need a tag
if git log -1 &>/dev/null ; then
    if [[ -z "$CURRENT_TAG" ]] ; then
        echo "Error: no tags found" >&2
        echo "(Hint: make tag)" >&2
        echo "(Hint: to skip version control, move this task outside your git tree)" >&2
        exit 1
    fi
fi

# TMP_DIR: do everything for this run under a unique temp directory
TMP_DIR=`mktemp -d /tmp/rhts-build-XXXXXXXX` || exit 1
echo "               TMP_DIR: $TMP_DIR"

# BUILD_DIR: the build directory for rpmbuild operations (to avoid needing root permission)
BUILD_DIR=$TMP_DIR/rpm-build
echo "             BUILD_DIR: $BUILD_DIR"
mkdir $BUILD_DIR || exit 1

# GENERATED_SOURCE_DIR: 
# this directory will contain the generated specfile and tarball
GENERATED_SOURCE_DIR=$TMP_DIR/build
echo "  GENERATED_SOURCE_DIR: $GENERATED_SOURCE_DIR"
mkdir $GENERATED_SOURCE_DIR || exit 1

# INSTALL_DIR: what is this?
INSTALL_DIR=$TMP_DIR/install
echo "           INSTALL_DIR: $INSTALL_DIR"
mkdir $INSTALL_DIR || exit 1

BASE_SPECFILE=/usr/share/rhts/lib/rhts-package-tests.spec.in
TESTCOVERAGE=$GENERATED_SOURCE_DIR/testcoverage 

# if we are in git, ensure the tag has been pushed
if git log -1 &>/dev/null ; then
    if git config remote.origin.url >/dev/null ; then
        echo "Verifying that tag is present in remote: $CURRENT_TAG"
        CURRENT_HASH=$(git show-ref --hash --tags $CURRENT_TAG)
        REMOTE_HASH=$(git ls-remote origin --tags $CURRENT_TAG| awk {'print $1'})
        if [ "$CURRENT_HASH" != "$REMOTE_HASH" ]; then
            if [ -z "$REMOTE_HASH" ]; then
                echo "Error: current tag $CURRENT_TAG is not in remote 'origin'"
                echo "(Hint: git push --tags)"
            else
                echo "Error: local hash $CURRENT_HASH of tag $CURRENT_TAG is different from remote $REMOTE_HASH"
            fi
            exit 1
        fi
    fi
fi

GENERATED_SPECFILE=$GENERATED_SOURCE_DIR/$RHTS_RPM_NAME-$VERSION-$RELEASE.spec
TARBALL=$GENERATED_SOURCE_DIR/$RHTS_RPM_NAME-$VERSION-$RELEASE.tar.gz

echo "Creating tarball: $TARBALL"
if git log -1 &>/dev/null ; then
    git archive --format=tar $CURRENT_TAG | gzip >$TARBALL || exit 1
else
    tar --exclude "CVS" --exclude ".svn" --exclude ".git" --exclude "rhts-.\*\.rpm" -zcvf $TARBALL --directory $SOURCE_DIR . || exit 1
fi

echo "Gathering testinfo.desc files:"
# Extract tarball to a clean location and run "make testinfo.desc" in each location:
EXTRACT_DIR=$TMP_DIR/extract-for-metadata
echo "           EXTRACT_DIR: $EXTRACT_DIR"
mkdir $EXTRACT_DIR || exit $?
tar -zxvf $TARBALL --directory $EXTRACT_DIR/ || exit $?
pushd $EXTRACT_DIR
make testinfo.desc || exit $?
popd

echo "Generating specfile: $GENERATED_SPECFILE"
find $EXTRACT_DIR -name testinfo.desc | rhts-mk-generate-specfile $ABI_OPTIONS $URL_OPTIONS $RHTS_RPM_NAME $VERSION $RELEASE $provides  > $GENERATED_SPECFILE || exit $?
echo "Building package:"
rpmbuild  -bb --define "_binaries_in_noarch_packages_terminate_build 0" --define "_unpackaged_files_terminate_build 0" --define "_builddir $BUILD_DIR" --define "_sourcedir $GENERATED_SOURCE_DIR"  --define "_rpmdir $INSTALL_DIR" $GENERATED_SPECFILE || exit 1

#bpeck: if $(TESTSERVER) passed in then submit rpm.
if [ -n "$TESTSERVER" ]; then
    pushd $INSTALL_DIR
    for RPM in $(find . -name \*.rpm); do
        rhts-mk-test-import $TESTSERVER $RPM $VERSION-$RELEASE || exit 1
    done
    popd
elif [ -n "$UPLOAD_TO_BEAKER" ]; then
    pushd $INSTALL_DIR
    for RPM in $(find . -name \*.rpm); do
        bkr task-add $RPM || exit 1
    done
    popd
else
    #GBN: copy rpm to cwd
    cp $INSTALL_DIR/*/*.rpm .
fi

rm -rf $TMP_DIR
echo "Finished building test package"

