#!/bin/sh -e

# TeXConfig version 3.0
# Originally written by Thomas Esser. Public domain.
# Now maintained as part of TeX Live; correspondence to tex-live@tug.org.

# invoke the right shell:

test -f /bin/ksh && test -z "$RUNNING_KSH" \
  && { UNAMES=`uname -s`; test "x$UNAMES" = xULTRIX; } 2>/dev/null \
  && { RUNNING_KSH=true; export RUNNING_KSH; exec /bin/ksh $0 ${1+"$@"}; }
unset RUNNING_KSH

test -f /bin/bsh && test -z "$RUNNING_BSH" \
  && { UNAMES=`uname -s`; test "x$UNAMES" = xAIX; } 2>/dev/null \
  && { RUNNING_BSH=true; export RUNNING_BSH; exec /bin/bsh $0 ${1+"$@"}; }
unset RUNNING_BSH

export PATH

# hack around a bug in zsh:
test -n "${ZSH_VERSION+set}" && alias -g '${1+"$@"}'='"$@"'

# initializations...
progname=texconfig

# the version string
version=20080708.1050plus_paperconf
# paperconf additions by Frank Kster 2010, Public Domain:
# You may freely copy, distribute and/or modify any part of the patch

envVars="
  AFMFONTS BIBINPUTS BSTINPUTS CMAPFONTS CWEBINPUTS ENCFONTS GFFONTS
  GLYPHFONTS INDEXSTYLE LIGFONTS MFBASES MFINPUTS MFPOOL MFTINPUTS
  MISCFONTS MPINPUTS MPMEMS MPPOOL MPSUPPORT OCPINPUTS OFMFONTS
  OPENTYPEFONTS OPLFONTS OTPINPUTS OVFFONTS OVPFONTS PDFTEXCONFIG PKFONTS
  PSHEADERS SFDFONTS T1FONTS T1INPUTS T42FONTS TEXBIB TEXCONFIG TEXDOCS
  TEXFONTMAPS TEXFONTS TEXFORMATS TEXINDEXSTYLE TEXINPUTS TEXMFCNF
  TEXMFDBS TEXMFINI TEXMFSCRIPTS TEXPICTS TEXPKS TEXPOOL TEXPSHEADERS
  TEXSOURCES TFMFONTS TRFONTS TTFONTS VFFONTS WEB2C WEBINPUTS
"
tmpdir=${TMPDIR-${TEMP-${TMP-/tmp}}}/tctmp.$$
needsCleanup=false
lastUpdatedFile=

# needed for set -e and replacing the various checks for $?
retval=0

# 
###############################################################################
# setupFMT(void) - find a suitable version of fmt / adjust
#
setupFMT()
{
  case $FMT in
    "") 
      FMT=fmt
      test ! -x /bin/fmt && test ! -f /usr/bin/fmt &&
        { test -x /bin/adjust || test -x /usr/bin/adjust; } && FMT=adjust
      ;;
    *)
      return
      ;;
  esac
}

###############################################################################
# myFmt(args) - run $FMT
#
myFmt()
{
  setupFMT
  $FMT ${1+"$@"}
}

###############################################################################
# echoShowVariable(args ...)
#   show environment variables which names are as args and their values
#
echoShowVariable()
{
  for esv
  do
    var=$esv
    eval val=\"\${$var+=}\${$var- is unset}\"
    echo "$var$val"
  done | grep -v 'is unset$'
}

###############################################################################
# echoShowKpseVariable(args ...)
#   show kpathsea variables which names are as args and their values
#
echoShowKpseVariable()
{
  for eskv
  do
    var=$eskv
    val=`kpsewhich -var-value="$eskv"`
    echo "$var=$val"
  done
}

###############################################################################
# echoLocateBinary(args ...) - show where programs actually exist
#
echoLocateBinary()
{
  for elb
  do
    elbLoc=`checkForBinary "$elb"`
    if test -n "$ELB_PATH_ONLY"; then
      test -n "$elbLoc" && echo "$elbLoc"
    else
      case $elbLoc in
        "") echo "$elb: not found";;
        *) echo "$elb: $elbLoc";;
      esac
    fi
  done
}

###############################################################################
# echoLocateCfgfile(args ...) - show where files actually exist
#
echoLocateCfgfile()
{
  for elc
  do
    case $elc in
      texmf.cnf) elcLoc=`kpsewhich $elc`;;
      *) elcLoc=`tcfmgr --cmd find --file "$elc"`;;
    esac
    case $elcLoc in
      "") echo "$elc: not found";;
      *)  echo "$elcLoc";;
    esac
  done
}

###############################################################################
# checkForBinary(prog) - echo full path of prog
#
checkForBinary()
{
  cfbBinary=$1

  OLDIFS=$IFS
  IFS=:
  set x `echo "$PATH" | sed 's/^:/.:/; s/:$/:./; s/::/:.:/g'`; shift
  found=false
  for pathElem
  do
    case $pathElem in
      "") continue;;
      *) test -f "$pathElem/$cfbBinary" && { echo "$pathElem/$cfbBinary"; found=true; break; }
    esac
  done
  IFS=$OLDIFS
  case $found in
    true) (exit 0); return 0;;
    false) (exit 1); return 1;;
  esac
}

###############################################################################
# cleanup() - clean up the temp area and exit with proper exit status
#
cleanup()
{
  rc=$1
  $needsCleanup && test -n "$tmpdir" && test -d "$tmpdir" \
    && { cd / && rm -rf "$tmpdir"; }
  (exit $rc); exit $rc
}

###############################################################################
# setupTmpDir() - set up a temp directory and a trap to remove it
#
setupTmpDir()
{
  case $needsCleanup in
    true) return;;
  esac

  trap 'cleanup 1' 1 2 3 7 13 15
  needsCleanup=true
  (umask 077; mkdir "$tmpdir") \
    || abort "could not create directory \`$tmpdir'"
}

###############################################################################
# setupTexmfmain() - get value for MT_TEXMFMAIN (with caching)
#
setupTexmfmain()
{
  case $MT_TEXMFMAIN in
    "") MT_TEXMFMAIN=`kpsewhich -var-value=TEXMFMAIN`;;
    *) return;;
  esac
}

###############################################################################
# setupTexmfmain() - get value for MT_TEXMFDIST (with caching)
#
setupTexmfdist()
{
  case $MT_TEXMFDIST in
    "") MT_TEXMFDIST=`kpsewhich -var-value=TEXMFDIST`;;
    *) return;;
  esac
}

###############################################################################
# setupTexmfvar() - get value for MT_TEXMFVAR (with caching)
#
setupTexmfvar()
{
  case $MT_TEXMVAR in
    "") MT_TEXMVAR=`kpsewhich -var-value=TEXMFVAR`;;
    *) return;;
  esac
}

###############################################################################
# setupSystexmf() - get value for MT_SYSTEXMF (with caching)
#
setupSystexmf()
{
  case $MT_SYSTEXMF in
    "") MT_SYSTEXMF=`kpsewhich -var-value=SYSTEXMF`;;
    *) return;;
  esac
}

###############################################################################
# abort(errmsg)
#   print `errmsg' to stderr and exit with error code 1
#
abort()
{
  echo "$progname: $1." >&2
  cleanup 1
}

###############################################################################
# mktexdir(args)
#   call mktexdir script, disable all features (to prevent sticky directories)
#
mktexdir()
{
  setupTexmfmain
  MT_FEATURES=none "$MT_TEXMFMAIN/web2c/mktexdir" "$@" >&2
}

