#!/usr/bin/env bash
# Copyright 1999-2018 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

source "${PORTAGE_BIN_PATH:?}"/isolated-functions.sh || exit

if [[ $# -lt 1 ]] ; then
	__helpers_die "${0##*/}: at least one argument needed"
	exit 1
fi

if ! ___eapi_has_prefix_variables; then
	ED=${D}
fi

i18n=""

ret=0

for x in "$@" ; do
	if [[ ${x:0:6} == "-i18n=" ]] ; then
		i18n=${x:6}/
		continue
	fi

	if [[ ${x:0:6} == ".keep_" ]] ; then
		continue
	fi

	suffix=${x##*.}

	# These will be automatically decompressed by ecompressdir.
	if [[ ${suffix} == @(Z|gz|bz2) ]]; then
		eqawarn "QA Notice: doman argument '${x}' is compressed, this is not portable"
		realname=${x%.*}
		suffix=${realname##*.}
	fi

	if [[ ${EAPI} == [23] ]] || [[ -z ${i18n} ]] && [[ ${EAPI:-0} != [01] ]] && [[ ${x} =~ (.*)\.([a-z][a-z](_[A-Z][A-Z])?)\.(.*) ]]
	then
		name=${BASH_REMATCH[1]##*/}.${BASH_REMATCH[4]}
		mandir=${BASH_REMATCH[2]}/man${suffix:0:1}
	else
		name=${x##*/}
		mandir=${i18n#/}man${suffix:0:1}
	fi


	if [[ ${mandir} == *man[0-9n] ]] ; then
		if [[ -s ${x} ]] ; then
			if [[ ! -d ${ED%/}/usr/share/man/${mandir} ]] ; then
				install -d "${ED%/}/usr/share/man/${mandir}"
			fi

			install -m0644 "${x}" "${ED%/}/usr/share/man/${mandir}/${name}"
			((ret|=$?))
		elif [[ ! -e ${x} ]] ; then
			echo "!!! ${0##*/}: ${x} does not exist" 1>&2
			((ret|=1))
		fi
	else
		__vecho "doman: '${x}' is probably not a man page; skipping" 1>&2
		((ret|=1))
	fi
done

[[ ${ret} -ne 0 ]] && __helpers_die "${0##*/} failed"
exit ${ret}
