#!/bin/sh
#
# Compress documentation files found in $DOCDIR. Omit some files we don't
# want to get compressed.
#
# /etc/rpm/noautocompressdoc and --noautocompressdoc= option can contain
# whitespace delimated list of patters to omit.
#

#set -x

COMPRESS_CMD="gzip -9nf"
EXCLUDE_SUFFIXES="htm html jpg jpeg png gif pdf css dia js abw HTM JPG PNG GIF PDF CSS JS"
EXCLUDE_MASKS=
RECOMPRESS_BZIP2=yes

nocompressdoc=''
while [ $# -gt 0 ]; do
	case "$1" in
	  --noautocompressdoc=*)
		EXCLUDE_MASKS=`echo "${1#--noautocompressdoc=}" | sed -e 's/^ *//;s/ *$//;s/ \+/|/g'`
	esac
	shift
done

if [ -r /etc/rpm/noautocompressdoc ]; then
	exclude=$(cat /etc/rpm/noautocompressdoc | grep -v '^#' | xargs echo | sed -e 's/^ *//;s/ *$//;s/ \+/|/g')
	if [ -n "${exclude}" ]; then
		if [ -n "${EXCLUDE_MASKS}" ]; then
			EXCLUDE_MASKS="${EXCLUDE_MASKS}|${exclude}"
		else
			EXCLUDE_MASKS="${exclude}"
		fi
	fi
fi

if [ "$DOCDIR" = "" ] ; then
	echo '$DOCDIR not set; exiting.'
	exit 1
fi

cd $DOCDIR

echo "Compressing documentation in $DOCDIR..."

if test "$EXCLUDE_MASKS" ; then
	echo "Excluding pattern '$EXCLUDE_MASKS'"
fi

FIND_CMD="find . -type f "
for SUF in $EXCLUDE_SUFFIXES ; do
	FIND_CMD="$FIND_CMD -a -not -name '*.$SUF'"
done

eval $FIND_CMD | while read FILENAME ; do
	if test -n "$EXCLUDE_MASKS" ; then
		if eval "case \$(basename \"$FILENAME\") in
			 $EXCLUDE_MASKS ) true ;;
			 * ) false ;;
			 esac" ; then
			continue
		fi
	fi
	case "$FILENAME" in
	*.gz | *.Z)
		gzip -d "$FILENAME"
		FILENAME=$(echo "$FILENAME" | sed -e 's/\.gz$//; s/\.Z$//')
		;;
	*.bz2)
		if [ "$RECOMPRESS_BZIP2" = yes ] ; then
			bzip2 -d "$FILENAME"
			FILENAME=$(echo "$FILENAME" | sed -e 's/\.bz2$//')
		else
			continue
		fi
		;;
	esac

	$COMPRESS_CMD "$FILENAME"

	echo -n "$FILENAME "
done

echo
echo "Documentation compressed."