###############################################################################
# tcfmgr(args) - call tcfmgr script
#
tcfmgr()
{
  setupTexmfmain
  "$MT_TEXMFMAIN/texconfig/tcfmgr" "$@"
}

###############################################################################
# mktexupd(args) - call mktexupd script
#
mktexupd()
{
  setupTexmfmain
  "$MT_TEXMFMAIN/web2c/mktexupd" "$@"
}

###############################################################################
# getRelDir(file)
#   matches file against SYSTEXMF. Returns relative directory of file within
#   a texmf tree in variable relPart.
#
getRelDir()
{
  file=$1
  relPart=

  setupSystexmf
  OLDIFS=$IFS
  IFS='
'
  set x `echo "$MT_SYSTEXMF" | tr : '
'`; shift
  IFS=$OLDIFS

  # now loop over all components of SYSTEXMF
  for dir
  do
    test -n "$dir" || continue
    case "$file" in
      $dir/*)
        relPart=`echo "$file" | sed "s%$dir/*%%"`
        break
        ;;
    esac
  done

  # now check for success / failure
  case $relPart in
    ""|$file)
      # empty or full filename -> getRelDir failed!
      (exit 1); return 1
      ;;
    *)
      # relPart should just have the "dirname" part:
      relPart=`echo "$relPart" | sed 's%/*[^/]*$%%'`
      (exit 0); return 0
      ;;
  esac
}

###############################################################################
# configReplace(file pattern line)
#   The first line in file that matches pattern gets replaced by line.
#   line will be added at the end of the file if pattern does not match.
#
configReplace()
{
  configReplaceFile=$1; configReplacePat=$2; configReplaceLine=$3

  if grep "$configReplacePat" "$configReplaceFile" >/dev/null; then
    ed "$configReplaceFile" >/dev/null 2>&1 <<-eof
	/$configReplacePat/c
	$configReplaceLine
	.
	w
	q
eof
  else
    echo "$configReplaceLine" >> $configReplaceFile
  fi
}

###############################################################################
# fmgrConfigShowPaper (file regex)
#   shows the paper setting in file, according to regex
#
fmgrConfigShow()
{
  fmgrConfigShowFile=`tcfmgr --cmd find --file $1`
  fmgrConfigShowRegex=$2

  sed -n "$fmgrConfigShowRegex" $fmgrConfigShowFile
}

###############################################################################
# fmgrConfigReplace (file regex value)
#   replaces line matching regex by value in file
#
fmgrConfigReplace()
{
  fmgrConfigReplaceChanged=false

  moreArgs=""
  use_ucf=false
  while
    case $1 in
      --ucf)
	use_ucf=true
	shift
	;;
      --*)
	moreArgs="$moreArgs $1 $2"
	shift; shift
	;;
      *) break;;
    esac
  do
    :
  done
  fmgrConfigReplaceFile=$1
  fmgrConfigReplaceRegex=$2
  fmgrConfigReplaceValue=$3

  setupTmpDir
  co=`tcfmgr $moreArgs --tmp $tmpdir --cmd co --file $fmgrConfigReplaceFile || retval=$?`
  if test $retval != 0; then
    echo "$progname: fmgrConfigReplace co failed for \`$fmgrConfigReplaceFile'" >&2
    (exit 1); return 1
  fi
  set x $co; shift
  fmgrConfigReplaceID=$1; fmgrConfigReplaceCfgFile=$3; fmgrConfigReplaceOrigFile=$4
  configReplace "$fmgrConfigReplaceCfgFile" "$fmgrConfigReplaceRegex" "$fmgrConfigReplaceValue"

  if [ $use_ucf = true ]; then
    # use ucf in Debian.  Since we just copied the file and made only
    # one change, there shouldn't be any need for prompting.  But since
    # texconfig might be called by a maintainer script with debconf
    # running, pass the option, if only to prevent it from nagging.
    if ! $(diff $fmgrConfigReplaceCfgFile $fmgrConfigReplaceOrigFile >/dev/null); then
      fmgrConfigReplaceChanged=true
    fi
    ucf --debconf-ok $fmgrConfigReplaceCfgFile $fmgrConfigReplaceOrigFile || retval=$?
    # here is a bug: We should somehow check whether the file had been
    # changed, in order to be able to recreate formats etc.
    if test $retval != 0; then
      echo "$progname: fmgrConfigReplace failed to call ucf for \`$fmgrConfigReplaceOrigFile'" >&2
      (exit 1); return 1
    fi
  else
    ci=`tcfmgr --tmp $tmpdir --cmd ci --id "$fmgrConfigReplaceID" || retval=$?`
    if test $retval != 0; then
      echo "$progname: fmgrConfigReplace ci failed for \`$fmgrConfigReplaceFile'" >&2
      (exit 1); return 1
    fi
      case $ci in
        "") :;;
        $lastUpdatedFile)
          fmgrConfigReplaceChanged=true;;
        *) echo "$progname: updated configuration saved as file \`$ci'" >&2
           fmgrConfigReplaceChanged=true
           lastUpdatedFile=$ci;;
      esac
      fi
  (exit 0); return 0
}

###############################################################################
# setupDvipsPaper(paper)
#   rearranges config.ps to make paper the first paper definition
#
setupDvipsPaper()
{
  setupDvipsPaperChanged=false
  setupDvipsPaperFile=config.ps
  setupDvipsPaperDftPaper=$1

  setupTmpDir
  co=`tcfmgr --tmp $tmpdir --cmd co --file $setupDvipsPaperFile || retval=$?`
  if test $retval != 0; then
    echo "$progname: setupDvipsPaper co failed for \`$setupDvipsPaperFile'" >&2
    (exit 1); return 1
  fi
  set x $co; shift
  setupDvipsPaperID=$1; setupDvipsPaperCfgFile=$3; setupDvipsPaperOrigFile=$4

  ed "$setupDvipsPaperCfgFile" > /dev/null 2>&1 <<-eof
	/@ /ka
	\$a
	@ 
	.
	/@ $setupDvipsPaperDftPaper /;/@ /-1m'a-1
	\$d
	w
	q
eof

  # use ucf in Debian.  Since we just copied the file and made only
  # one change, there shouldn't be any need for prompting.  But since
  # texconfig might be called by a maintainer script with debconf
  # running, pass the option, if only to prevent it from nagging.
  ucf --debconf-ok $setupDvipsPaperCfgFile $setupDvipsPaperOrigFile || retval=$?
  if test $retval != 0; then
    echo "$progname: fmgrConfigReplace failed to call ucf for \`$fmgrConfigReplaceOrigFile'" >&2
    (exit 1); return 1
  fi
  # ci=`tcfmgr --tmp $tmpdir --cmd ci --id "$fmgrConfigReplaceID"`
  # if test $? != 0; then
  #   echo "$progname: fmgrConfigReplace ci failed for \`$fmgrConfigReplaceFile'" >&2
  #   (exit 1); return 1
  # fi
  case $ci in
    "") :;;
    $lastUpdatedFile)
      setupDvipsPaperChanged=true;;
    *) echo "$progname: updated configuration saved as file \`$ci'" >&2
       setupDvipsPaperChanged=true
       lastUpdatedFile=$ci;;
  esac
  (exit 0); return 0
}

###############################################################################
# setupModesMfFile(void) - find modes.mf file (with caching)
#
setupModesMfFile()
{
  case $modesMfFile in
    "")
      modesMfFile=`tcfmgr --cmd find --file modes.mf`
      ;;
    *)
      return
      ;;
  esac
}

###############################################################################
# locateConfigPsFile(void) - find config.ps file (with caching)
#
locateConfigPsFile()
{
  case $configPsFile in
    "")
      configPsFile=`tcfmgr --cmd find --file config.ps`
      ;;
    *)
      return
      ;;
  esac
}

###############################################################################
# listMfModes(file) - list modes from modes.mf file
#
listMfModes()
{
  grep mode_def "$modesMfFile" |
  sed -e "s/mode_def //" \
      -e "s/ .*%[^ ]* / '/" \
      -e "s/\$/' /" |
  egrep -v "^(help|%)" | sort
}

###############################################################################
# listDvipsPapers(void) - list paper definitions from config.ps
#
listDvipsPapers()
{
  grep '@ ' $configPsFile | sed "s/..//;s/ / '/;s/\$/' /"
}

###############################################################################
# getFormatsForHyphen(void)
#   list all formats which have customizable hyphenation
#
getFormatsForHyphen()
{
  fmtutil --catcfg | awk '$3 != "-" {print $1}' | sort
}

###############################################################################
# getRes(mode) - print resolution (both X and Y axis) to metafont mode
#
getRes()
{
  getResMode=$1
  (
    cd $tmpdir
    cat >mftmp.mf <<-'eof'
	let myexit = primitive_end_;
	mode_setup;
	string xdpi;
	xdpi := decimal round pixels_per_inch;
	message "XDPI = " & xdpi;
	string ydpi;
	ydpi := decimal round (pixels_per_inch * aspect_ratio);
	message "YDPI = " & ydpi;
	fontmaking := 0;
	myexit;
eof
    mf '\mode='"$getResMode"';  \input ./mftmp' </dev/null \
     | awk '$1 == "XDPI" || $1 == "YDPI" { print $3 }'
  )
}

###############################################################################
# checkElemInList(elem, list)
#   check if element exists in list
###############################################################################
checkElemInList()
{
  checkElemInListElem=$1; shift
  checkElemInListFound=false
  for checkElemInListIter
  do
    case "x$checkElemInListElem" in
      x$checkElemInListIter)
        checkElemInListFound=true
        break
        ;;
    esac
  done
  case $checkElemInListFound in
    true) (exit 0); return 0;;
  esac
  (exit 1); return 1
}


# show version information from the distribution, if we have any.
showDistVersionInfo()
{
  # TeX Live file.
  test -f $MT_TEXMFMAIN/../release-texlive.txt \
  && sed 1q $MT_TEXMFMAIN/../release-texlive.txt

  # no harm in continuing to look for the teTeX files.
  test -f $MT_TEXMFMAIN/release-tetex-src.txt \
  && "teTeX-src release:   `cat $MT_TEXMFMAIN/release-tetex-src.txt`"
  test -f $MT_TEXMFDIST/release-tetex-texmf.txt \
  && "teTeX-texmf release: `cat $MT_TEXMFDIST/release-tetex-texmf.txt`"
}

# 
###############################################################################
# Main functions,
#   called from tcBatch with original positional parameters shifted by 1
###############################################################################

###############################################################################
# SizeToPaper
#   Convert paper dimensions to a unique paper name
###############################################################################
SizeToPaper()
{
  UsageSizeToPaper="Usage: texconfig size-to-paper height width"
  case $1 in
    "")
      echo $UsageSizeToPaper >&2
      ;;
    *)
      AskedHeight=$1
      AskedWidth=$2
      locateConfigPsFile
      papername=$(listDvipsPapers | \
	grep "$AskedWidth[[:space:]]*$AskedHeight" | \
	sed 's/[[:space:]].*//' \
	)
      if [ ! -n "$papername" ] || [ "$papername" = "unknown" ] || [ "$papername" = "nopaper" ]; then
	echo "No paper known with height $AskedHeight and width $AskedWidth"  >&2
	echo "Known units are mm and in, decimal separator is \`.'"
	echo "Maybe height and width have been exchanged?" >&2
	cleanup 1
      else
	if [ $(echo $papername | wc -w) -gt 1 ]; then
	  # filter out duplicates.  This command line shows duplicates in the current config.ps:
	  # ./texconfig dvips paper-list | \
	  #     sed 's/\([[:alnum:]]*\)[[:space:]]\(.*\)/\2 \1/' | \
	  #     sort | \
	  #     sed 's/\(.*\)[[:space:]]\([[:alnum:]]*\)/\2 \1/' | \
	  #     uniq -D -f 1
	  papernameList=$papername
	  papername=$(echo $papername | \
	    sed 's/11x17//;s/statement//;s/a4size//;s/letterSize//;s/flse//;s/[[:space:]]//g' \
	    )
	fi
	echo $papername
      fi
      ;;
  esac
}

