#!/bin/sh

GROUP=
MODE=
OWNER=
PAGE=
MANDIR=

doit="${DOITPROG-}"
INSTALL="${INSTALLPROG-install -c}"
ECHO="${ECHOPROG-echo}"

DIR=
SHOW=

while [ "x$1" != "x" ]; do
	case $1 in
		-g|--group)
			GROUP="$2";
			shift;
			shift;
			continue;;
		
		-m|--mode)
			MODE="$2";
			shift;
			shift;
			continue;;
		
		-o|--owner)
			OWNER="$2";
			shift;
			shift;
			continue;;
			
		-n)
			SHOW="name";
			shift;
			continue;;
			
		-d)
			SHOW="dir";
			shift;
			continue;;
			
		*)
			if [ "x$PAGE" = "x" ]; then
				PAGE="$1";
			elif [ "x$MANDIR" = "x" ]; then
				MANDIR="$1";
			else
				echo "$0: too many parameters"
				echo "usage: $0 [OPTIONS] PAGE MANDIR"
				echo
				echo "OPTIONS:"
				echo
				echo "  -m|--mode MODE     set permission mode"
				echo "  -g|--group GROUP   set group ownership"
				echo "  -o|--owner OWNER   set ownership"
				echo "  -n                 output the name of the installed file"
				echo
				echo "  Install a man page in the correct directory"
				echo "  adding the suffix to the MANDIR given taking"
				echo "  it from the extension of the PAGE."
				exit 1;
			fi
			shift;
			continue;;
	esac
done

if [ "x$GROUP" != "x" ]; then
	GROUP_OPTION="-g $GROUP";
else
	GROUP_OPTION="";
fi

if [ "x$MODE" != "x" ]; then
	MODE_OPTION="-m $MODE";
else
	MODE_OPTION="";
fi

if [ "x$OWNER" != "x" ]; then
	OWNER_OPTION="-o $OWNER";
else
	OWNER_OPTION="";
fi

if [ "x$PAGE" = "x" ]; then
	echo "$0: missing PAGE parameter"
	echo "usage: $0 [OPTIONS] PAGE MANDIR"
	echo
	echo "OPTIONS:"
	echo
	echo "  -m|--mode MODE     set permission mode"
	echo "  -g|--group GROUP   set group ownership"
	echo "  -o|--owner OWNER   set ownership"
	echo "  -n                 output the name of the installed file"
	echo
	echo "  Install a man page in the correct directory"
	echo "  adding the suffix to the MANDIR given taking"
	echo "  it from the extension of the PAGE."
	exit 1;
fi

if [ "x$MANDIR" = "x" ]; then
	echo "$0: missing MANDIR parameter"
	echo "usage: $0 [OPTIONS] PAGE MANDIR"
	echo
	echo "OPTIONS:"
	echo
	echo "  -m|--mode MODE     set permission mode"
	echo "  -g|--group GROUP   set group ownership"
	echo "  -o|--owner OWNER   set ownership"
	echo "  -n                 output the name of the installed file"
	echo
	echo "  Install a man page in the correct directory"
	echo "  adding the suffix to the MANDIR given taking"
	echo "  it from the extension of the PAGE."
	exit 1;
fi

DIR=$MANDIR/man`echo ${PAGE##*.} | head -c 1`;

if [ "$SHOW" = "name" ]; then
	$doit $ECHO $DIR/$PAGE
elif [ "$SHOW" = "dir" ]; then
	$doit $ECHO $DIR
else
	$doit $INSTALL $MODE_OPTION $OWNER_OPTION $GROUP_OPTION $PAGE $DIR
fi
