#!/bin/sh -efu

PROG="${0##*/}"

[ -f /etc/rpm/rpmwraprc ] && . /etc/rpm/rpmwraprc ||:
[ -f ~/.rpmwraprc ] && . ~/.rpmwraprc ||:

: ${RPM_PREFIX:="/usr/bin"}
: ${RPM:="$RPM_PREFIX/rpm"}
: ${macrofile:=".rpmwrapmacros"}
: ${allow_prefix:=}

case "$PROG" in
    rpmwrap-*)
	PROG="${PROG#rpmwrap-}"
	;;
    rpmwrap)
	if [ $# -eq 0 ]; then
	    cat <<EOF
$PROG is a simple rpm/rpmbuild wrapper for using different
rpm macro files depending on current working directory.

Usage:

1) Make a symlink somewhere in \$PATH pointing to $PROG.
   \$RPM_PREFIX/<symlink basename> will be called with
   appropriate arguments.

2) Make a symlink somewhere in \$PATH pointing to $PROG
   with name $PROG-<something> \$RPM_PREFIX/<something>
   will be called with appropriate arguments.

   In this case you can have both, e.g., rpm and $PROG-rpm
   in the same directory.

3) Run $PROG <something>, \$RPM_PREFIX/<something> will
   be called with appropriate arguments.

Variables:

RPM_PREFIX   = \`$RPM_PREFIX'
RPM          = \`$RPM'
macrofile    = \`$macrofile'
allow_prefix = \`$allow_prefix'
EOF
	    exit 0
	fi
	PROG="${1##*/}"
	shift
	;;
    *)
	;;
esac

cwd="$(pwd)"
rpmmacros=
prefix=

if [ -n "$allow_prefix" ]; then
    sIFS="$IFS"
    IFS=":"
    for i in $allow_prefix; do
	case "$cwd" in
	    $i/* | $i)
		prefix="$i"
		break
		;;
	    *)
		continue
	    ;;
	esac
    done
    IFS="$sIFS"
fi

if [ -n "$prefix" ]; then
    startdir="$cwd"
    while :; do
	case "$startdir" in
	    "$prefix/"*)
		[ -f "$startdir/$macrofile" ] && rpmmacros="$startdir/$macrofile" ||:
		[ -n "$rpmmacros" ] && break ||:
		;;
	    "$prefix")
		[ -f "$startdir/$macrofile" ] && rpmmacros="$startdir/$macrofile" ||:
		break
		;;
	    *)
		break
	    ;;
	esac
	startdir="$(dirname $startdir)"
    done
fi

rpmrc=
exit_handler()
{
	local rc=$?
	trap - EXIT
	[ -z "$rpmrc" ] || rm -r -- "$rpmrc"
	exit $rc
}

if [ -n "$rpmmacros" ]; then
    rpmrc="$(mktemp -t "$PROG-rpmrc.XXXXXXXX")"
    trap exit_handler HUP PIPE INT QUIT TERM EXIT
    macrofiles="$($RPM --showrc| grep macrofiles)"
    macrofiles="${macrofiles#macrofiles}"
    macrofiles="${macrofiles#*:}"
    cat <<EOF > "$rpmrc"
include:	/usr/lib/rpm/rpmrc
macrofiles:	${macrofiles+$macrofiles:}$rpmmacros
EOF
fi

[ -x "$RPM_PREFIX/$PROG" ]  && "$RPM_PREFIX/$PROG" ${rpmrc:+--rcfile="$rpmrc"} ${rpmmacros:+--define "_macropath $startdir"} "$@"