###############################################################################
# PaperToSize
#   Convert paper name to dimensions, values taken from config.ps
###############################################################################
PaperToSize()
{
  UsagePaperToSize="Usage: texconfig paper-to-size [-m|--machine-readable] papername"
  sparseOutput=0
  case $1 in
    -m|--machine-readable)
      sparseOutput=1
      shift
      ;;
  esac
  case $1 in
    "")
      echo $UsagePaperToSize >&2
      ;;
    *)
      AskedPaper=$1
      locateConfigPsFile
      paperline=$(listDvipsPapers | grep "^$AskedPaper[[:space:]]")
      if [ ! -n "$paperline" ]; then
	echo "unknown paper size: $AskedPaper" >&2
	cleanup 1
      fi
      allowedUnitLetters="min"
      width=$(echo $paperline | sed \
	"s/.*['\'']\([[:digit:].]*[$allowedUnitLetters][$allowedUnitLetters]\).*/\1/" \
	)
      height=$(echo $paperline | sed \
	"s/.*[[:space:]]\([[:digit:].]*[$allowedUnitLetters][$allowedUnitLetters]\).$/\1/" \
	)
      if [ $sparseOutput = 1 ]; then
	echo $height $width
      else
	echo "Paper $AskedPaper has height $height and width $width"
      fi
      ;;
  esac

}

###############################################################################
# pdftexSetPaper
#   set paper for pdftex
###############################################################################
pdftexSetPaper()
{
  pdfPaperHelp="Usage: $progname pdftex paper PAPER"

  skipFormats=false
  pdfPaperName="$1"
  if [ -n "$2" ] && [ "$2" = "no-recreate-formats" ]; then skipFormats=true; fi

  if [ -z $pdfPaperName ]; then
    echo "$help" >&2
    rc=1
    return $rc
  fi

  pdfPaperDims=$(PaperToSize -m $pdfPaperName)
  PaperHeight=$(echo $pdfPaperDims | sed 's/ .*//') # keep value before blank
  PaperWidth=$( echo $pdfPaperDims | sed 's/.* //') # keep value after blank

  pdfPaperHeight=$(echo $PaperHeight | sed 's/mm/ true mm/;s/in/ true in/')
  pdfPaperWidth=$( echo $PaperWidth  | sed 's/mm/ true mm/;s/in/ true in/')

  setupTmpDir
  fmgrConfigReplace --ucf pdftexconfig.tex pdfpagewidth '\pdfpagewidth='"$pdfPaperWidth"
  wChanged=$fmgrConfigReplaceChanged
  if $wChanged; then
    # don't tell again about replacing pdftexconfig
    fmgrConfigReplace --ucf pdftexconfig.tex pdfpageheight '\pdfpageheight='"$pdfPaperHeight" 2>/dev/null
  else
    fmgrConfigReplace --ucf pdftexconfig.tex pdfpageheight '\pdfpageheight='"$pdfPaperHeight"
  fi
  if $skipFormats; then return 0; fi
  if $wChanged || $fmgrConfigReplaceChanged; then
    echo "pdftex paper size has changed, refreshing formats"
    fmtutil --byengine pdftex 2>&1 | grep "^fmtutil"
  fi
}

