#!/bin/bash

   ##########################################################
  #   Written 10/29/2009 and released under the GNU/GPLv2  ##
 #  (c) Jeff Schroeder (jeffschroeder@computer.org)       # #
##########################################################  #
#                                                        #  #
# pkgbuild - Build a rpm package when fed a valid spec   #  #
#            file or source rpm. I've been putting off   #  #
#            writing this exact thing and finally did it #  #
#                                                        # #
##########################################################

# http://www.digitalprognosis.com

usage() {
    # Use <<-EOF and tabs for an indented here document
    cat <<-EOF
	Usage: $(basename $0) [arch] [package]
	Build a custom gnome rpm in a mock chroot.

	    [arch]    can be either i386 or x86_64.
	    [package] can be either a valid spec file or src.rpm.

	Try putting this in ~/.bashrc:
	  export CUSTOM_MOCK_OPTIONS="--resultdir ${HOME}/build/RPMS/"
	  alias build32="pkgbuild i386"
	  alias build64="pkgbuild x86_64"
	EOF
}

arch="$1"
package="$2"

if [ "$arch" = "-h" -o "$arch" = "--help" -o $# -eq 0 ]; then
    usage
    exit 0
fi

# RHEL5's older coreutils complains about unportable BRE
# if the regex passed to expr starts with a caret (^). The
# version in Fedora is happy to accept this for some reason.
if ! expr "$arch" : '^i386$\|^x86_64$' >/dev/null 2>&1; then
    echo "ERROR: '$arch' is an invalid architecture" >&2
    usage
    exit 1
elif [ ! -e "$package" ]; then
    echo "ERROR: '$package' is not a valid file" >&2
    usage
    exit 1
fi

# Support ${package_name}.spec or ${package_name}.src.rpm
if expr "$package" : '^.*\.spec$' >/dev/null 2>&1; then
    # Change package from the spec file into the binary srpm if it builds
    package=$(rpmbuild -bs --nodeps $package | awk '/Wrote:/{print $NF}')

    # In case of errors, rpmbuild will spit them out so quietly exit.
    # See bash(1) for more info about PIPESTATUS
    if [ ${PIPESTATUS[0]} -ne 0 ]; then
        exit 1
    fi
elif ! expr "$package" : '^.*\.src.rpm$' >/dev/null 2>&1; then
    echo "ERROR: '${package}' must be a spec file or source rpm" >&2
    usage
    exit 1
elif [ ! -e "$package" ]; then
    echo "ERROR: '$package' didn't properly build or file not found" >&2
    exit 1
fi

# Lets do this!
mock $CUSTOM_MOCK_OPTIONS -r epel-5-$arch rebuild $package
