#!/gentoo/prefix64/usr/bin/bash

# for expansion below we need some things to be defined
prefix="/var/tmp/portage-tmpinst"
exec_prefix="${prefix}"

# For bug #279550 we have to do some nasty trick to make sure that sed
# doesn't strip the backslash in the replacement value (because it can
# be a backreference) and hence escape those.  Eventually in strings we
# need to escape the backslash too, such that the single backslash
# doesn't get lost when considered an invalid escape
rootuser='ruurd'
portagegroup='merlijn'
portageuser='ruurd'
rootuser=${rootuser//\\/\\\\}
portagegroup=${portagegroup//\\/\\\\\\\\}
portageuser=${portageuser//\\/\\\\\\\\}

# there are many ways to do this all dynamic, but we only care for raw
# speed here, so let configure fill in this list and be done with it
at='@'
sedexp=(
	-r
	-e "s,${at}PORTAGE_BASE${at},${exec_prefix}/lib/portage,g"
	-e "s,${at}PORTAGE_BASE_PATH${at},${exec_prefix}/lib/portage,g"
	-e "s,${at}PORTAGE_BIN_PATH${at},${exec_prefix}/lib/portage/bin,g"
	-e "s,${at}PORTAGE_BASH${at},/gentoo/prefix64/usr/bin/bash,g"
	-e "s,${at}PORTAGE_EPREFIX${at},/var/tmp/portage-tmpinst,g"
	-e "s,${at}PORTAGE_MV${at},/gentoo/prefix64/usr/bin/mv,g"
	-e "s,${at}PREFIX_PORTAGE_PYTHON${at},/gentoo/prefix64/usr/bin/python,g"
	-e "s,${at}EPREFIX${at},/var/tmp/portage-tmpinst,g"
	-e "s,${at}INSTALL_TYPE${at},SYSTEM,g"
	-e "s,${at}datadir${at},${prefix}/share,g"
	-e "s,${at}portagegroup${at},${portagegroup},g"
	-e "s,${at}portageuser${at},${portageuser},g"
	-e "s,${at}rootgid${at},500,g"
	-e "s,${at}rootuid${at},501,g"
	-e "s,${at}rootuser${at},${rootuser},g"
	-e "s,${at}sysconfdir${at},${prefix}/etc,g"
)

if [[ $1 == --hprefixify ]] ; then
	shift
	dirs='/(usr|lib(|[onx]?32|n?64)|etc|bin|sbin|var|opt|run)'
	sedexp+=(
		-e 's,([^[:alnum:]}\)\.])'"${dirs}"',\1/var/tmp/portage-tmpinst/\2,g'
		-e 's,^'"${dirs}"',/var/tmp/portage-tmpinst/\1,'
	)
fi

sources=( )
target=
args=( "$@" )

while [[ ${#@} != 0 ]] ; do
	case "$1" in
		-t)
			[[ -n ${target} ]] && sources=( "${sources[@]}" "${target##*/}" )
			shift
			target=":${1}"
		;;
		-*)
			shift
		;;
		*)
			if [[ -z ${target} ]] ; then
				target="${1}"
			elif [[ ${target} != ":"* ]] ; then
				sources=( "${sources[@]}" "${target##*/}" )
				target="${1}"
			else
				sources=( "${sources[@]}" "${1##*/}" )
			fi
		;;
	esac
	shift
done

target=${target#:}
INSTALL="/gentoo/prefix64/usr/bin/install -c"
echo ${INSTALL} -m 644 "${args[@]}"
if [[ ! -d ${target} ]] ; then
	# either install will die, or it was just a single file copy
	${INSTALL} -m 644 "${args[@]}" && sed -i "${sedexp[@]}" "${target}"
else
	${INSTALL} -m 644 "${args[@]}" && sed -i "${sedexp[@]}" "${sources[@]/#/${target}/}"
fi
