#!/bin/sh
# $Id$
# 
# common.sh -- common routines for the TeX Live installation scripts.
# Do not call directly.
# 
# Copyright 2003, 2004, 2005, 2006, 2007 Sebastian Rahtz and Karl Berry.
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
# 
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
# 
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
#    02110-1301, USA.
#     
#    Send bug reports or suggestions to tex-live@tug.org.

# We only do English, and we don't want different locales to mess up the
# output of, e.g., ls.
LC_ALL=C; export LC_ALL

setvars()
{
  # These names correspond to the texmf/lists/bin-tex.* files, with -
  # changed to _.
  p_alpha_linux_n='DEC Alpha with GNU/Linux'
  p_alphaev5_osf_n='DEC Alphaev5 OSF'
  p_hppa_hpux_n='HP-UX'
  p_i386_cygwin_n='Intel x86 with Cygwin'
  p_i386_darwin_n='Intel x86 with MacOSX/Darwin'
  p_i386_freebsd_n='Intel x86 with FreeBSD'
  p_i386_openbsd_n='Intel x86 with OpenBSD'
  p_i386_linux_n='Intel x86 with GNU/Linux'
  p_i386_solaris_n='Intel x86 with Sun Solaris'
  p_mips_irix_n='SGI IRIX'
  p_powerpc_aix_n='PowerPC AIX'
  p_powerpc_darwin_n='Mac OSX/Darwin 5.3 or 6.*'
  p_sparc_linux_n='Sparc with GNU/Linux'
  p_sparc_solaris_n='Sparc with Solaris'
  p_win32_n='Windows'
  p_x86_64_linux_n='Intel x86_64 with GNU/Linux'


  iden_1=a
  iden_2=b
  iden_3=c
  iden_4=d
  iden_5=e
  iden_6=f
  iden_7=g
  iden_8=h
  iden_9=i
  iden_10=j
  iden_11=k
  iden_12=l
  iden_13=m
  iden_14=n
  iden_15=o
  iden_16=p
  iden_17=s
  iden_18=t
  iden_19=u
  iden_20=v
  iden_21=w
  iden_22=x
  iden_23=y
  iden_24=z
  iden_25=A
  iden_26=B
  iden_27=C
  iden_28=D
  iden_29=E
  iden_30=F
  iden_31=G
  iden_32=H
  iden_33=I
  iden_34=J
  iden_35=K
  iden_36=L
  iden_37=M
  iden_38=N
  iden_39=O
  iden_40=P
  iden_41=T
  iden_42=U
  iden_43=V
  iden_44=W
  iden_45=X
  iden_46=Y
  iden_47=Z
  iden_48=1
  iden_49=2
  iden_50=3
  iden_51=4
  iden_52=5
  iden_53=6
  iden_54=7
  iden_55=8
  iden_56=9
  iden_57=0
}


series_select_level()
{
  p=$1
  l=$2
  case $l in
    0) eval p_${p}_s=false
       eval p_${p}_level=\'[ ]\'
       eval p_${p}_dus=0;;
    1) eval p_${p}_s=true
       eval p_${p}_level=\'[X]\'
       eval p_${p}_dus=\$p_${p}_du;;
    2) eval S=\$p_${p}_s
       if test "$S" = "true"; then
         eval p_${p}_s=false
         eval p_${p}_level=\'[ ]\'
         eval p_${p}_dus=0
       else
         eval p_${p}_s=true
         eval p_${p}_level=\'[X]\'
         eval p_${p}_dus=\$p_${p}_du
       fi
       ;;
  esac
  setlength p_${p}_dus 6
}

scheme_select()
{
  S=`echo $1 | sed -e 's/_/-/g' `
  series_lang_allnone
  series_allnone
  for i in `grep "^-collection-" $LISTS/$S.scheme | sed -e 's/^-//' -e 's/-/_/g'`
  do
     series_select_level $i 1
  done
  selected_packages=`grep "^[+\-]" $LISTS/$S.scheme | grep -v collection- | sed -e 's/^.//' -e 's/-/_/'`
  selected_collections=`grep "^-collection-" $LISTS/$S.scheme | sed -e 's/^-collection-//'`
}

