#!/usr/bin/env bash
# Copyright 2006-2010 Gentoo Foundation; Distributed under the GPL v2

# <grobian@gentoo.org> -- 2010-01-18
# no longer auto-migrate gx86 keywords to Prefix ones
# <grobian@gentoo.org> -- 2009-09-29
# warn when no KEYWORDS line is found, allow KEYWORDS to be preceded by
# whitespace
# <grobian@gentoo.org> -- 2006-09-22
# ecleankw weeds out all keywords in $KEYWORDS of an ebuild that are not
# in $my_keywords.  Next to that, it currently drops all left over
# keywords back to ~arch.  (The script basically performs a full inner
# join, based on the nested loop algorithm.)
# For exg: this script does in fact the intersection of my_keywords and
# KEYWORDS and drops the intersection to ~arch.  In this case it's equal
# to the full inner join, because in theory we have (unique) sets.

# these need to reflect the keywords that are valid for the tree
my_keywords="
	ppc-aix
	x86-freebsd x64-freebsd
	hppa-hpux ia64-hpux
	x86-interix
	amd64-linux x86-linux ia64-linux
	ppc-macos x86-macos x64-macos
	sparc-solaris sparc64-solaris x86-solaris x64-solaris
	x86-winnt
	m68k-mint
"

if [[ -z $1 ]] ; then
	files="*.ebuild"
else
	files="$*"
fi

for f in $files ; do
	echo -n "Processing $f ... "
	newkw=""
	if [[ $(egrep "^[ 	]*KEYWORDS=" "$f" | wc -l) != 1 ]] ; then
		echo "ABORTED"
		echo "ERROR: $f has no or multiple KEYWORDS= lines, leaving ebuild untouched"
		continue
	fi
	eval $(egrep "^[ 	]*KEYWORDS=" "$f")
	for kw in $KEYWORDS ; do
		for mkw in $my_keywords ; do
			if [[ $kw == $mkw || $kw == ~$mkw ]] ; then
				newkw="$newkw ~$mkw"
				break
			fi
		done
	done
	sed -i \
		-e "s|^\([ \t]*\)KEYWORDS=.*$|\1KEYWORDS=\"${newkw:1}\"|" \
		"$f"
	echo "${newkw:1}"
done
