#!/bin/ash -euf
# -*- mode: Shell-script; tab-width: 8; fill-column: 70; -*- 
# $Id: buildarch.ash,v 0.0.1 2006/04/14 17:30:05 legion Exp $ 
#
# This script shows the list of Sisyphus build architecture for SRPM package
#

delim=' '
filename=
ARCHITECTURES=
PROG="${0##*/}"

usage() {
    [ "$1" = 0 ] || exec >&2
    cat << EOF
Usage: $PROG [options]

Options:
    -f, --filename
    -a, --archs=LIST
    -d, --delim=STRING
    -h, --help                   show this message;

EOF
    [ -n "$1" ] && exit "$1" || exit
}

TEMP=`getopt -n $PROG -o a:,d:,f,h -l archs:,delim:,filename,help -- "$@"` || usage 1
eval set -- "$TEMP"

while :; do
    case $1 in
	-f|--filename) filename=1
	    ;;
	-a|--archs) shift
	    ARCHITECTURES="$1"
	    ;;
	-d|--delim) shift
	    delim="$1"
	    ;;
	-h|--help) usage 0
	    ;;
	--) shift; break
	    ;;
	*) echo "unrecognized option: $1" >&2
	    ;;
    esac
    shift
done

# All supported architecture in Sisyphus repository are listed in ARCHITECTURES.
: ${ARCHITECTURES?required}

exclude() {
    [ "$#" -gt 1 ] || return 0
    local p= o=
    p="$1" && shift
    while [ "$#" -gt 0 ]; do
	[ "$1" != "$p" ] && o="$o $1"
	shift
    done
    printf %s "${o# }"
}

in_list() {
    local list=" ${*#$1 } "
    [ "$list" != "${list#* $1 }" ]
}

while read f; do
    [ -n "$f" -a "$f" != "${f%.src.rpm}" ] || continue
    f="$(readlink -ve "$f")" || continue

    if ! values="$(LC_ALL=C rpmquery -p --qf='
exclusive_arch=\"[%{EXCLUSIVEARCH} ]\";
exclude_arch=\"[%{EXCLUDEARCH} ]\"; 
build_archs=\"[%{BUILDARCHS} ]\";
' -- "$f")"; then
	printf %s "Error: rpmuery failed!">&2
	continue
    fi
    exclusive_arch= exclude_arch= build_archs=
    eval "$values"
    unset values
    
    [ -z "$filename" ] || printf %s%s "${f##*/}" "$delim"

    # Only first element will be used by rpm.
    build_arch="${build_archs%% *}"

    # NOARCH package we may build anywhere.
    [ "$build_arch" = "noarch" ] && exclude "noarch" $ARCHITECTURES && printf \\n && continue ||:

    valid_archs= # This variable facilitates work in mode `set -x'
    for a in $ARCHITECTURES; do
	[ "$a" != "noarch" ] || continue
	
	# BUILDARCH equivalent `rpm --target ...`
	[ -n "$build_arch" ] && [ "$a" != "$build_arch" ] && continue ||:

	# Exclusive ARCH check: ignore this architecture if current architecture not in list of exclusive architectures.
	[ -n "$exclusive_arch" ] && ! in_list "$a" $exclusive_arch && continue ||:
  
	# Exclude ARCH check: we must ignore architecture if current architecture in list of excluded architectures.
	[ -n "$exclude_arch" ] && in_list "$a" $exclude_arch && continue ||:

	valid_archs="$valid_archs$delim$a"
    done

    printf %s\\n "${valid_archs#$delim}"
done
