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

# <grobian@gentoo.org> -- 2009-04-04
# add eapi mode which only removes EAPI=prefix
# <grobian@gentoo.org> -- 2009-03-27
# add switch to control full reverse of eapify and gentoo-x86
# compatibility mode, set the latter one as default
# <grobian@gentoo.org> -- 2007-11-08
# initial version of the reverse of eapify, in its simplest form, only
# working for the latest prefix API


replace() {
	local cnt
	echo -n "  replacing $1 -> $2 ... "
	[[ -z $2 ]] \
		&& cnt=$(sed -e "${4:-s}|$1|$2|g" "$3" | diff -U0 "$3" - | wc -l) \
		|| cnt=$(sed -e "${4:-s}|$1|$2|g" "$3" | diff "$3" - | grep -o "$2" | wc -l)
	if [[ $cnt > 0 ]];
	then
		sed -i -e "${4:-s}|$1|$2|g" "$3"
		echo -n "$cnt occurence"
		[[ $cnt == 1 ]] \
			&& echo "" \
			|| echo "s"
	else
		echo "not found"
	fi
}

do_usage() {
	echo "usage: ${0##*/} [-m <compat|reverse|eapi>] [file ...]"
	exit
}

MODE=compat

while [[ ${#*} > 0 ]] ; do
	case $1 in
		-h)
			do_usage
		;;
		-m*)
			arg=${1#-m}
			if [[ -z ${arg} ]] ; then
				shift
				arg=$1
			fi
			case ${arg} in
				reverse|rev)        MODE=reverse  ;;
				compatible|compat)  MODE=compat   ;;
				eapi)               MODE=eapi     ;;
				*)
					do_usage;
				;;
			esac
		;;
		*)
			files="${files} $1"
		;;
	esac
	shift
done

# default to all ebuilds if no files given
[[ -z $files ]] && files="*.ebuild"

for f in $files ; do
	if [[ ! -f $f ]] ; then
		echo "no such file: $f"
		exit -1
	fi

	echo "Processing $f"

	unset EAPI
	echo -n "  EAPI ... "
	eval "$(egrep "^EAPI=" "$f")"

	if [[ ${EAPI} == "prefix "* ]] ; then
		echo "demoting ${EAPI}"
		sed -i \
			-e '/^EAPI=/cEAPI='"${EAPI#prefix }" \
			"$f"
	elif [[ ${EAPI} == "prefix" ]] ; then
		echo "removing ${EAPI}"
		sed -i \
			-e '/^$/{' \
			-e 'N' \
			-e '/^\nEAPI=/d' \
			-e '}' \
			"$f"
	elif [[ -n ${EAPI} ]] ; then
		echo "retaining ${EAPI}"
	else
		echo "absent"
	fi

	if [[ ${MODE} == "reverse" ]] ; then
		# we replace all ${ED} with ${D}, no need to care about make install
		replace '${ED}' '${D}' "$f"

		# replace ${EROOT} with ${ROOT}
		replace '${EROOT}' '${ROOT}' "$f"

		# get rid of ${EPREFIX}
		replace '${EPREFIX}' '' "$f"
	elif [[ ${MODE} == "compat" ]] ; then
		# expand ${ED} into ${D}${EPREFIX}
		replace '${ED}' '${D%/}${EPREFIX}/' "${f}"

		# expand ${EROOT} into ${ROOT}${EPREFIX}
		replace '${EROOT}' '${ROOT%/}${EPREFIX}/' "${f}"
	elif [[ ${MODE} == "eapi" ]] ; then
		# we already de-eapi-fied, so nothing to do here!
		:
	else
		echo "I don't know this mode: ${MODE}"
	fi
done
