#!/bin/sh
# Emulate nroff with groff.

prog="$0"
opts=

# `for i; do' doesn't work with some versions of sh

for i
  do
  case $1 in
    -c)
      opts="$opts -P-c" ;;
    -h)
      opts="$opts -P-h" ;;
    -[eq] | -s*)
      # ignore these options
      ;;
    -[dmrnoT])
      echo "$prog: option $1 requires an argument" >&2
      exit 1 ;;
    -[iptSUC] | -[dmrno]*)
      opts="$opts $1" ;;
#    -Tascii | -Tlatin1 | -Tutf8 | -Tcp1047)
#      T=$1 ;;
    -T*)
      # ignore other devices
      ;;
    -u*)
      # Solaris 2.2 through at least Solaris 9 `man' invokes
      # `nroff -u0 ... | col -x'.  Ignore the -u0,
      # since `less' and `more' can use the emboldening info.
      # However, disable SGR, since Solaris `col' mishandles it.
      opts="$opts -P-c" ;;
    -v | --version)
      echo "GNU nroff (groff) version 1.19.1"
      exit 0 ;;
    --help)
      echo "usage: nroff [-CchipStUv] [-dCS] [-mNAME] [-nNUM] [-oLIST] [-rCN]"
      echo "       [-Tname] [FILE...]"
      exit 0 ;;
    --)
      shift
      break ;;
    -)
      break ;;
    -*)
      echo "$prog: invalid option $1" >&2
      exit 1 ;;
    *)
      break ;;
  esac
  shift
done

# copy the man page to a temp file
TMPFILE=$(mktemp /tmp/man.XXXXXX)
trap "rm -f $TMPFILE" 0 1 2 3 15
cat ${1+"$@"} >| ${TMPFILE}

# test the charset encoding of the man page
if iconv -f utf-8 -t utf-8 -o /dev/null ${TMPFILE} 2>/dev/null
then
  charset_in=utf-8
else
  # non utf-8 encoding
  case "${LANGUAGE-${LC_CTYPE-${LANG}}}" in
    cs*|hr*|hu*|pl*|ro*|sk*|sl*) charset_in=iso-8859-2 ;;
    el*) charset_in=iso-8859-7 ;;
    tr*) charset_in=iso-8859-9 ;;
    bg*) charset_in=cp1251 ;;
    ja*) charset_in=euc-jp ;;
    ko*) charset_in=euc-kr ;;
    ru*) charset_in=koi8-r ;;
    uk*) charset_in=koi8-u ;;
    zh_TW*|zh_HK*) charset_in=big5 ;;
    zh_CN*|zh*) charset_in=gb2312 ;;
    *) charset_in=iso-8859-1 ;;
  esac
fi
charset_out=`locale charmap 2>/dev/null`

# Set up the `GROFF_BIN_PATH' variable
# to be exported in the current `GROFF_RUNTIME' environment.

GROFF_RUNTIME="${GROFF_BIN_PATH=/usr/bin}:"
export GROFF_BIN_PATH

# This shell script is intended for use with man, so warnings are
# probably not wanted.  Also load nroff-style character definitions.

/usr/bin/iconv -f ${charset_in} -t ${charset_out}//translit ${TMPFILE} | \
    PATH="$GROFF_RUNTIME$PATH" groff -mtty-char -Tutf8 $opts 2>/dev/null | \
    /usr/bin/iconv -f utf-8 -t ${charset_out}//translit

rm -f ${TMPFILE}

# eof