###############################################################################
# pdftexPaperConf
#   get paper for pdftex
###############################################################################
pdftexPaperConf(){
  pdftexconfig=`tcfmgr --cmd find --file pdftexconfig.tex`
  pdftexPaperWidth=$(sed -n '/^\\pdfpagewidth/ {s/^\\pdfpagewidth=//;s/ true //;p}' $pdftexconfig)
  pdftexPaperHeight=$(sed -n '/^\\pdfpageheight/ {s/^\\pdfpageheight=//;s/ true //;p}' $pdftexconfig)

  SizeToPaper $pdftexPaperHeight $pdftexPaperWidth
}

###############################################################################
# dvipdfmPaperConf
#   get paper for dvipdfm
###############################################################################
dvipdfmPaperConf(){
  fmgrConfigShow config '/^p/ {s/^p //;p}'
}

###############################################################################
# dvipdfmxPaperConf
#   get paper for dvipdfmx
###############################################################################
dvipdfmxPaperConf(){
  fmgrConfigShow dvipdfmx.cfg '/^p/ {s/^p[[:space:]]*//;p}'
}

###############################################################################
# dvipsPaperConf
#   get paper for dvips
###############################################################################
dvipsPaperConf(){
  locateConfigPsFile
  fmgrConfigShow config.ps '/^@ / {s/^@ \([^[:space:]]*\).*/\1/;p;q}'
}

###############################################################################
# XDviPaperConf
#   get paper for XDvi
###############################################################################
XDviPaperConf(){
  fmgrConfigShow XDvi '/^\*paper:/ {s/^\*paper: \([^[:space:]]*\).*/\1/;p;q}'
}

# 
###############################################################################
# tcBatch(args)
#   handle batch mode
###############################################################################
tcBatch()
{
  help="texconfig supports adjusting and updating many aspects of
the TeX installation.

Usage: $progname conf                  (show configuration information)
       $progname dvipdfmx paper PAPER  (dvipdfmx paper size)
       $progname dvipdfm paper PAPER   (dvipdfm paper size)
       $progname dvips [OPTION...]     (dvips options)
       $progname faq                   (show teTeX faq)
       $progname findprog PROG...      (show locations of PROGs, a la which)
       $progname font vardir DIR
       $progname font ro
       $progname font rw
       $progname formats               (edit fmtutil.cnf)
       $progname help                  (or --help; show this help)
       $progname hyphen FORMAT         (edit hyphenation config for FORMAT)
       $progname init [FORMAT]...      (rebuild FORMATs, or all formats
                                        plus run updmap)
       $progname mode MODE             (set Metafont MODE)
       $progname paper PAPER           (set default paper size to PAPER)
       $progname pdftex [OPTION]...    (pdftex options)
       $progname rehash                (rebuild ls-R files with mktexlsr)
       $progname version               (or --version; show version info)
       $progname xdvi paper PAPER      (xdvi paper size)

Get more help with:
       $progname dvipdfmx
       $progname dvipdfm
       $progname dvips
       $progname font
       $progname hyphen
       $progname mode
       $progname paper
       $progname pdftex
       $progname xdvi

See http://tug.org/texlive/ for other documentation, etc.
Report bugs to <tex-k@tug.org>."

  case $1 in
    # texconfig conf
    conf|confall)
      setupTexmfmain
      setupTexmfdist
      echo '=========================== version information =========================='
      showDistVersionInfo
      echo
      echo '==================== binaries found by searching $PATH ==================='
      echo "PATH=$PATH"
      echoLocateBinary kpsewhich updmap fmtutil texconfig tex pdftex mktexpk dvips dvipdfm
      echo
      echo '=========================== active config files =========================='
      echoLocateCfgfile texmf.cnf updmap.cfg fmtutil.cnf config.ps mktex.cnf XDvi pdftexconfig.tex config | sort -k 2
      echo
      echo '============================= font map files ============================='
      for m in psfonts.map pdftex.map ps2pk.map dvipdfm.map; do
        echo "$m: `kpsewhich $m`"
      done
      echo
      echo '=========================== kpathsea variables ==========================='
      echoShowKpseVariable TEXMFMAIN TEXMFDIST TEXMFLOCAL TEXMFSYSVAR TEXMFSYSCONFIG TEXMFVAR TEXMFCONFIG TEXMFHOME VARTEXFONTS TEXMF SYSTEXMF TEXMFDBS WEB2C TEXPSHEADERS TEXCONFIG ENCFONTS TEXFONTMAPS

      echo
      echo '==== kpathsea variables from environment only (ok if no output here) ===='
      echoShowVariable $envVars
      echo
      echo '========================== default paper sizes =========================='
      echo -n "dvipdfm: "
      dvipdfmPaperConf
      echo -n "dvipdfmx: "
      dvipdfmxPaperConf
      echo -n "dvips: "
      dvipsPaperConf
      echo -n "pdftex: "
      pdftexPaperConf
      echo -n "XDvi: "
      XDviPaperConf
      ;;

    # texconfig dvipdfm
    dvipdfm)
      help="Usage: $progname dvipdfm paper PAPER

Valid PAPER settings:
  letter legal ledger tabloid a4 a3"
      case $2 in
        # texconfig dvipdfm paper
        paper-list)
          for p in letter legal ledger tabloid a4 a3; do echo $p; done
          ;;
        paper)
          case $3 in
            letter|legal|ledger|tabloid|a4|a3)
              fmgrConfigReplace --ucf config '^p' "p $3";;
            "") echo "$help" >&2; rc=1;;
            *)
             echo "$progname: unknown PAPER \`$3' given as argument for \`$progname dvipdfm paper'" >&2
             echo "$progname: try \`$progname dvipdfm paper' for help" >&2
             rc=1 ;;
          esac ;;
	paperconf)
	  dvipdfmPaperConf
	  ;;
        # texconfig dvipdfm ""
        "")
          echo "$help" >&2; rc=1 ;;
        # texconfig dvipdfm <unknown>
        *)
          echo "$progname: unknown option \`$2' given as argument for \`$progname dvipdfm'" >&2
          echo "$progname: try \`$progname dvipdfm' for help" >&2
          rc=1
          ;;
      esac
      ;;

    # texconfig dvipdfmx
    dvipdfmx)
      help="Usage: $progname dvipdfmx paper PAPER

