#!/usr/bin/env pkgcore-ebuild-helper

shopt -s extdebug extglob

if ! ${PKGCORE_PREFIX_SUPPORT:=false}; then
	ED=${D}
elif [[ ${ED:-unset} == "unset" ]]; then
	__helper_exit -1 "The variable ED is missing from the environment, but is required for prefix mode; failing."
fi

dir=${ED}/usr/share/doc/${PF}

[[ ! -d ${dir} ]] && return

z=$(find "${dir}" \
	'(' -type f -or -type l ')' \
	-not -name '*.gz' \
	-not -name '*.bz2' \
	-not -name '*.xz' \
	-not -name '*.Z' \
	-not -name '*.js' \
	-not -path "${ED}/usr/share/doc/${PF}/html/*" \
	-print \
	2>/dev/null)

[[ -z ${z} ]] && return

if [[ -z ${PORTAGE_COMPRESS_SUFFIX} ]]; then
	case ${PORTAGE_COMPRESS} in
		gzip)  suffix="gz";;
		bzip2) suffix="bz2";;
		xz)    suffix="xz";;
		(p?)zstd suffix="zst";;
		*)     die "prepalldocs error: please set PORTAGE_COMPRESS_SUFFIX in make.conf";;
	esac
fi

IFS=$'\n'
echo "doc: ${PORTAGE_COMPRESS} ${PORTAGE_COMPRESS_FLAGS}"
for y in ${z}; do
	if [[ -L ${y} ]]; then
		# Symlink ...
		mylink=${y}
		linkto=$(readlink "${y}")

		if [[ ${linkto##*.} != ${suffix} ]]; then
			linkto=${linkto}.${suffix}
		fi
		if [[ ${mylink##*.} != ${suffix} ]]; then
			mylink=${mylink}.${suffix}
		fi

		echo "  link fixed ${mylink##*/}"
		ln -snf "${linkto}" "${mylink}"
		if [[ ${y} != ${mylink} ]]; then
			echo "  link removed ${y##*/}"
			rm -f "${y}"
		fi
	else
		if [[ ${y##*.} != ${suffix} ]]; then
			echo "  compressing ${y##*/}" >&2
			"${PORTAGE_COMPRESS}" ${PORTAGE_COMPRESS_FLAGS} -f "${y}"
		fi
	fi
done

:
