#!/bin/sh

PATH=/bin:/usr/bin:/usr/local/bin
umask 022

checkdir()
{
    dir=$1

    if [ -d $dir ]; then
	if [ ! -w $dir ]; then
	    echo "$basename: directory $dir is not writeable."
	    exit 1
	fi
    else
	mkdir $dir || exit 1
    fi
}

basename=`basename $0`

if [ $# -lt 2 ] || [ $# -gt 3 ]; then
    echo "usage: $basename mandir formatter suffix"
    echo "example: $basename /usr/man/ja_JP.ujis gzip .gz"
    exit 1
fi

mandir=$1
formatter=$2
suffix=$3

checkdir $mandir

for src in *.man; do
    dst=`echo $src | sed 's/\.man//'`
    sec=`echo $dst | sed 's/.*\.//g'`

    dst_dir=$mandir/man$sec
    dst_path=$dst_dir/$dst$suffix
    checkdir $dst_dir

    echo "$src -> $dst_path"
    rm -f $dst_path
    cat $src | $formatter > $dst_path
done

exit 0