Valid PAPER settings:
  letter legal ledger tabloid a4 a3"
      case $2 in
        # texconfig dvipdfmx paper
        paper-list)
          for p in letter legal ledger tabloid a4 a3; do echo $p; done
          ;;
        paper)
          case $3 in
            letter|legal|ledger|tabloid|a4|a3)
              fmgrConfigReplace --ucf dvipdfmx.cfg '^p' "p $3";;
            "") echo "$help" >&2; rc=1;;
            *)
             echo "$progname: unknown PAPER \`$3' given as argument for \`$progname dvipdfmx paper'" >&2
             echo "$progname: try \`$progname dvipdfmx paper' for help" >&2
             rc=1 ;;
          esac ;;
        # texconfig dvipdfmx ""
	paperconf)
	  dvipdfmxPaperConf
	  ;;
        "")
          echo "$help" >&2; rc=1 ;;
        # texconfig dvipdfmx <unknown>
        *)
          echo "$progname: unknown option \`$2' given as argument for \`$progname dvipdfmx'" >&2
          echo "$progname: try \`$progname dvipdfmx' for help" >&2
          rc=1
          ;;
      esac
      ;;

    # texconfig dvips
    dvips)
      shift
      help="Usage: $progname dvips add PRINTER
       $progname dvips del PRINTER
       $progname dvips paper PAPER
       $progname dvips paper-list
       $progname dvips [-P PRINTER] mode MODE
       $progname dvips [-P PRINTER] offset OFFSET
       $progname dvips [-P PRINTER] printcmd CMD"
      case $1 in
        -P)
          case $2 in
            "")
              echo "$progname: missing arg for parameter -P" >&2
              rc=1; (exit $rc); return $rc
              ;;
            *)
              otherPrinter=true
              otherPrinterName=$2
              otherPrinterFile=`kpsewhich -format='dvips config' "config.$otherPrinterName"`
              case $otherPrinterFile in
                "")
                  echo "$progname: configuration file \`config.$otherPrinterName' for printer \`$otherPrinterName' not found" >&2
                  rc=1; (exit $rc); return $rc
                  ;;
                *) shift; shift;;
              esac
              ;;
          esac
          ;;
        *)
          otherPrinter=false
          ;;
      esac
      case $otherPrinter in
        true)
          tcBatchDvipsPrinter=$otherPrinterName
          moreFmgrArgs="--reldir dvips/config --infile $otherPrinterFile"
          ;;
        *)
          tcBatchDvipsPrinter=ps
          ;;
      esac
      case $1 in
        add)
          case $2 in
            "")
              echo "Usage: $progname dvips add PRINTER" >&2
              rc=1
              ;;
            *)
              printerName=$2
              pFile=`kpsewhich -format='dvips config' "config.$printerName"`
              case $pFile in
                "")
                  setupTmpDir
                  tcfRet=`tcfmgr --emptyinfile --reldir dvips/config --cmd co --tmp $tmpdir --file "config.$printerName" || retval=$?`
                  if test $retval != 0; then
                    echo "$progname: failed to add new configuration file \`config.$printerName'" >&2
                    rc=1
                  else
                    set x $tcfRet; shift
                    tcBatchDvipsAddID=$1; tcBatchDvipsAddFile=$3
                    echo "% file config.$printerName; added by texconfig" > "$tcBatchDvipsAddFile"
                    tcfRet=`tcfmgr --tmp $tmpdir --id "$tcBatchDvipsAddID" --cmd ci || retval=$?`
                    if test $retval != 0; then
                      echo "$progname: failed to add new configuration file \`config.$printerName'" >&2
                      rc=1
                    else
                      echo "$progname: file $tcfRet added" >&2
                    fi
                  fi
                  ;;
                *)
                  echo "$progname: configuration file for printer \`$printerName' already exists (\`$pFile')" >&2
                  rc=1
                  ;;
              esac
              ;;
          esac
          ;;
        del)
          case $2 in
            "")
              echo "Usage: $progname dvips del PRINTER" >&2
              rc=1
              ;;
            *)
              printerName=$2
              pFile=`kpsewhich -format='dvips config' "config.$printerName"`
              case $pFile in
                "")
                  echo "$progname: configuration file for printer \`$printerName' (config.$printerName) not found" >&2
                  rc=1
                  ;;
                *)
                  if rm "$pFile"; then
                    echo "$progname: file \`$pFile' removed" >&2
                  else
                    echo "$progname: failed to remove file \`$pFile'" >&2
                    rc=1
                  fi
                  ;;
              esac
              ;;  
          esac
          ;;
        paper-list)
          locateConfigPsFile
          listDvipsPapers
          ;;
        paper)
          case $2 in
            "")
              echo "Usage: $progname dvips paper PAPER" >&2
              echo >&2; echo "Valid PAPER settings:" >&2
              locateConfigPsFile
              listDvipsPapers | sed 's@ .*@@; s@^@  @' | myFmt
              rc=1
              ;;
            *)
              tcBatchDvipsPaper=$2
              locateConfigPsFile
              case "$configPsFile" in
                "")
                  echo "$progname: file config.ps not found" >&2; rc=1
                  ;;
                *)
                  if grep "@ $tcBatchDvipsPaper " $configPsFile >/dev/null 2>&1; then
                    setupDvipsPaper "$tcBatchDvipsPaper"
                  else
                    echo "$progname: paper \`$tcBatchDvipsPaper' not found in file \`$configPsFile'" >&2; rc=1
                  fi
                  ;;
              esac
              ;;
          esac
          ;;
	paperconf)
	  dvipsPaperConf
	  ;;
        mode)
          case $2 in
            "")
              echo "Usage: $progname dvips mode MODE

Valid MODE settings:"
              setupModesMfFile
              listMfModes | sed 's@ .*@@; s@^@  @' | myFmt
              rc=1
              ;;
            *)
              tcBatchDvipsMode=$2
              setupTmpDir
              setupModesMfFile
              if checkElemInList "$tcBatchDvipsMode" `listMfModes | sed 's@ .*@@'`; then
                set x `getRes "$tcBatchDvipsMode"`; shift
                resX=$1; resY=$2
                fmgrConfigReplace $moreFmgrArgs config.$tcBatchDvipsPrinter '^M' "M $tcBatchDvipsMode"
                fmgrConfigReplace $moreFmgrArgs config.$tcBatchDvipsPrinter '^D' "D $resX"
                fmgrConfigReplace $moreFmgrArgs config.$tcBatchDvipsPrinter '^X' "X $resX"
                fmgrConfigReplace $moreFmgrArgs config.$tcBatchDvipsPrinter '^Y' "Y $resY"
              else
                echo "$progname: unknown MODE \`$tcBatchDvipsMode' given as argument for \`$progname dvips mode'" >&2
                echo "$progname: try \`$progname dvips mode' for help" >&2
                rc=1
              fi
              ;;
          esac
          ;;
        offset)
          offset=$2
          case $offset in
            "")
              echo "Usage: $progname dvips offset OFFSET"
              rc=1
              ;;
            *)
              fmgrConfigReplace $moreFmgrArgs config.$tcBatchDvipsPrinter '^O' "O $offset"
          esac
          ;;
        printcmd)
          printcmd=$2
          case $printcmd in
            "")
              echo "Usage: $progname dvips printcmd CMD"
              rc=1
              ;;
            -)
              fmgrConfigReplace $moreFmgrArgs config.$tcBatchDvipsPrinter '^o' o
              ;;
            *)
              fmgrConfigReplace $moreFmgrArgs config.$tcBatchDvipsPrinter '^o' "o |$printcmd"
              ;;
          esac
          ;;
        "")
          echo "$help" >&2; rc=1
          ;;
        *)
          echo "$progname: unknown option \`$1' given as argument for \`$progname dvips'" >&2
          echo "$progname: try \`$progname dvips' for help" >&2
          rc=1
          ;;
      esac
      ;;

    faq)
      setupTexmfmain
      if test -f $MT_TEXMFDIST/doc/tetex/teTeX-FAQ.gz; then
        <$MT_TEXMFDIST/doc/tetex/teTeX-FAQ.gz eval zcat | ${PAGER-sensible-pager}
      else
        echo "$progname: faq not found (usually in \$TEXMFMAIN/doc/tetex/teTeX-FAQ)" >&2
        rc=1
      fi
      ;;

    findprog)
      shift
      ELB_PATH_ONLY=1 echoLocateBinary "$@"
      ;;

    # handle "texconfig font"
    font)
      help="Usage: $progname font vardir DIR
       $progname font ro
       $progname font rw

