#!/bin/bash
# 2008 Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain

# Get replacement rule for ALT package to local in $1 (scan for files in $@)
# set ALTPKGNAME, TARGETPKGNAME variable
tolocal_anyrepl()
{
	local i REPLRULE WARULES
	local GREP=$1
	shift
	# TODO: fix space removing
	WARULES="s/^ *//g 
		s/ *\$//g 
		s/ *|/|/g 
		s/| */|/g"

	for i in $@ ; do
		REPLRULE=`grep -v "^#" "$i" 2>/dev/null | grep -- "^ *$GREP *|" | sed -e "$WARULES" | head -n1`
		# For broken rule
		echo $REPLRULE | grep "|" >/dev/null || REPLRULE=""
		#REPLRULE=`echo $REPLRULE | sed -r -e 's,|,!,g'`
		ALTPKGNAME=`echo $REPLRULE | cut -d"|" -f1 | sed -e "s|\+|\\\\\+|g"`
		TARGETPKGNAME=`echo $REPLRULE | cut -d"|" -f2 | sed -e "s|\+|\\\\\+|g"`
		test -n "$REPLRULE" && return 0
	done

	# Hack for default replace -devel to -dev on Deb target
	if [ "$TARGET" = "deb" ] ; then
		local NEWRESULT=`echo $GREP | sed -e "s|^ *\(.*\)-devel *\$|\1-dev|g"`
		[ "$NEWRESULT" = "$GREP" ] && return 1
		ALTPKGNAME=$GREP
		TARGETPKGNAME="$NEWRESULT"
		return 0
	fi
	return 1
}

# Clean require names from various stuffs
clean_pkgreq()
{
	local i VAR
	VAR=`cat`
	for i in $VAR ; do
		echo "$i" | grep "[()<=>]" >/dev/null && continue
		echo "$i" | grep "^ *[0-9]\.[0-9]" >/dev/null && continue
		echo -n "$i "
	done
}

# Print list of all build requires in ALT notation
print_buildreq()
{
	eval_spec ${1} | grep "Build.*Req" | sed -e "s|^.*:||g" | clean_pkgreq
}

# Print list of all pkg requires
print_pkgreq()
{
	eval_spec ${1} | grep "Requires" | sed -e "s|^.*:||g" | clean_pkgreq
}

# internal
print_replbased_list()
{
	local REPLBASE="$1"
	# VENDOR, TARGET is already defined in detect_target_env() func
	[ -z "$DISTRVERSION" ] && DISTRVERSION=`distr_vendor -v`

	# separate checking for x86_64
	[ $(uname -m) = "x86_64" ] && echo -n "$REPLBASE.$VENDOR.$DISTRVERSION.x86_64 $REPLBASE.$VENDOR.x86_64 "
	[ "$VENDOR" != "alt" ] && [ $(uname -m) = "x86_64" ] && echo -n "$REPLBASE.$TARGET.x86_64"

        # general rules listing
	echo -n "$REPLBASE.$VENDOR.$DISTRVERSION $REPLBASE.$VENDOR "
	[ "$VENDOR" != "alt" ] && echo -n "$REPLBASE.$TARGET"

}

# TODO: list in  alph. order and use if <= then our version
print_pkgrepl_list()
{
	print_replbased_list $PKGREPLBASE/pkgrepl
}

print_grprepl_list()
{
	print_replbased_list $PKGREPLBASE/../grprepl/grprepl
}


# Prints out buildreqs in target notation for SPEC (1st arg)
print_target_buildreq()
{
	local i SPACE="" TARGETPKGNAME
	# Build list in target ($VENDOR) notation for package's buildreqs
	for i in `print_buildreq ${1}` ; do
		# get target name or just print out original one
		tolocal_anyrepl $i `print_pkgrepl_list` || TARGETPKGNAME="$i"
		echo -n "$SPACE${TARGETPKGNAME}"
		SPACE=" "
	done
}
