#!/bin/sh
shout() { echo "$0: $@" >&2; }
barf() { shout "fatal: $@"; exit 111; }
safe() { "$@" || barf "cannot $@"; }

unix=`uname -a | cut -d' ' -f1 | tr [a-z] [A-Z]`
mandoc=`echo $unix | grep BSD | grep -ic open`
if [ $mandoc -eq 0 ] 
then
  mandoc=`echo $unix | grep -ic sun`
fi

safe umask 022
[ -d man ] || barf "no man directory"

mandir=""
if [ -f conf-man ]
then
   mandir=`head -1 conf-man`
   if [ -d "$mandir" ]
   then
     shout "Setting manual man-dir: $mandir."
   else
     mandir=`manpath | awk -F: '{print $1}'`
     if [ -d "$mandir" ]
     then
       shout "Setting manpath man-dir: $mandir."
     else
       barf "can't determine man-path directory."
     fi
  fi
fi

mgroup=`grep -v '#' conf-ids | head -1 | awk -F: '{print $2}'`
shout "Setting man group owernership: $mgroup"

cd man
if [ $mandoc -eq 1 ]
then
  safe make -f Makefile.mandoc
else
  safe make 
fi

if [ $mandoc -eq 0 ]
then
  shout "Installing s/qmail compressed man-files in ${mandir}."
else
  shout "Installing s/qmail un-compressed man-files in ${mandir}."
fi

for i in `find . -name "*[1-8]"`
do
  all="$all $i"
done

for manfile in $all
do
  dir="man`echo $manfile | awk -F. '{print $NF}'`"
  [ -d $mandir/$dir ] || safe mkdir $mandir/$dir
  if [ $mandoc -eq 0 ]
  then
    safe gzip $manfile && \
         install -m 644 -g $mgroup "$manfile.gz" $mandir/$dir/"${manfile#*/}.gz"
  else
    safe install -m 644 -g $mgroup $manfile $mandir/$dir/$manfile
  fi
done

## nroff: Required for old catman systems only 

if [ $mandoc -eq 0 ]
then
  shout "Installing s/qmail nroff'ed man-files in ${mandir}/catX."

  all=""
  for i in `find . -name "*0"`
  do
    all="$all $i"
  done

  for manfile in $all
  do
    catname=${manfile%.0}
    catfiles=`ls -1 ${catname}* | grep -v '.0' | grep -v '.9'`

    for catfile in $catfiles
    do
      dir="$mandir/cat`echo $catfile | awk -F. '{print $(NF-1)}'`"
      safe mkdir -p $dir
      safe install -m 644 -g $mgroup $manfile $dir/${manfile#*/}
    done
  done
else
  shout "Installing s/qmail mandoc files in db."
  makewhatis $mandir
  exit 0
fi

cd ..

exit 0