The vardir option changes the VARTEXFONTS variable in the texmf.cnf file.

The rw option makes the VARTEXFONTS directory (and subtrees pk, tfm,
source) world writable and sets the features appendonlydir:varfonts
in mktex.cnf.

The ro option makes the VARTEXFONTS directory (and subtrees pk, tfm,
source) writable for the owner only and sets the feature texmfvar in
mktex.cnf.

For more information about these \`features', consult the teTeX manual
(e.g. by running \`texdoc TETEXDOC')."

      case $2 in
        vardir)
          case $3 in
            "")
              echo "$help" >&2
              rc=1
              ;;
            *)
              tcBatchFontVardir=$3
	      tfcs=$(grep -l '^[[:space:]]*VARTEXFONTS[[:space:]]*=' /etc/texmf/texmf.d/*.cnf)
	      # last match wins
	      for file in $tfcs; do tfc=$file; done
              if test -n "$tfc"; then
                if test -w "$tfc"; then
                  configReplace "$tfc" '^VARTEXFONTS' "VARTEXFONTS  = $tcBatchFontVardir"
		  update-texmf
                else
                  echo "$progname: setting up vardir failed. Reason: no permission to write file \`$tfc'" >&2
                  rc=1
                fi
              else
                echo "$progname: setting up vardir failed. Reason: failed to find file \`$tfc'" >&2
                rc=1
              fi
              ;;
          esac
          ;;
        rw)
          MT_VARTEXFONTS=`kpsewhich -var-value VARTEXFONTS`
          if test -z "$MT_VARTEXFONTS"; then
            echo "$progname: failed to set \`font rw'; reason: could not determine VARTEXFONTS variable." >&2; rc=1
            return
          fi
          test -d "$MT_VARTEXFONTS" || mktexdir "$MT_VARTEXFONTS"
          if test ! -d "$MT_VARTEXFONTS"; then
            echo "$progname: failed to set \`font rw'; reason: directory \`$MT_VARTEXFONTS' does not exist." >&2; rc=1
            return
          fi
          chmod 1777 "$MT_VARTEXFONTS" || {
            echo "$progname: failed to modify permissions in \`$MT_VARTEXFONTS'." >&2; rc=1
            return;
          }
          (
            cd "$MT_VARTEXFONTS" || exit
            echo "$progname: modifying permissions in \`$MT_VARTEXFONTS' ..." >&2
            for d in pk tfm source; do
              test -d "$d" && find $d -type d -exec chmod 1777 '{}' \;
            done
            echo "$progname: all permissions set." >&2
          )
          setupTmpDir
          fmgrConfigReplace mktex.cnf '^: ..MT_FEATURES=' ": \${MT_FEATURES=appendonlydir:varfonts}"
          ;;
        ro)
          MT_VARTEXFONTS=`kpsewhich -var-value VARTEXFONTS`
          if test -z "$MT_VARTEXFONTS"; then
            echo "$progname: failed to set \`font ro'; reason: could not determine VARTEXFONTS variable." >&2; rc=1
            return
          fi
          test -d "$MT_VARTEXFONTS" || mktexdir "$MT_VARTEXFONTS"
          if test ! -d "$MT_VARTEXFONTS"; then
            echo "$progname: failed to set \`font ro'; reason: directory \`$MT_VARTEXFONTS' does not exist." >&2; rc=1
            return
          fi
          chmod 755 "$MT_VARTEXFONTS" || {
            echo "$progname: failed to modify permissions in \`$MT_VARTEXFONTS'." >&2; rc=1
            return;
          }
          (
            cd "$MT_VARTEXFONTS" || exit
            echo "$progname: modifying permissions in \`$MT_VARTEXFONTS' ..." >&2
            for d in pk tfm source; do
              test -d "$d" && find "$d" -type d -exec chmod 755 '{}' \;
            done
            echo "$progname: all permissions set." >&2
          )
          setupTmpDir
          fmgrConfigReplace mktex.cnf '^: ..MT_FEATURES=' ": \${MT_FEATURES=texmfvar}"
          ;;
        "") echo "$help" >&2; rc=1;;
        *) echo "$progname: unknown option \`$2' given as argument for \`$progname font'" >&2
           echo "$progname: try \`$progname font' for help" >&2
           rc=1
           ;;
      esac
      ;;

    formats)
      setupTmpDir
      echo "$progname: analyzing old configuration..." >&2
      fmtutil --catcfg > $tmpdir/pre
      fmtutil --edit
      echo "$progname: analyzing new configuration..." >&2
      fmtutil --catcfg > $tmpdir/post

      if cmp $tmpdir/pre $tmpdir/post >/dev/null 2>&1; then
        echo "$progname: no new/updated formats available ..." >&2
      else
      echo "$progname: updating formats ..." >&2
        comm -13 $tmpdir/pre $tmpdir/post > $tmpdir/addOrChange
        for i in `awk '{print $1}' $tmpdir/addOrChange`; do
          fmtutil --byfmt "$i" || rc=1
        done
      fi
      ;;

    help|--help|-h)
      echo "$help"
      ;;

    # "hyphen FORMAT"
    hyphen)
      tcBatchHyphenFormat=$2
      formatsForHyphen=`getFormatsForHyphen`
      formatsForHyphenFmt=`echo "$formatsForHyphen" | myFmt | sed 's@^@  @'`
      help="Usage: $progname hyphen FORMAT

Valid FORMATs are:
$formatsForHyphenFmt"
      case $tcBatchHyphenFormat in
        "")
          echo "$help" >&2; rc=1
          ;;
        *)
          if checkElemInList "$tcBatchHyphenFormat" $formatsForHyphen; then

            tcBatchHyphenFile=`fmtutil --showhyphen "$tcBatchHyphenFormat"`
            case $tcBatchHyphenFile in
              "")
                echo "$progname: could not find hyphen setup file for format \`$tcBatchHyphenFormat'" >&2
                rc=1
                return
                ;;
	      /var/lib/texmf/*)
		echo "$progname: The hyphenation file for $tcBatchHyphenFormat is a generated file in Debian"
		echo "You cannot use this texconfig command, use \`update-language(1)' instead."
		echo "Please read its manual page or /usr/share/tex-common/TeX-on-Debian*"
		;;
            esac

            getRelDir "$tcBatchHyphenFile"
            case $relPart in
              "")
                # edit tcBatchHyphenFile directly
                tcBatchHFID=
                setupTmpDir
                tcBatchHFEdit=$tcBatchHyphenFile
                tcBatchHFOrig=$tmpdir/hforig
                cp "$tcBatchHyphenFile" "$tcBatchHFOrig"
                ;;
              *)
                # use tcfmgr
                tcBatchHyphenFileBasename=`echo "$tcBatchHyphenFile" | sed 's@.*/@@'`
                setupTmpDir
                co=`tcfmgr --tmp $tmpdir --cmd co --file "$tcBatchHyphenFileBasename" --reldir "$relPart" --infile "$tcBatchHyphenFile" || retval=$?`
                if test $retval != 0; then
                  echo "$progname: failed to check out file \`$tcBatchHyphenFile'" >&2
                  rc=1
                  return 1
                else
                  set x $co; shift
                  tcBatchHFID=$1; tcBatchHFEdit=$3; tcBatchHFOrig=$4
                fi
                ;;
            esac
            ${VISUAL:-${EDITOR:-sensible-editor}} "$tcBatchHFEdit"
            if cmp "$tcBatchHFEdit" "$tcBatchHFOrig" >/dev/null 2>&1; then
              echo "$progname: configuration unchanged." >&2
            else
              case $tcBatchHFID in
                "")
                  tcBatchHFOut=$tcBatchHFEdit
                  echo "$progname: updated configuration saved as file \`$tcBatchHFOut'" >&2
                  lastUpdatedFile=$ci
                  ;;
                *)
                  ci=`tcfmgr --tmp $tmpdir --cmd ci --id "$tcBatchHFID" || retval=$?`
                  if test $retval != 0; then
                    echo "$progname: failed to check in file \`$tcBatchHyphenFileBasename'" >&2
                    rc=1
                    return
                  else
                    tcBatchHFOut=$ci
                    echo "$progname: updated configuration saved as file \`$tcBatchHFOut'" >&2
                    lastUpdatedFile=$ci
                  fi
                  ;;
              esac
              fmtutil --byhyphen "$tcBatchHFOut"
            fi
          else
            echo "$progname: invalid format \`$tcBatchHyphenFormat' specified as argument for \`$progname hyphen'" >&2
            echo "$progname: for getting help, try \`$progname hyphen'" >&2
            rc=1
          fi
          ;;
      esac
      ;;

    hyphen-list)
      getFormatsForHyphen
      ;;

    init)
      if test -n "$texconfig_sys"; then  # set by texconfig-sys
        fmtutil=fmtutil-sys
        updmap=updmap-sys
      else
        fmtutil=fmtutil
        updmap=updmap
      fi
      
      case $2 in
        "")
          if $fmtutil --all \
             && $updmap; then
            :
          else
            rc=1
          fi
          ;;
        *)
          shift 1
          for i in "$@"; do
            $fmtutil --byfmt "$i" || rc=1
          done
          ;;
      esac
      ;;

    mode-list)
      setupModesMfFile
      listMfModes
      ;;

    mode)
      case $2 in
        "")
          echo "Usage: $progname mode MODE

Valid MODE settings:"
          setupModesMfFile
          listMfModes | sed 's@ .*@@; s@^@  @' | myFmt
          rc=1
          ;;
        *)
          tcBatchMode=$2
          setupModesMfFile
          if checkElemInList $tcBatchMode `listMfModes | sed 's@ .*@@'`; then

            # modify mktex.cnf
            setupTmpDir
            fmgrConfigReplace mktex.cnf '^: ..MODE=' ": \${MODE=$tcBatchMode}"
            set x `getRes "$tcBatchMode"`; shift
            tcBatchRes=$1
            fmgrConfigReplace mktex.cnf '^: ..BDPI=' ": \${BDPI=$tcBatchRes}"

            if checkForBinary dvips >/dev/null && tcfmgr --cmd find --file config.ps >/dev/null 2>&1; then
              tcBatch dvips mode "$tcBatchMode"
            fi
            if checkForBinary pdftex >/dev/null && tcfmgr --cmd find --file pdftexconfig.tex >/dev/null 2>&1; then
              tcBatch pdftex mode "$tcBatchMode"
            fi
          else
            echo "$progname: unknown mode \`$tcBatchMode' specified as argument for \`$progname mode'" >&2; rc=1
          fi
          ;;
      esac
      ;;

    paper)
      help="Usage: $progname paper PAPER

Valid PAPER settings:
  a0 a1 a10 a2 a3 a4 a5 a6 a7 a8 a9 b0 b1 b2 b3 b4 b5 b6 c5 ledger legal letter tabloid"

      p=$2
      case $2 in
	a0|a1|a10|a2|a3|a4|a5|a6|a7|a8|a9|b0|b1|b2|b3|b4|b5|b6|c5|ledger|legal|letter|tabloid)
	  # handled by xdvi and dvips (and hence all others)
	  :
	  ;;
        "") echo "$help" >&2; rc=1; return;;
        *)
          echo "$progname: PAPER \`$2' is not understood by all programs." >&2
          echo "$progname: try \`$progname paper' for help" >&2
	  echo "           or use \`$progname PROGNAME paper $2' instead " >&2
	  echo "           for the programs you need." >&2
          rc=1
          return;;
      esac
      if checkForBinary dvips >/dev/null && tcfmgr --cmd find --file config.ps >/dev/null 2>&1; then
        tcBatch dvips paper $p
      fi
      # dvipdfm is now only a symlink to dvipdfmx. Changing the old
      # config file doesn't make sense.  moreover, it is not under ucf
      # control in Debian, so running the command from the libpaper
      # hook would give false ucf questions
      # if checkForBinary dvipdfm >/dev/null && tcfmgr --cmd find --file config >/dev/null 2>&1; then
      #   tcBatch dvipdfm paper $p
      # fi
      if checkForBinary dvipdfmx >/dev/null && tcfmgr --cmd find --file dvipdfmx.cfg >/dev/null 2>&1; then
        tcBatch dvipdfmx paper $p
      fi
      if checkForBinary xdvi >/dev/null && tcfmgr --cmd find --file XDvi >/dev/null 2>&1; then
        tcBatch xdvi paper $p
      fi
      if checkForBinary pdftex >/dev/null && tcfmgr --cmd find --file pdftexconfig.tex >/dev/null 2>&1; then
        tcBatch pdftex paper $p
      fi
      ;;

    pdftex)
      help="Usage:
       $progname pdftex paper PAPER

          Valid PAPER settings: Same as for dvips, use
            $progname dvips paper-list
          to get a list of valid PAPER values.

       $progname pdftex paperconf
       $progname pdftex mode MODE
"
      case $2 in

        mode)
          case $3 in
            "")
              echo "Usage: $progname pdftex mode MODE"
              rc=1
              ;;
            *)
              tcBatchPdftexMode=$3
              setupTmpDir
              setupModesMfFile
              if checkElemInList "$tcBatchPdftexMode" `listMfModes | sed 's@ .*@@'`; then
                set x `getRes "$tcBatchPdftexMode"`; shift
                fmgrConfigReplace pdftexconfig.tex 'pdfpkresolution' "\\pdfpkresolution=$1"
                if $fmgrConfigReplaceChanged; then
                  fmtutil --refresh
                fi
              else
                echo "$progname: unknown MODE \`$tcBatchPdftexMode' given as argument for \`$progname pdftex mode'" >&2
                rc=1
              fi
              ;;
          esac
          ;;

        paper)
	  shift; shift
	  pdftexSetPaper $@
	  ;;
	paperconf)
	  pdftexPaperConf
	  ;;
        "")
          echo "$help" >&2; rc=1;;
        *)
          echo "$progname: unknown option \`$2' given as argument for \`$progname pdftex'" >&2
          echo "$progname: try \`$progname pdftex' for help" >&2
          rc=1
          ;;
      esac
      ;;

    rehash)
      mktexlsr
      ;;
    
    # 
    version|--version)
      echo "$progname version $version"
      setupTexmfmain
      setupTexmfdist
      showDistVersionInfo
      (exit 0); exit 0;;

    # handle "xdvi paper PAPER"
    xdvi)
      # 20100125: added paper sizes found in xdvi.c, version.h says 22.84.16 in TeXLive 2010
      tcBatchXdviPapers='us           "8.5x11"
letter       "8.5x11"
usr          "11x8.5"
ledger       "17x11"
tabloid      "11x17"
legal        "8.5x14"
legalr       "14x8.5"
foolscap     "13.5x17.0"
foolscap     "17.0x13.5"
a0           "84.1x118.9cm"
a1           "59.4x84.0cm"
a2           "42.0x59.4cm"
a3           "29.7x42.0cm"
a4           "21.0x29.7cm"
a5           "14.85x21.0cm"
a6           "10.5x14.85cm"
a7           "7.42x10.5cm"
a8           "5.2x7.4cm"
a9           "3.7x5.2cm"
a10          "2.6x3.7cm"
a0r          "118.9x84.1cm"
a1r          "84.0x59.4cm"
a2r          "59.4x42.0cm"
a3r          "42.0x29.7cm"
a4r          "29.7x21.0cm"
a5r          "21.0x14.85cm"
a6r          "14.85x10.5cm"
a7r          "10.5x7.42cm"
a8r          "7.4x5.2cm"
a9r          "5.2x3.7cm"
a10r         "3.7x2.6cm"
b0           "1000.0x141.4cm"
b1           "70.6x100.0cm"
b2           "50.0x70.6cm"
b3           "35.3x50.0cm"
b4           "25.0x35.3cm"
b5           "17.6x25.0cm"
b6           "13.5x17.6cm"
b7           "8.8x13.5cm"
b8           "6.2x8.8cm"
b9           "4.4x6.2cm"
b10          "3.1x4.4cm"
b0           "141.4x100cm"
b1r          "100.0x70.6cm"
b2r          "70.6x50.0cm"
b3r          "50.0x35.3cm"
b4r          "35.3x25.0cm"
b5r          "25.0x17.6cm"
b6r          "17.6x13.5cm"
b7r          "13.5x8.8cm"
b8r          "8.8x6.2cm"
b9r          "6.2x4.4cm"
b10r         "4.4x3.1cm"
c0           "91.7x129.7cm"
c1           "64.8x91.6cm"
c2           "45.8x64.8cm"
c3           "32.4x45.8cm"
c4           "22.9x32.4cm"
c5           "16.2x22.9cm"
c6           "11.46x16.2cm"
c7           "8.1x11.46cm"
c8           "5.7x8.1cm"
c9           "4.0x5.7cm"
c10          "2.8x4.0cm"
c0r          "129.7x91.7cm"
c1r          "91.6x64.8cm"
c2r          "64.8x45.8cm"
c3r          "45.8x32.4cm"
c4r          "32.4x22.9cm"
c5r          "22.9x16.2cm"
c6r          "16.2x11.46cm"
c7r          "11.46x8.1cm"
c8r          "8.1x5.7cm"
c9r          "5.7x4.0cm"
c10r         "4.0x2.8cm"'
      help="Usage: $progname xdvi paper PAPER

Valid PAPER settings:
  a0 a0r a1 a1r a2 a2r a3 a3r a4 a4r a5 a5r a6 a6r a7 a7r a8 a8r a9 a9r a10 a10r
  b0 b0r b1 b1r b2 b2r b3 b3r b4 b4r b5 b5r b6 b6r b7 b7r b8 b8r b9 b9r b10 b10r
  c0 c0r c1 c1r c2 c2r c3 c3r c4 c4r c5 c5r c6 c6r c7 c7r c8 c8r c9 c9r c10 c10r
  foolscap foolscapr legal legalr us|letter usr ledger tabloid"
      case $2 in
        paper-list)
          echo "$tcBatchXdviPapers"
          ;;
        paper)
          case $3 in
	    # 20100125: added paper sizes found in xdvi.c, version.h says 22.84.16 in TeXLive 2010
            a0|a1|a1r|a2|a2r|a3|a3r|a4|a4r|a5|a5r|a6|a6r|a7|a7r|a8|a8r|a9|a9r|a10|a10r|b0|b0r|b1|b1r|b2|b2r|b3|b3r|b4|b4r|b5|b5r|b6|b6r|b7|b7r|b8|b8r|b9|b9r|b10|b10r|c0|c0r|c1|c1r|c2|c2r|c3|c3r|c4|c4r|c5|c5r|c6|c6r|c7|c7r|c8|c8r|c9|c9r|c10|c10r|foolscap|foolscapr|legal|legalr|us|usr|letter|ledger|tabloid)
              fmgrConfigReplace --ucf XDvi paper: "*paper: $3"
              ;;
            "") echo "$help" >&2; rc=1;;
            *)
             echo "$progname: unknown PAPER \`$3' given as argument for \`$progname xdvi paper'" >&2
             echo "$progname: try \`$progname xdvi paper' for help" >&2
             rc=1 ;;
          esac ;;
	paperconf)
	  XDviPaperConf
	  ;;
        "")
          echo "$help" >&2; rc=1;;
        *)
          echo "$progname: unknown option \`$2' given as argument for \`$progname xdvi'" >&2
          echo "$progname: try \`$progname xdvi' for help" >&2
          rc=1
          ;;
      esac
      ;;
    paper-to-size)
      shift
      PaperToSize $@
      ;;
    size-to-paper)
      shift
      SizeToPaper $@
      ;;
    # compare-papers)
    #   # this option is not meant to be used by users; therefore I don't care for insecure tempfiles
    #   tcBatch xdvi paper-list | cut -d " " -f 1 | sort -u > ${TMPDIR:-/tmp}/xdvi.list
    #   tcBatch dvips paper-list | cut -d " " -f 1 | sort -u > ${TMPDIR:-/tmp}/dvips.list
    #   xdviOnly=$(comm -2 -3 ${TMPDIR:-/tmp}/xdvi.list ${TMPDIR:-/tmp}/dvips.list)
    #   dvipsOnly=$(comm -1 -3 ${TMPDIR:-/tmp}/xdvi.list ${TMPDIR:-/tmp}/dvips.list)
    #   knownToBoth=$(comm -1 -2 ${TMPDIR:-/tmp}/xdvi.list ${TMPDIR:-/tmp}/dvips.list)
    #   echo "xdvi only:"
    #   eval echo $xdviOnly
    #   echo
    #   echo
    #   echo "dvips only:"
    #   eval echo $dvipsOnly
    #   echo
    #   echo
    #   echo "known to both:"
    #   eval echo $knownToBoth
    #   rm ${TMPDIR:-/tmp}/dvips.list
    #   rm ${TMPDIR:-/tmp}/xdvi.list
    #   ;;
    *)
      echo "$progname: unknown option \`$1' given as argument for \`$progname'" >&2
      echo "$progname: try \`$progname help' for help" >&2
      rc=1
  esac
}

###############################################################################
# tcInteractive(void)
#   handle interactive mode
###############################################################################
tcInteractive()
{
  texconfig-dialog
}

###############################################################################
# main()
###############################################################################
rc=0
case $# in
  0) tcInteractive;;
  *) tcBatch "$@";;
esac

cleanup $rc