system_selectall()
{
  size=0
  for s in $all_systems; do
    eval p_${p}_s=false
    eval size=\`expr $size + \$p_${s}_du\`
    eval p_${s}_s=true
  done
  all_systems_ns=$all_systems_anz
  setlength all_systems_ns 2
}

system_deselectall()
{
  for s in $all_systems; do
    series_select_level $s 0
  done
  all_systems_ns=0
  setlength all_systems_ns 2
}

series_lang_allnone()
{
  for s in $all_lang_collections; do
    series_select_level $s 0
  done
  series_select_level tex_basic 1
  total_stat
}

series_lang_allall()
{
  for s in $all_lang_collections; do
    series_select_level $s 1
  done
  total_stat
}

series_allnone()
{
  for s in $all_collections; do
    series_select_level $s 0
  done
  series_select_level tex_basic 1
  total_stat
}

series_allall()
{
  for s in $all_collections; do
    series_select_level $s 1
  done
  total_stat
}


systems_init () {
  $echon "Initializing system packages... "
  all_systems=
  anz=0
  for s in $systems; do
    anz=`expr $anz + 1`
    t=`echo $s | sed 's@-@_@g; s@\.@@g'`
    all_systems="$all_systems $t"
    eval p_${t}_fn=$s
    eval p_${t}_s=false
  done
  echo "done."
  
  all_systems_anz=$anz
  platform_guess
  if test -n "$this_system"; then
    eval p_${this_system}_s=true
    eval this_platform_n=\$p_${this_system}_n
    eval this_platform_fn=\$p_${this_system}_fn
    all_systems_ns=1
  fi
  setlength all_systems_anz 2
  setlength all_systems_ns 2
    total_stat
}

select_platforms()
{
  changed=false
  cls
  echo "Available sets of binaries: ";
  for p in $all_systems; do eval name=\"\$p_${p}_n\"; echo "  $p: $name" ;done
  echo "You can now choose to install some of these "
  echo "Possible answers: <Y>es, <N>o, <R>eturn to main menu, <Q>uit."
  echo ""
  for p in $all_systems; do
    eval name=\"\$p_${p}_n\"
    case `getopt YNRQ "Install binaries for system [$p] $name"` in
      Y) eval p_${p}_s=true; changed=true;;
      N) eval p_${p}_s=false; changed=true;;
      R) break;;
      Q) exit_on_confirm;;
    esac
  done
  $changed && { system_stat;   total_stat; }
}

system_stat()
{
  $echon "Counting selected system packages... "
  anz=0
  for i in $all_systems; do
    eval \$p_${i}_s && anz=`expr $anz + 1`
  done
  all_systems_ns=$anz
  setlength all_systems_ns 2
  echo "done."
}

nobinstat()
{
  $echon "Counting selected collections... "
  anz=0
  for i in $all_collections; do
    eval \$p_${i}_s && anz=`expr $anz + 1`
  done
  for i in $all_lang_collections; do
    eval \$p_${i}_s && anz=`expr $anz + 1`
  done
  all_collections_ns=$anz
  setlength all_collections_ns 2
  echo "done."

  $echon "Calculating disk space requirements for collections..."
  size=0
  for i in $all_collections; do
    eval \$p_${i}_s && eval size=\`expr $size + \$p_${i}_du\`
  done
  for i in $all_lang_collections; do
    eval \$p_${i}_s && eval size=\`expr $size + \$p_${i}_du\`
  done
  all_collections_dus=$size
  setlength all_collections_dus 6
  echo "done."
}

total_stat()
{
  nobinstat
  total_dus=`expr $all_collections_dus`
  setlength total_dus 6
}

this_platform_set()
{
  system_deselectall
  if test -n "$this_system"; then
    eval p_${this_system}_s=true
    size=0
    eval size=\`expr $size + \$p_${this_system}_du\`
    eval this_platform_n=\$p_${this_system}_n
    eval this_platform_fn=\$p_${this_system}_fn
    all_systems_ns=1
  fi

}

TEXMFCNF__fix_texmf()
{
  #test "$TEXDIR/texmf" = "$TEXMF" && return
  #test -w "$TEXMFCNF_DIR/texmf.cnf" || return
  cd $work_dir || exit 1
  #
  LOCAL=$TEXMFLOCAL
  if test "x$LOCAL_CHANGE" = "x1"; then
    : # explicitly set by user.
  elif test "x$LOCAL_CHANGE" = "x2"; then
    # implicitly set by changing TEXDIR
    LOCAL="\$SELFAUTOPARENT/texmf-local"
  else
    # no changes, meaning they took the default of /usr/local/texlive/YYYY,
    # meaning we want /usr/local/texlive/texmf-local ... one level up.
    LOCAL="\$SELFAUTOPARENT/../texmf-local"
  fi
  echo "Setting local tree (TEXMFLOCAL) to $LOCAL in $TEXMFCNF_DIR/texmf.cnf... " >&2
  sed "s@^TEXMFLOCAL.*@TEXMFLOCAL=$LOCAL@" $TEXMFCNF_DIR/texmf.cnf \
    >.sed_tmp.$$
  #
  VAR=$TEXMFSYSVAR
  test "x$VAR_CHANGE" = "x" && VAR="\$SELFAUTOPARENT/texmf-var"
  echo "Setting system var tree (TEXMFSYSVAR) to $VAR in $TEXMFCNF_DIR/texmf.cnf... " >&2
  sed "s@^TEXMFSYSVAR.*@TEXMFSYSVAR=$VAR@" \
    <.sed_tmp.$$ >$TEXMFCNF_DIR/texmf.cnf 
  rm .sed_tmp.$$
  # 
  # the TEXMFHOME tree
  if test "x$TEXMFHOME" != '$HOME/texmf'; then
    # if the variable starts with the explicit home of the current user
    # (as in "/u/karl") replace that with the string '$HOME' as the
    # explicit home of the current user is unlikely to ever be right.
    if echo "$TEXMFHOME" | grep "$HOME" >/dev/null; then
      hme=`echo "$TEXMFHOME" | sed "s,$HOME/*,,"`
      TEXMFHOME="\$HOME/$hme" 
    fi
    #
    echo "Setting TEXMFHOME to $TEXMFHOME in $TEXMFCNF_DIR/texmf.cnf... " >&2
    sed "s,^TEXMFHOME.*,TEXMFHOME=$TEXMFHOME," $TEXMFCNF_DIR/texmf.cnf \
      >sedtmp.$$
    cp sedtmp.$$ $TEXMFCNF_DIR/texmf.cnf
    rm -f sedtmp.$$
  fi
  
  echo "Done updating texmf.cnf." >&2
  echo >&2
}


TEXMFCNF__fix_fmtutil()
{
  echo "Configuring fmtutil.cnf from $TEXMFCNF_DIR  into  $TEXMFSYSVAR/web2c... " >&2
  cd $work_dir
  mkdirhier $TEXMFSYSVAR/web2c
  sed "s@^\#!\#@@" $TEXMFCNF_DIR/fmtutil.cnf > $TEXMFSYSVAR/web2c/fmtutil.cnf
}



prepare_dirs()
{
  $echon "Preparing destination directories... " >&2
  unset TEXMFCNF
  unset TEXMFMAIN
  test -d "$CDDIR" \
    || fatal "$CDDIR does not seem to be the TeX Live distribution!"

  work_dir=${TMP-/tmp}/.tmp_tlinst.$$
  ERRLOG=$work_dir/.errlog.$$

  trap "cd /; rm -rf $work_dir $TEXDIR/texmf/.tmp_testfile.$$;trap '' 0; exit 0" 0 1 2 15

  alldirs="$TMPDIR $TEXDIR $TEXMFSYSVAR $TEXMF $work_dir $opt_symlinks_bin $opt_symlinks_info"
  test -z "$TEXMFSYSVAR" ||
    alldirs="$alldirs $TEXMFSYSVAR/fonts/pk $TEXMFSYSVAR/fonts/tfm"
  test -z "$opt_varfonts_dir" ||
    alldirs="$alldirs $opt_varfonts_dir/pk $opt_varfonts_dir/tfm"
  for dir in $alldirs; do
    while test ! -d $dir || test ! -w $dir; do
      mkdirhier $dir
      test -d $dir || { warn "could not make directory '$dir'"; continue; }
      test -w $dir || { warn "cannot write to directory '$dir'"; continue; }
    done
  done
  test -z "$TEXMFSYSVAR" || chmod -R a+w $TEXMFSYSVAR ||
     warn "command 'chmod -R a+w $TEXMFSYSVAR' failed"
  test -z "$opt_varfonts_dir" ||
    chmod 1777 $opt_varfonts_dir/pk $opt_varfonts_dir/tfm ||
    warn "command 'chmod 1777 $opt_varfonts_dir/pk $opt_varfonts_dir/tfm' failed"

  echo "done preparing." >&2
  if test $all_systems_ns = 1; then
    cls
    textvar_show screen_6
    echo
  fi
}

make_var_skeleton ()
{
  mkdirhier $TEXMFSYSVAR/tex/generic/config
  mkdirhier $TEXMFSYSVAR/dvipdfm/config
  mkdirhier $TEXMFSYSVAR/tex/plain/config
  mkdirhier $TEXMFSYSVAR/dvips/config
  mkdirhier $TEXMFSYSVAR/fonts/map/dvipdfm/updmap
  mkdirhier $TEXMFSYSVAR/fonts/map/dvips/updmap
  mkdirhier $TEXMFSYSVAR/fonts/map/pdftex/updmap
  mkdirhier $TEXMFSYSVAR/web2c
  mkdirhier $TEXMFSYSVAR/xdvi
  mkdirhier $TEXMFSYSVAR/tex/context/config
}

make_local_skeleton ()
{
 # skeleton local hierarchy
  mkdirhier $TEXMFLOCAL/tex/latex/local
  mkdirhier $TEXMFLOCAL/tex/plain/local
  mkdirhier $TEXMFLOCAL/dvips/local
  mkdirhier $TEXMFLOCAL/bibtex/bib/local
  mkdirhier $TEXMFLOCAL/bibtex/bst/local
  mkdirhier $TEXMFLOCAL/fonts/tfm/local
  mkdirhier $TEXMFLOCAL/fonts/vf/local
  mkdirhier $TEXMFLOCAL/fonts/source/local
  mkdirhier $TEXMFLOCAL/fonts/type1/local
  mkdirhier $TEXMFLOCAL/metapost/local
  mkdirhier $TEXMFLOCAL/web2c
}


maketex_setoptfonts()
{
    test -w "$TEXMFCNF_DIR/texmf.cnf" || return
    test "$opt_varfonts" = X || return
    $echon "Setting VARFONTS in texmf.cnf... " >&2
    ed "$TEXMFCNF_DIR/texmf.cnf" >$ERRLOG 2>&1 <<eof
/^VARTEXFONTS.*=/
c
VARTEXFONTS        = $opt_varfonts_dir
.
w
q
eof
    show_error
    echo "Done setting varfonts." >&2

    mtsite=$TEXMFCNF_DIR/mktex.cnf
    chmod u+w $mtsite
    test -w "$mtsite" || return
    show_error
    $echon "Adding varfonts feature in $mtsite... " >&2
    ed "$mtsite" >$ERRLOG 2>&1 <<'eof'
/MT_FEATURES=appendonlydir/
s/dir/dir:varfonts/
w
q
eof
    show_error
    echo "Done adding varfonts." >&2
}

greetings()
{
  cat <<ENDG

See ./index.html for links to documentation.
The TeX Live web site (http://tug.org/texlive/)
contains any updates and corrections.

TeX Live is a joint project of the TeX user groups around the world;
please consider supporting it by joining the group best for you.  
The list of groups is available on the web at 
http://tug.org/usergroups.html.

Welcome to TeX Live!

ENDG
}

opt_do_symlinks()
{
  test "$opt_symlinks" = X || return

  $echon 'Creating symbolic links...'
  texdocdir=$TEXDIR/texmf/doc
  
  # Dynamically see which man sections we have.
  mans=`(cd $texdocdir/man && echo *)`
  test -z "$mans" && return  # unlikely but possible
  #
  for m in $mans; do
    mandir=$texdocdir/man/$m
    test -d $mandir || continue  # in case a README or something sneaks in.

    mkdirhier $opt_symlinks_man/$m
    test ! -w $opt_symlinks_man/$m && continue
    
    $echon " $m"
    cd $opt_symlinks_man/$m || continue
    rm -f `ls $mandir`
    ln -s $mandir/* .
  done

  # no subdirs for info.
  infodir=$texdocdir/info
  if test -w "$opt_symlinks_info"; then
    $echon " info"
    if cd $opt_symlinks_info; then
      rm -f `ls $infodir`
      ln -s $infodir/*info* .
    fi
  fi

  this_platform_bin=
  if test -x $TEXDIR/bin/tex; then
    this_platform_bin=$TEXDIR/bin
  elif test -x $TEXDIR/bin/$this_platform_fn/tex; then
    this_platform_bin=$TEXDIR/bin/$this_platform_fn
  fi
  if test -n "$this_platform_bin"; then
    $echon " binaries"
    $debug && echo " (target $this_platform_bin)"
    if cd $opt_symlinks_bin; then
      rm -f `ls $this_platform_bin`
      ln -s $this_platform_bin/* .
    fi
  fi

  echo ' ... done linking.'
}

################################################################
# menus:
################################################################
menu_main()
{
    while true; do
        cls
        opt_savespace_man=X
        echo; textvar_show screen_1; echo
        case `getopt BCDHILOPQRS 'Enter command'` in
          B) select_platforms;;
          C) menu_series_customize;;
          D) menu_directories;;
          H) helpme help_1;;
          I) install_now;;
          L) menu_lang_series_customize;;
          O) menu_options;;
          P) menu_this_platform;;
          Q) exit_on_confirm;;
          R) install_cd;;
          S) menu_schemes;;
        esac
    done
}


# NEW PLATFORM: change getopt call and add a new case.
menu_this_platform()
{
    while true; do
        cls
        textvar_show screen_5; echo
      case `getopt NABCDEFGHIJKLMOPRQ 'Select the platform you are currently on'` in
          N) this_system=''; this_platform_set ;;
          A) this_system=i386_linux; this_platform_set ;;
          B) this_system=win32; this_platform_set ;;
          C) this_system=powerpc_darwin; this_platform_set ;;
          D) this_system=i386_darwin; this_platform_set ;;
          E) this_system=alpha_linux; this_platform_set ;;
          F) this_system=mips_irix; this_platform_set ;;
          G) this_system=powerpc_aix; this_platform_set ;;
          H) this_system=hppa_hpux; this_platform_set ;;
          I) this_system=sparc_solaris; this_platform_set ;;
          J) this_system=i386_solaris; this_platform_set ;;
          K) this_system=i386_freebsd; this_platform_set ;;
          L) this_system=i386_openbsd; this_platform_set ;;
          M) this_system=i386_cygwin; this_platform_set ;;
          # N above
          O) this_system=x86_64_linux; this_platform_set ;;
          P) this_system=sparc_linux; this_platform_set ;;
          Q) exit_on_confirm ;;
          R) total_stat; return ;;
        esac
    done
}


# This run for scheme selection <S>.
menu_schemes()
{
    while true; do
        cls
        for i in $all_schemes
	do 
	    eval key=\"\$schemes_${i}_ident\"
	    eval name=\"\$schemes_${i}_n\"
	    echo $key $name
	done | pr -t -2 - 
        echo
        echo "Current scheme: $selected_scheme."
        echo
        echo '    Press <S> to see collections for this scheme,'
        echo '          <R> to return to main menu, <Q> to quit'
        K=`getopt ABCDEFGHIJKLMNOPQRSTUVWXYZ '      or press key to select a scheme'`
        case $K in 
          Q) exit_on_confirm;;
          R) total_stat; return ;;
          S) echo "Collections: $selected_collections" \
             | sed 's/tex_//g' | fmt;;
          *) eval W=\"\$SCHEMES_${K}\"
	     selected_scheme=$W
	     scheme_select $W
	     total_stat
	     echo "New scheme: $selected_scheme."
	     return;;
        esac
    done
}

# emacs-page
menu_series_customize()
{
    while true; do
        cls
        for i in $all_collections 
	do 
	    eval status=\"\$p_${i}_level\"
	    eval key=\"\$p_${i}_ident\"
	    eval name=\"\$p_${i}_n\"
	    echo $key $status $name
	done | pr -t -2 -
        textvar_show screen_customize; echo
        K=`getoptallcase -+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 'Press key to toggle status of collection'`
        case $K in 
          +) series_allall;;
          -) series_allnone;;
          R)  total_stat; return ;;
          r)  total_stat; return ;;
          Q) exit_on_confirm;;
          q) exit_on_confirm;;
          *) eval W=\"\$P_${K}\"
             series_select_level $W 2; 
        esac
    done
}

menu_lang_series_customize()
{
    while true; do
        cls
        for i in $all_lang_collections 
	do 
	    eval status=\"\$p_${i}_level\"
	    eval key=\"\$p_${i}_ident\"
	    eval name=\"\$p_${i}_n\"
	    echo $key $status $name
	done | pr -t -2 -
        textvar_show screen_customize; echo
        K=`getoptallcase -+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 'Press key to toggle status of collection'`
        case $K in 
          +) series_lang_allall;;
          -) series_lang_allnone;;
          R)  total_stat; return ;;
          Q) exit_on_confirm;;
          r)  total_stat; return ;;
          q) exit_on_confirm;;
          *) eval W=\"\$LP_${K}\"
             series_select_level $W 2; 
        esac
    done
}


menu_directories()
{
    while true; do
        cls
        textvar_show screen_2; echo
        case `getopt 1234RQ 'Enter command'` in
          1) gets TEXDIR
	     LOCAL_CHANGE=2
             TEXDIR=`dirname "$TEXDIR/x" | sed 's@//*@/@g'`
             TEXMF=`echo $TEXDIR/texmf | sed 's@//*@/@g'`
	     TEXMFLOCAL=`echo $TEXDIR/texmf-local` 
	     TEXMFSYSVAR=`echo $TEXDIR/texmf-var`
	     ;;
          2) gets TEXMFLOCAL
             LOCAL_CHANGE=1
             TEXMFLOCAL=`dirname "$TEXMFLOCAL/x" | sed 's@//*@/@g'`
             ;;
          3) gets TEXMFSYSVAR
             VAR_CHANGE=1
             TEXMFSYSVAR=`dirname "$TEXMFSYSVAR/x" | sed 's@//*@/@g'`
             ;;
          4) gets TEXMFHOME
             TEXMFHOME=`dirname "$TEXMFHOME/x" | sed 's@//*@/@g'` ;;
          R) return;;
          Q) exit_on_confirm;;
        esac
    done
}

menu_options()
{
    while true; do
        cls
        textvar_show screen_3; echo
        case `getopt ADFLRSQ 'Enter command'` in
          A) toggle opt_varfonts
             if test "$opt_varfonts" = X; then
               cls; textvar_show screen_3; echo
               opt_varfonts_dir=$opt_varfonts_dir_last
               test -z "$opt_varfonts_dir" && opt_varfonts_dir=/tmp/texfonts
               gets opt_varfonts_dir 'alternate directory'
             else
               opt_varfonts_dir_last=$opt_varfonts_dir
               opt_varfonts_dir=''
             fi
             ;;
          S) toggle opt_source
             if test "$opt_source" = X; then
               cls; textvar_show screen_3; echo
             fi
             ;;
          D) toggle opt_doc
             if test "$opt_doc" = X; then
               cls; textvar_show screen_3; echo
             fi
             ;;
          L) toggle opt_symlinks
             if test "$opt_symlinks" = X; then
               cls; textvar_show screen_3; echo
               opt_symlinks_bin=$opt_symlinks_bin_last
               test -z "$opt_symlinks_bin" && opt_symlinks_bin=/usr/bin
               gets opt_symlinks_bin 'binary directory'
               opt_symlinks_man=$opt_symlinks_man_last
               test -z "$opt_symlinks_man" && opt_symlinks_man=`dirname $opt_symlinks_bin`/man
               gets opt_symlinks_man 'man directory   '
               opt_symlinks_info=$opt_symlinks_info_last
               test -z "$opt_symlinks_info" && opt_symlinks_info=`dirname $opt_symlinks_bin`/info
               gets opt_symlinks_info 'info directory  '
             else
               opt_symlinks_bin_last=$opt_symlinks_bin
               opt_symlinks_man_last=$opt_symlinks_man
               opt_symlinks_info_last=$opt_symlinks_info
               opt_symlinks_bin=''; opt_symlinks_man=''; opt_symlinks_info=''
             fi
             ;;
          R) return;;
          Q) exit_on_confirm;;
        esac
    done
}

exit_on_confirm()
{
    cls
    yesno 'Really quit' && exit
}

################################################################
# global variables
################################################################
: ${PAGER=more}
envvars='
BIBINPUTS BSTINPUTS DVIPSHEADERS GFFONTS GLYPHFONTS MFBASES MFINPUTS
MFPOOL PKFONTS TEXCONFIG TEXFONTS TEXFORMATS TEXINPUTS TEXMFCNF TEXPICTS
TEXPKS TEXPOOL TFMFONTS VFFONTS DVIPSFONTS XDVIVFS XDVIFONTS DVILJFONTS
'
TARPROG=tar
TAROPT=""
varprefix='/var'
usrprefix='/usr'
opt_varfonts=' '
opt_vartexmf=' '
opt_source=' '
opt_doc=' '
opt_varfonts_dir=''
opt_vartexmf_dir=''
opt_varfonts_dir_last=''
opt_vartexmf_dir_last=''
opt_symlinks=' '
opt_symlinks_bin=''
opt_symlinks_man=''
opt_symlinks_info=''
opt_symlinks_bin_last=''
opt_symlinks_man_last=''
opt_symlinks_info_last=''

this_platform=

################################################################
# screens:
################################################################

screen_2='Current directories setup:
==============================================================================

  <1>  TEXDIR:       $TEXDIR
       support tree: $TEXMF

  <2>  TEXMFLOCAL:   $TEXMFLOCAL
  <3>  TEXMFSYSVAR:  $TEXMFSYSVAR
  <4>  TEXMFHOME:    $TEXMFHOME

Other options:
==============================================================================
  <R>   return to main menu
  <Q>   quit
'

screen_3='Current options setup:
==============================================================================

  <A>  alternate directory for automatically generated fonts: [$opt_varfonts]
         directory name: $opt_varfonts_dir
  <L>  create symlinks in standard directories:               [$opt_symlinks]
            binaries to: $opt_symlinks_bin
            manpages to: $opt_symlinks_man
                info to: $opt_symlinks_info
  <D>  do not install font/macro doc tree: [$opt_doc]
  <S>  do not install font/macro source tree: [$opt_source]

Other options:
==============================================================================
  <R>   return to main menu
  <Q>   quit
'

screen_5='Current platform: $this_platform_n
==============================================================================
  <N>  none of the entries below
  <A> $p_i386_linux_n
  <B> $p_win32_n
  <C> $p_powerpc_darwin_n
  <D> $p_i386_darwin_n
  <E> $p_alpha_linux_n
  <F> $p_mips_irix_n
  <G> $p_powerpc_aix_n
  <H> $p_hppa_hpux_n
  <I> $p_sparc_solaris_n
  <J> $p_i386_solaris_n
  <K> $p_i386_freebsd_n
  <L> $p_i386_openbsd_n
  <M> $p_i386_cygwin_n
  <O> $p_x86_64_linux_n
  <P> $p_sparc_linux_n

  <R>   return to main menu
  <Q>   quit
'


screen_6='TeX Live can be used on multiple systems
as a separate subdirectory is used for each
installed binary package in $TEXDIR/bin.'

screen_customize='
  <-> deselect all  <+> select all  <R> return to main menu  <Q> quit
'

system_screen='System setup section
==============================================================================
Current selection: $all_systems_ns out of $all_systems_anz

==============================================================================
  <R>   return to platform menu
  <Q>   quit
'

help_1='
This is the installation program of the TeX Live distribution.

The installation procedure is simple: just go through the
menus until you are happy with the way all options are set up,
and then do <I> (start installation).

To select a menu item (a letter or a number marked with brackets)
just enter the corresponding letter or number and press return
(the letters are case insensitive except when collections
are being selected). Do not enter the 
angle brackets <> themselves.

We will now consider each menu item in more detail:

======================================================================
  The collections menu (<C>)
======================================================================

The collections menu allows you to select and deselect standard
collections. Each collection --- TeX macro files, Metafont font
families, and so on --- consists of several packages.

======================================================================
  The language collections menu (<L>)
======================================================================

The language collections menu allows you to select and deselect
language support collections. Each collection consists of several
packages, which provide features like hyphenation files and fonts.

======================================================================
  The binary systems menu (<B>)
======================================================================

The systems menu allows you to select and deselect 
the binary packages for various different platforms.

======================================================================
  The directories menu (<D>)
======================================================================

The TeX Live distribution will be installed in a single directory tree
(TEXDIR). You may choose any directory you like
since there are no absolute paths compiled into the binaries. Instead,
the Kpathsea library selfdir feature ensures that all
paths are relative to the location of the binaries.

The platform independent files are stored in a directory tree in
TEXDIR/texmf. There is also an extra directory for performing
administrative tasks like change of configuration and languages. This
is where all format files are stored. It defaults to TEXDIR/texmf-var.

This system allows you to mount your
TEXDIR/texmf tree read-only.

======================================================================
  The options menu (<O>)
======================================================================

The options are not applicable to all installations.  Set them as
appropriate for yours.

======================================================================
  The schemes menu (<S>)
======================================================================

You can choose from a number of different installation
schemes for TeX Live. Selecting one of these selects
some collections in the Collections and Languages lists.
which you can subsequently modify.

"alternate fonts directory":
============================

You can choose an alternate directory for automatically generated fonts;
the default is TEXMFSYSVAR/fonts

One disadvantage may be that new fonts are not shared.  I.e., if you
set this to /tmp, and users on two different machines need the same
font, it will be built twice, once on each machine.

"symlinks in standard directories"
==================================

You can make the binaries, man pages, and info files available on your
system in either (or both) of two ways:
  1) install them in "standard places" that are searched for these files
  2) change your search paths to include the new directories

If you select the "symlinks" option, symbolic links will be installed in
the directories you choose. Note that if you share the TeX Live installation
accross several machines across NFS and if the chosen "standard places" are
not shared, you need to create the symbolic links on each client, too
(or use method 2 on your clients).

If you do not use the "symlinks" option, you probably need to set up
your search paths (PATH, MANPATH, INFOPATH).

"do not install doc or source trees"
====================================
These options are not recommended, but you can use them to save space. 
Normally all packages are installed with the source and/or documentation,
but these are not needed to actually run the software. If you
are installing a system for other people, it would be unfriendly to
select these options; if you know what you are doing and need a
minimal disk footprint, go ahead


======================================================================
  Other commands (<I>, <H>, <R> and <Q>
======================================================================

Well, this is easy to explain:
  <R> does not install the system, but sets you to run off the CD
  <I> starts the installation after you are happy with the setup
  <H> displays this help
  <Q> quits the installation program
'

init()
{
  #$debug && set -x
  echo "Welcome to TeX Live installation. (`date`)"; echo
  locate_binaries
  bad_sh
  find_echo
  find_tar
  series_init
  bindir=
  tex_prefix=${TEXLIVE_INSTALL_PREFIX-/usr/local/texlive}
  TEXDIR=${TEXLIVE_INSTALL_TEXDIR-$tex_prefix/2007}  # manually update each year!
  TEXMFSYSVAR=${TEXLIVE_INSTALL_TEXMFSYSVAR-$TEXDIR/texmf-var}
  TEXMF=$TEXDIR/texmf
  TEXMFLOCAL=${TEXLIVE_INSTALL_TEXMFLOCAL-$tex_prefix/texmf-local}
  TEXMFHOME=${TEXLIVE_INSTALL_TEXMFHOME-'$HOME/texmf'}
  VAR_CHANGE=""
  LOCAL_CHANGE=""

screen_1=' ===================> TeX Live installation procedure <==================

===> Note: Letters/digits in <angle brackets> indicate menu items <===
===>       for commands or configurable options                   <===

    Proposed platform: $this_platform_n
    <P> override system detection and choose platform
    <B> binary systems:        $all_systems_ns out of $all_systems_anz
    <S> Installation scheme ($selected_scheme)
        [to customize within installation scheme:
         <C> standard collections   <L> language collections]
    $all_collections_ns out of $all_collections_anz, disk space required: $all_collections_dus kB
    <D> directories:
      TEXDIR      (main TeX directory):     $TEXDIR     
      TEXMFSYSVAR (systemwide config):      $TEXMFSYSVAR
      TEXMFLOCAL  (systemwide styles etc.): $TEXMFLOCAL
      TEXMFHOME   (personal styles etc.):   $TEXMFHOME
    <O> options:
       [$opt_varfonts] alternate directory for generated fonts ($opt_varfonts_dir)
       [$opt_symlinks] create symlinks in standard directories
       [$opt_doc] do not install macro/font doc tree
       [$opt_source] do not install macro/font source tree
    <R> do not install files, set up to run off CD or DVD
    <I> start installation
    <H> help,  <Q> quit
'

}

list_zipped_files()
{
  col=`echo $1 | sed 's/_/-/g'`
  $debug && echo "          -> collection $col" >&2
    morecols=`grep -- "^-" $LISTS/$col | sed 's/.//'`
    packages=`grep "^+"    $LISTS/$col | sed 's/.//'`
    :>$work_dir/tmp.text
    :>$work_dir/$col.jobs
    echo "$col.zip" >> $work_dir/tmp.text
    eval sort < $LISTS/$col | grep '^\!' | tr ' ' '=' >> $work_dir/$col.jobs
    if  test "x$packages" != "x"
    then
      for i in $packages 
      do
        expand_package $i $col
      done
    fi
  eval sort -u $work_dir/tmp.text >> $work_dir/$col.list.text


  rm $work_dir/tmp.text 

  if test "x$morecols" != "x"
  then
  for p in $morecols
  do
      list_zipped_files $p
  done
  fi

}

expand_package ()
{
  pack=$1
  col=$2
  $debug && echo "      expand package $pack"  >&2
  echo "$pack.zip" >> $work_dir/tmp.text
  eval sort < $LISTS/$pack | grep '^\!' | tr ' ' '=' >> $work_dir/$col.jobs
  more=`grep "^+" $LISTS/$pack | sed 's/.//'`
  if test "x$more" != "x"
  then
  for i in $more
   do
    expand_package $i $col
   done
  fi
}


# emacs-page
# at the beginning of the end ... called at the beginning of install_new.
# the caller must set list_file_func and list_package_func.
# 
common_start_install()
{
  prepare_dirs
  make_local_skeleton
  make_var_skeleton

  skip_systemstuff=false
  TEXMFCNF_DIR=$TEXDIR/texmf/web2c
  test -f $TEXMFCNF_DIR/texmf.cnf && skip_systemstuff=true

  # 
  cat >$TEXMFSYSVAR/web2c/updmap.cfg <<OAF
# created during TeX Live installation, `date`.
################################################################
# OPTIONS
################################################################
#
# dvipsPreferOutline
#
# Should dvips (by default) prefer bitmap fonts or outline fonts
# if both are available? Independent of this setting, outlines
# can be forced by putting "p psfonts_t1.map" into a config file
# that dvips reads. Bitmaps (for the fonts in question) can
# be forced by putting "p psfonts_pk.map" into a config file.
# We provide such config files which can be enabled via
# dvips -Poutline ... resp. dvips -Ppk ...
#
# Valid settings for dvipsPreferOutline are true / false:
dvipsPreferOutline true

#
# LW35
#
# Which fonts for the "Basic 35 Laserwriter Fonts" do you want to use and
# how are the filenames chosen? Valid settings:
#   URW:     URW fonts with "vendor" filenames (e.g. n019064l.pfb)
#   URWkb:   URW fonts with "berry" filenames (e.g. uhvbo8ac.pfb)
#   ADOBE:   Adobe fonts with "vendor" filenames (e.g. hvnbo___.pfb)
#   ADOBEkb: Adobe fonts with  "berry" filenames (e.g. phvbo8an.pfb)
LW35 URWkb

#
# dvipsDownloadBase35
# 
# Should dvips (by default) download the standard 35 LaserWriter fonts
# with the document (then set dvipsDownloadBase35 true) or should these
# fonts be used from the ps interpreter / printer?
# Whatever the default is, the user can override it by specifying
# dvips -Pdownload35 ... resp. dvips -Pbuiltin35 ... to either download
# the LW35 fonts resp. use the built-in fonts.
#
# Valid settings are true / false:
dvipsDownloadBase35 false

#
# pdftexDownloadBase14
#
# Should pdftex download the base 14 pdf fonts? Since some configurations
# (ps / pdf tools / printers) use bad default fonts, it is safer to download
# the fonts. The pdf files will get bigger, though.
# Valid settings are true (download the fonts) or false (don't download
# the fonts). Adobe recomments to embed all fonts.
pdftexDownloadBase14 true

#
# dvipdfmDownloadBase14
#
# Should dvipdfm download the base 14 pdf fonts? Since some configurations
# (ps / pdf tools / printers) use bad default fonts, it is safer to download
# the fonts. The pdf files will get bigger, though.
# Valid settings are true (download the fonts) or false (don't download
# the fonts).
dvipdfmDownloadBase14 true

################################################################
# Map files.
################################################################
#
# There are two possible entries: Map and MixedMap. Both have one additional
# argument: the filename of the map file. MixedMap ("mixed" means that
# the font is available as bitmap and as outline) lines will not be used
# in the default map of dvips if dvipsPreferOutline is false. Inactive
# Map files should be marked by "#! " (without the quotes), not just #.
#
# (comments on a few map files from the teTeX updmap.cfg; for TeX Live,
# the actual Map lines are created during installation.)
# 
# AntykwaPoltawskiego; CTAN:fonts/psfonts/polish/antp/
# 
# AntykwaTorunska; CTAN:fonts/antt/
# 
# "quasi" fonts derived from URW and enhanced (from the Polish TeX users);
# CTAN:fonts/psfonts/polish/qfonts/
# 
# Bitstream Charter text font
#
# Computer Modern fonts extended with Russian letters;
# CTAN:fonts/cyrillic/cmcyr/
# 
# symbols for ConTeXt macro package
#
# latin modern; CTAN:fonts/lm.
#
# a symbol font; CTAN:fonts/psfonts/marvosym/
#
# two font map entries for the mathpple package
#
# for Omega
#
# the pazo fonts; CTAN:fonts/mathpazo
#
# pxfonts (palatino extension); CTAN:fonts/pxfonts
#
# txfonts (times extension); CTAN:fonts/txfonts
#
# XY-pic fonts; CTAN:macros/generic/diagrams/xypic
#
# 7-8-9 sizes for cmex taken from TeXtrace2001 different implementation
# for font entries found in ams-cmex-bsr-interpolated.map and
# cmother-bsr-interpolated.map.
#
# ps-type1 versions for ams; CTAN:fonts/amsfonts/ps-type1
#
# ps-type1 versions for cm; CTAN:fonts/cm/ps-type1/bluesky
#
# CSTeX; http://math.feld.cvut.cz/olsak/cstex/
#
# mf -> type1 converted fonts by Taco Hoekwater
#
# Polish version of Computer Modern; CTAN:language/polish/plpsfont
#
# Polish version of Computer Concrete; CTAN:fonts/psfonts/polish/cc-pl
#
# See comments in doc/fonts/belleek/README about using mt-belleek.map
# instead of mt-yy.map:
#
# Euro Symbol fonts by Henrik Theiling; CTAN:fonts/eurosym
#
# vntex support, see http://vntex.org/
#
# Doublestroke, based on Knuth's Computer Modern Roman; CTAN:fonts/doublestroke
#
# FPL, free substitutes for the commercial Palatino SC/OsF fonts
# are available from CTAN:fonts/fpl; used by psnfss 9.2.
OAF
  (
    echo "Preparing list of files to be installed..." >&2
    $debug && echo "debug:for selected systems:" >&2
    for p in $all_systems; do
      $debug && echo "debug: checking system $p_${p}_s..."
      eval \$p_${p}_s || continue
      eval name=\"\$p_${p}_n\"
      echo "  $name" >&2
    done
    echo >&2

    $debug && echo "debug:for selected collections:" >&2
    for p in $all_collections; do
      $debug && echo "debug: checking coll $p_${p}_s..."
      eval \$p_${p}_s || continue
      eval name=\"\$p_${p}_n\"
      echo "  $name ">&2
      $list_file_func $p
    done
    echo >&2
    
    $debug && echo "debug:for selected language collections:" >&2
    for p in $all_lang_collections; do
      $debug && echo "debug: checking lang coll $p_${p}_s..."
      eval \$p_${p}_s || continue
      eval name=\"\$p_${p}_n\"
      echo "  $name ">&2
      $list_file_func $p
    done

    # e.g., GUST scheme depends on some individual packages, not just
    # collections.  Write info for those to a special .list file.
    # (Ignored for compressed installation.)
    $debug && echo "debug:for selected packages:" >&2
    :>$work_dir/PKGONLY.list
    for p in $selected_packages; do
      $list_package_func $p PKGONLY
    done
  )
}


# emacs-page
# at the end of the end ... this routine does not return.
# 
common_end_install()
{
  test -n "$platform_subdir_strip_d" && rm -f $TEXDIR/bin/$platform_subdir_strip_d 2>/dev/null

  if test "x$TEXMF" != "x$TEXDIR/texmf"; then
    $echon "Fixing permissions in $TEXMF... " >&2
    chmod -R a+r,u+w,go-w $TEXMF 2>/dev/null
    rm -f $TEXDIR/texmf
    echo "done." >&2
  fi
  $echon "Fixing permissions in $TEXDIR... " >&2
  chmod -R a+r,u+w,go-w $TEXDIR 2>/dev/null
  test -z "$TEXMFSYSVAR" ||
    chmod -R a+w $TEXMFSYSVAR ||
     warn "command 'chmod 1777 $TEXMFSYSVAR' failed"
  echo "done." >&2

  if test "$opt_varfonts" = X; then
     $echon "$opt_varfonts_dir will be used for font creation... " >&2
  else
    $echon "Setting up directories for automatic font creation... " >&2
    find "$TEXMF/fonts/pk" "$TEXMF/fonts/tfm" "$TEXMF/fonts/source/jknappen" -type d \
      -print 2>/dev/null | $XARGS chmod 1777 2>/dev/null
  fi
  find "$TEXMF/fonts/source/jknappen" -type d -print 2>/dev/null | $XARGS chmod 1777 2>/dev/null
  echo "done." >&2

  $skip_systemstuff || maketex_setoptfonts
  $skip_systemstuff || TEXMFCNF__fix_fmtutil
  $skip_systemstuff || TEXMFCNF__fix_texmf
  pd=$this_platform_fn
  bindir=
  have_system=false
  echo Testing for $TEXDIR/bin/$pd/texconfig....  >&2
  if test -x $TEXDIR/bin/$pd/texconfig; then
    have_system=true
    bindir=$TEXDIR/bin/$pd
  elif test -x $TEXDIR/bin/texconfig; then
    have_system=true
    bindir=$TEXDIR/bin
  fi
  $skip_systemstuff && have_system=false
  $skip_systemstuff || opt_do_symlinks
  $skip_systemstuff && echo "System updated successfully."  >&2
  if $have_system; then
    runsetup
    echo
    echo "Add $TEXDIR/texmf/doc/man to MANPATH." >&2
    echo "Add $TEXDIR/texmf/doc/info to INFOPATH." >&2
    echo "Most importantly, add $bindir" >&2
    echo "  to your PATH for current and future sessions." >&2
    
    if test "$pd" = i386-solaris; then
      # we should do this if i386-solaris is installed, not just if it's
      # the current platform, but that seems pretty painful.
      echo
      echo "For i386-solaris, you must also install extra libraries:"
      echo "  gzip -d <support/i386-solaris-libs.pkg.gz >/tmp/tlibs.pkg"
      echo "  pkgadd -d /tmp/tlibs.pkg"
      echo "(or the equivalent.)"
      echo
    fi
  fi

  $skip_systemstuff || greetings

  if $skip_systemstuff; then
   echo Since $TEXMFCNF_DIR/texmf.cnf already existed,
   echo we have not modified anything in that directory.
   echo Please review your setup.
  fi
  exit
}


# called from runsetup.
# 
post_install_jobs ()
{
 $debug && echo "debug:do post_install_jobs " >&2
 for j in `sort -u $work_dir/*.jobs`; do
    command=`echo $j | sed 's/.\(.*\)=.*/\1/'`
    test "x$command" = xBuildFormat && continue  # we do nothing with these

    parameter=`echo $j | sed 's/.*=\(.*\)/\1/'`
    echo "   EXECUTE $j: $command on $parameter" >&2
    case $command in
        addMap)
	    echo "Map $parameter" >> $TEXMFSYSVAR/web2c/updmap.cfg;;
        addMixedMap)
	    echo "MixedMap $parameter" >> $TEXMFSYSVAR/web2c/updmap.cfg;;
        addDvipsMap)
	    echo "p +$parameter" >> $TEXMFSYSVAR/dvips/config/config.ps;;
        addDvipdfmMap)
	    test -f $TEXMFSYSVAR/dvipdfm/config/config && echo "f $parameter" >> $TEXMFSYSVAR/dvipdfm/config/config;;
	BuildLanguageDat) ;;  # handle differently, in runsetup
    esac
