#!/bin/bash

COMPRESSOR=xz
COMPRESS_EXT=.xz

echo "Compressing man pages..."

BUILDROOT=${1}
shift

dir="${BUILDROOT}/usr/share/man"

for file in $(find ${dir} -type f 2>/dev/null); do
	[ -f "${file}" ] || continue

	case "${file}" in
		*.gz)
			gzip -d ${file}
			file=${file%*.gz}
			;;
		*.bz2)
			bzip2 -d ${file}
			file=${file%*.bz2}
			;;
	esac

	echo "  Compressing man page ${file//${BUILDROOT}/}..."
	${COMPRESSOR} ${file} </dev/null 2>/dev/null || {
		# Handle files with hardlinks.
		others=$(find ${dir} -type f -samefile ${file})
		if [ -n "${others}" ]; then
			for afile in ${others}; do
				[ "${afile}" != "${file}" ] && rm -f ${afile}
			done
			${COMPRESSOR} -f ${file}
			for afile in ${others}; do
				[ "${afile}" != "${file}" ] && ln ${file}${COMPRESS_EXT} ${afile}${COMPRESS_EXT}
			done
		else
	                ${COMPRESSOR} -f ${file}
		fi
	}
done

for file in $(find ${dir} -type l 2>/dev/null); do
	link=$(ls -l ${file} | sed -e 's/.* -> //' -e 's/\.\(gz\|Z\|bz2\|xz\|lzma\)$//')
	rm -f ${file}
	b=$(echo ${file} | sed -e 's/\.\(gz\|Z\|bz2\|xz\|lzma\)$//')
	ln -sf ${link}${COMPRESS_EXT} ${b}${COMPRESS_EXT}
done

exit 0
