#!/bin/sh -eu

SetupMethods()
{
	local suffix="$1" inm="$2"; shift 2
	inm=$(IFS="$IFS,"; echo $inm)
	local allm= f=
	for f in /usr/lib/rpm/*.$suffix; do
		[ -f "$f" ] || continue
		f=$(basename "$f" ."$suffix")
		allm=" $allm $f"
	done
	[ -n "$allm" ] || Fatal "No $suffix methods available"
	local outm="$allm"
	for m in $inm; do
		case $m in
			yes|auto|all)
				outm=$allm
				;;
			no|none|off|false|skip)
				outm=
				;;
			no*)
				m=${m#no}
				outm=$(echo "$outm" |sed "s/ $m / /g")
				;;
			/*/*)
				[ -f "$m" -a -x "$m" ] || Fatail "Method $m not available"
				[ -n "$outm" -a -z "${outm##* $m *}" ] || outm=" $outm $m "
				;;
			*)
				[ -z "${allm##* $m *}" ] || Fatail "Method $m not available"
				[ -n "$outm" -a -z "${outm##* $m *}" ] || outm=" $outm $m "
				;;
		esac
	done
	echo $outm
}

ShowMethods()
{
	local fmt="$1" methods="$2"; shift 2
	[ -n "$methods" ] || methods=skip
	printf "$fmt\n" "$(echo "$methods" |tr ' ' ',')"
}

DoMethods()
{
	local m= suffix="$1" methods="$2"; shift 2
	for m in $methods; do
		case $m in
			/*/*) "$@" $m ;;
			*) "$@" /usr/lib/rpm/$m.$suffix ;;
		esac
	done
}

methods=$(SetupMethods req all,noperl)
ShowMethods "Finding required packages (%s)" "$methods"
DoMethods req "$methods" echo
