#!/bin/bash
# Copyright 1999-2007 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id: prepalldocs 3483 2006-06-10 21:40:40Z genone $

source "${PORTAGE_BIN_PATH:-/usr/lib/portage/bin}"/isolated-functions.sh

if [[ -z $1 ]] ; then
	vecho "${0##*/}: at least one argument needed" 1>&2
	exit 1
fi

# figure out the new suffix
suffix=$(ecompress --suffix)

# funk_up_dir(action, suffix, binary)
#	- action: compress or decompress
#	- suffix: the compression suffix to work with
#	- binary: the program to execute that'll compress/decompress
# The directory we act on is implied in the ${dir} variable
funk_up_dir() {
	local act=$1 suffix=$2 binary=$3

	local negate=""
	[[ ${act} == "compress" ]] && negate="!"

	# first we act on all the files
	find "${dir}" -type f ${negate} -iname '*'${suffix} -print0 | ${XARGS} -0 ${binary}
	((ret+=$?))

	find "${dir}" -type l -print0 | \
	while read -d $'\0' brokenlink ; do
		[[ -e ${brokenlink} ]] && continue
		olddest=$(readlink "${brokenlink}")
		[[ ${act} == "compress" ]] \
			&& newdest="${olddest}${suffix}" \
			|| newdest="${olddest%${suffix}}"
		rm -f "${brokenlink}"
		[[ ${act} == "compress" ]] \
			&& ln -snf "${newdest}" "${brokenlink}${suffix}" \
			|| ln -snf "${newdest}" "${brokenlink%${suffix}}"
		((ret+=$?))
	done
}

ret=0

for dir in "$@" ; do
	dir=${dir#/}
	dir="${D}${dir}"
	if [[ ! -d ${dir} ]] ; then
		vecho "${0##*/}: /${dir#${D}} does not exist!"
		continue
	fi
	cd "${dir}"
	actual_dir=${dir}
	dir=. # use relative path to avoid 'Argument list too long' errors

	# not uncommon for packages to compress doc files themselves
	funk_up_dir "decompress" ".Z" "gunzip -f"
	funk_up_dir "decompress" ".gz" "gunzip -f"
	funk_up_dir "decompress" ".bz2" "bunzip2 -f"

	# forcibly break all hard links as some compressors whine about it
	find "${dir}" -type f -links +1 -exec env file="{}" sh -c \
		'cp -p "${file}" "${file}.ecompress.break" ; mv -f "${file}.ecompress.break" "${file}"' \;

	# now lets do our work
	[[ -z ${suffix} ]] && continue
	vecho "${0##*/}: $(ecompress --bin) /${actual_dir#${D}}"
	funk_up_dir "compress" "${suffix}" "ecompress"
done

exit ${ret}
