#!/usr/bin/env bash
# $Id: mockbuild 362 2008-01-07 18:18:05Z mbhowmic $

RESULTBASE="/opt/data/mock-rhel5"
REPOCACHE="${HOME}/rpmbuild/repocache-5"

if [ ${#} != 2 ]
then
    echo "Usage: $(basename ${0}) <arch> <specfile>.spec"
    exit 1
fi

if [ "${1}" != "x86_64" ] && [ "${1}" != "i386" ]
then
    echo "Arch must be x86_64 or i386"
    exit 1
fi
ARCH=${1}

if [ "${ARCH}" == "x86_64" ]
then
    MOCKCMD="mock"
else
    MOCKCMD="linux32 mock"
fi
shift

SPECFILE=${1}

if [ "$(expr "${SPECFILE}" : '.*\(spec\)')" != "spec" ]
then
    echo "${SPECFILE} is not a spec file."
    exit 1
fi

if [ ! -r "${SPECFILE}" ]
then
    echo "Cannot read ${SPECFILE}"
    exit 1
fi

if [ ! -e ${RESULTBASE} ]
then
    mkdir -p ${RESULTBASE}
fi

if [ -e ${HOME}/.mock/default.cfg ] && [ -e ${HOME}/.mock/defaults.cfg ]
then
    CONFIGDIR="${HOME}/.mock"
else
    CONFIGDIR="/etc/mock"
fi

if SRPM=$(rpmbuild -bs --nodeps ${SPECFILE} | awk '{print $2}')
then
    RESULTDIR=$(rpm -qp ${SRPM} --queryformat '%{NAME}\n')
    ${MOCKCMD} --resultdir=${RESULTBASE}/${RESULTDIR} --configdir=${CONFIGDIR} --arch=${ARCH} -r rhel-5-${ARCH} rebuild ${SRPM}
else
    echo "Cannot create srpm from ${SPECFILE}"
    exit 1
fi

if which createrepo &>/dev/null
then
    createrepo --update -c ${REPOCACHE} -x *debuginfo* -d ${RESULTBASE}
fi

exit 0
# vim:syntax=sh
# vim:sw=4:softtabstop=4:expandtab