done
}


# subroutine called from common_end_setup.
# 
runsetup()
{
  PATH=$bindir:/bin:/usr/bin; export PATH
  
  # We do not do anything with the BuildLanguageDat TPM:Execute instruction.
  # We just use whatever lang.dat files got installed.
  texmf_langdir=$TEXDIR/texmf/tex/generic/config
  sysvar_langdir=$TEXMFSYSVAR/tex/generic/config
  sysvar_langdat=$sysvar_langdir/language.dat
  #
  if test -f $sysvar_langdat; then
   echo "Using language.dat from TeX Live ($sysvar_langdat)."  >&2
  else
   echo Making language.dat in $sysvar_langdir  >&2
   echo " from your language selections..."  >&2
   # if no lang.dat's installed (basic scheme), don't mention missing files.
   langsel=$texmf_langdir/language.*.dat
   test -n "`ls $langsel 2>/dev/null`" || langsel=
   mkdirhier $sysvar_langdir
   cat $texmf_langdir/language.us $langsel >$sysvar_langdat
  fi

  # Update ls-R before running texconfig, or modes.mf et al. may not be found.
  echo Updating filename database with mktexlsr... >&2
  $bindir/mktexlsr --verbose

  echo "Doing post-install jobs from the packages..."
  post_install_jobs

  echo "Making map files for dvips, pdftex, dvipdfm with updmap..." >&2
  $bindir/updmap-sys --nohash --quiet \
    --cnffile=$TEXMFSYSVAR/web2c/updmap.cfg \
    --dvipsoutputdir=$TEXMFSYSVAR/fonts/map/dvips/updmap \
    --dvipdfmoutputdir=$TEXMFSYSVAR/fonts/map/dvipdfm/updmap \
    --pdftexoutputdir=$TEXMFSYSVAR/fonts/map/pdftex/updmap

  echo "Re-updating filename database with mktexlsr..." >&2
  $bindir/mktexlsr

  cat <<ENDC

=========================
Installation is finished.  (`date`)

Formats will be built for each user as needed.  If you wish to install
all formats at once, for everyone on your system, run fmtutil-sys --all.

For future global configuration, edit files in $TEXMFSYSVAR
(or run texconfig or texconfig-sys).
ENDC
}