#!/bin/bash
if [ -e /etc/cmake-fedora.conf ]; then
    source /etc/cmake-fedora.conf
fi

FEDORA_RAWHIDE_VERSION=${FEDORA_RAWHIDE_VERSION:-""}
FEDORA_SUPPORTED_VERSIONS=${FEDORA_SUPPORTED_VERSIONS:-""}
EPEL_SUPPORTED_VERSIONS=${EPEL_SUPPORTED_VERSIONS:-""}

FEDORA_CURRENT_RELEASE_TAGS="f${FEDORA_RAWHIDE_VERSION}"
for f in ${FEDORA_SUPPORTED_VERSIONS}; do
    FEDORA_CURRENT_RELEASE_TAGS="${FEDORA_CURRENT_RELEASE_TAGS} f${f}"
done

for e in ${EPEL_SUPPORTED_VERSIONS}; do
    EPEL_CURRENT_RELEASE_TAGS="${EPEL_CURRENT_RELEASE_TAGS} el${e}"
done

function print_usage(){
    cat <<END
Usage: $0 <srpm> [fedora | fedoraReleases]  [epel | epelReleases]
This command does the scratch build for fedora and epel releases with koji

Options:
    srpm: SRPM file to be sent to koji
    fedora: to build the currently supported fedora releases
        (i.e. $FEDORA_CURRENT_RELEASE_TAGS)
    fedoraReleases: The fedora releases to be built. (such as $FEDORA_CURRENT_RELEASE_TAGS)
    epel: to build the currently supported fedora releases
        (i.e. $EPEL_CURRENT_RELEASE_TAGS)
    epelReleases: The fedora releases to be built. (such as $EPEL_CURRENT_RELEASE_TAGS)


If neither fedora releases nor epel releases are specified, then it builds
both fedora and epel releases.
END
}

if [[ $# < 1 ]];then
    print_usage
    exit 0
fi

srpm="$1"
shift

_SUFFIX="-candidate"
TARGETS=

for i in $@; do
    case $i in
	fedora )
	    TARGETS+=" $FEDORA_CURRENT_RELEASE_TAGS"
	    ;;
	epel )
	    TARGETS+=" $EPEL_CURRENT_RELEASE_TAGS"
	    ;;
	* )
	    TARGETS+=" $i"
	    ;;
    esac
done

TARGETS=${TARGETS:-"$FEDORA_CURRENT_RELEASE_TAGS $EPEL_CURRENT_RELEASE_TAGS"}

for t in $TARGETS; do
#    echo "koji build --scratch $t$_SUFFIX $srpm"
    if [ ! "x$t" = "xrawhide" -a ! "x$t" = "xf${FEDORA_RAWHIDE_VERSION}" ]; then
	t=$t$_SUFFIX
    fi
    if ! koji build --scratch "$t" "$srpm"; then
	echo "Koji build failed on $t" > /dev/stderr
	exit 1
    fi
done

