#!/bin/bash
# eitl.sh Easy Install of TeXLive
# $Id: eitl.sh 38 2012-11-16 20:05:01Z herbert $
# v 0.04
#
# Rolf Niepraschk <Rolf.Niepraschk@gmx.de>
# Herbert Voß     <hvoss@tug.org>
#
# This script is copyright of the authors and 
# published under the LPPL 
#
# Call the script with the optional installation directory:
# ./eitl.sh 
# ./eitl.sh /opt/texlive
#
#
clear
echo "***************************************************"
echo "***         Easy Install of TeXLive             ***"
echo "***************************************************"
echo ""

TEXLIVE_DEMO=0
# 0 install all
# 1 do not install basic texlive
# 2 do not install getnonfreefonts
# 3 same as option 1 and 2
#
CREATE_PROFILE_FILES=0
# 1 creates files in /etc/profile.d/zzz-texlive.(c)sh

TEXLIVE_VERBOSE=0
# 1 for more output

restoreSystem() {
   mv ~/.bashrc.eitl ~/.bashrc 2> /dev/null
   sudo rm -r /etc/profile.d/zzz-texlive.* 2> /dev/null
}

case $# in
  0) TEXLIVE_DIR="$HOME/texlive" 
     mkdir $TEXLIVE_DIR &> /dev/null ;;
  1) if [ "$1" == "restore" ] ; then
       restoreSystem
       exit 0
     else
       TEXLIVE_DIR=$1 
       sudo mkdir -p $TEXLIVE_DIR &> /dev/null
       sudo chown -R ${LOGNAME}:`groups | cut -d" " -f1` $TEXLIVE_DIR  
     fi ;;
  *) TEXLIVE_DIR="$HOME/texlive" ;;
esac

ExitError() {
    echo "######################################################################";
    echo "### E R R O R                                                      ###";
    echo "######################################################################";
    sleep 1;
    exit 1;
}

createTLProfile() {
cat <<End_Of_File > $PROFILE_NAME
	  selected_scheme scheme-custom
	  TEXDIR $TEXLIVE_DIR/$TEXLIVE_VERSION
	  TEXDIRW $TEXLIVE_DIR/$TEXLIVE_VERSION
	  TEXMFCONFIG ~/.texlive$TEXLIVE_VERSION/texmf-config
	  TEXMFHOME ~/texmf
	  TEXMFLOCAL $TEXLIVE_DIR/texmf-local
	  TEXMFSYSCONFIG $TEXLIVE_DIR/$TEXLIVE_VERSION/texmf-config
	  TEXMFSYSVAR $TEXLIVE_DIR/$TEXLIVE_VERSION/texmf-var
	  TEXMFVAR ~/.texlive$TEXLIVE_VERSION/texmf-var
	  collection-basic 1
	  collection-bibtexextra 1
	  collection-binextra 1
	  collection-context 1
	  collection-documentation-arabic 1
	  collection-documentation-base 1
	  collection-documentation-bulgarian 1
	  collection-documentation-chinese 1
	  collection-documentation-czechslovak 1
	  collection-documentation-dutch 1
	  collection-documentation-english 1
	  collection-documentation-finnish 1
	  collection-documentation-french 1
	  collection-documentation-german 1
	  collection-documentation-italian 1
	  collection-documentation-japanese 1
	  collection-documentation-korean 1
	  collection-documentation-mongolian 1
	  collection-documentation-polish 1
	  collection-documentation-portuguese 1
	  collection-documentation-russian 1
	  collection-documentation-slovenian 1
	  collection-documentation-spanish 1
	  collection-documentation-thai 1
	  collection-documentation-turkish 1
	  collection-documentation-ukrainian 1
	  collection-documentation-vietnamese 1
	  collection-fontsextra 1
	  collection-fontsrecommended 1
	  collection-fontutils 1
	  collection-formatsextra 1
	  collection-games 1
	  collection-genericextra 1
	  collection-genericrecommended 1
	  collection-htmlxml 1
	  collection-humanities 1
	  collection-langafrican 1
	  collection-langarabic 1
	  collection-langarmenian 1
	  collection-langcjk 1
	  collection-langcroatian 1
	  collection-langcyrillic 1
	  collection-langczechslovak 1
	  collection-langdanish 1
	  collection-langdutch 1
	  collection-langfinnish 1
	  collection-langfrench 1
	  collection-langgerman 1
	  collection-langgreek 1
	  collection-langhebrew 1
	  collection-langhungarian 1
	  collection-langindic 1
	  collection-langitalian 1
	  collection-langlatin 1
	  collection-langlatvian 1
	  collection-langlithuanian 1
	  collection-langmongolian 1
	  collection-langnorwegian 1
	  collection-langother 1
	  collection-langpolish 1
	  collection-langportuguese 1
	  collection-langspanish 1
	  collection-langswedish 1
	  collection-langtibetan 1
	  collection-langturkmen 1
	  collection-langvietnamese 1
	  collection-latex 1
	  collection-latex3 1
	  collection-latexextra 1
	  collection-latexrecommended 1
	  collection-luatex 1
	  collection-mathextra 1
	  collection-metapost 1
	  collection-music 1
	  collection-omega 1
	  collection-pictures 1
	  collection-plainextra 1
	  collection-pstricks 1
	  collection-publishers 1
	  collection-science 1
	  collection-texinfo 1
	  collection-texworks 1
	  collection-xetex 1
	  from_dvd 0
	  option_autobackup 1
	  option_backupdir tlpkg/backups
	  option_desktop_integration 1
	  option_doc 1
	  option_file_assocs 1
	  option_fmt 1
	  option_letter 0
	  option_path 0
	  option_post_code 1
	  option_src 1
          option_sys_bin $TEXLIVE_DIR/$TEXLIVE_VERSION/bin/$TL_PLATFORM
          option_sys_info $TEXLIVE_DIR/$TEXLIVE_VERSION/texmf/doc/info
          option_sys_man $TEXLIVE_DIR/$TEXLIVE_VERSION/texmf/doc/man
	  option_w32_multi_user 0
	  option_write18_restricted 1
	  portable 0
End_Of_File
}

createSHProfile() {
cat <<End_Of_File > zzz-texlive.sh
#
#    /etc/profile.d/zzz-texlive.sh 
#
TL_DIR="$TEXLIVE_DIR/$TEXLIVE_VERSION"

arch=\`arch\`
case \$arch in
    i?86) arch=i386;;
esac
export PATH=\${TL_DIR}/bin/\${arch}-linux:\$PATH
export MANPATH=\${TL_DIR}/texmf/doc/man:\$MANPATH
export INFOPATH=\${TL_DIR}/texmf/doc/info:\$INFOPATH
unset TEXINPUTS
unset TEXMFCONFIG

unset x
End_Of_File
}

createCSHProfile() {
cat <<End_Of_File > zzz-texlive.csh
#
#    /etc/profile.d/zzz-texlive.csh 
#

set TL_DIR="$TEXLIVE_DIR/$TEXLIVE_VERSION"

set arch=\`arch\`
switch ( \$arch )
  case i?86: 
    set arch=i386
endsw
setenv PATH \${TL_DIR}/bin/\${arch}-linux:\$PATH
setenv MANPATH \${TL_DIR}/texmf/doc/man:\$MANPATH
setenv INFOPATH \${TL_DIR}/texmf/doc/info:\$INFOPATH
unset TEXINPUTS
unset TEXMFCONFIG
End_Of_File
}

echo -n "Detect the current Linux distribution: "
if [ -e /etc/debian_version ] ; then
  LOCAL_LINUX_DISTRO=1
elif [ -e /etc/SuSE-release ] ; then
#  if [ `grep -c -i suse /etc/os-release` -gt 0 ] ; then
    LOCAL_LINUX_DISTRO=0
#  fi
else
  LOCAL_LINUX_DISTRO=-1 # unknown
fi

case $LOCAL_LINUX_DISTRO in
  0) echo "SuSE Linux" ;;
  1) echo "Debian/Ubuntu Linux" ;;
 -1) echo " We have an unknown Linux distro! We will quit :-("
     exit 1 ;;
esac

TEMP_DIR="/tmp/texlive"
trap "rm -rf $TEMP_DIR" 1 2 3 7 13 15
#voss@shania:~/Linux-Unix/eitl> trap -l
#   1) SIGHUP	 	 2) SIGINT	 3) SIGQUIT	 4) SIGILL	 5) SIGTRAP
#   6) SIGABRT	 	 7) SIGBUS	 8) SIGFPE	 9) SIGKILL	10) SIGUSR1
#  11) SIGSEGV		12) SIGUSR2	13) SIGPIPE	14) SIGALRM	15) SIGTERM
#  16) SIGSTKFLT	17) SIGCHLD	18) SIGCONT	19) SIGSTOP	20) SIGTSTP
#  21) SIGTTIN		22) SIGTTOU	23) SIGURG	24) SIGXCPU	25) SIGXFSZ
#  26) SIGVTALRM	27) SIGPROF	28) SIGWINCH	29) SIGIO	30) SIGPWR
#  31) SIGSYS		34) SIGRTMIN	35) SIGRTMIN+1	36) SIGRTMIN+2	37) SIGRTMIN+3
#  38) SIGRTMIN+4	39) SIGRTMIN+5	40) SIGRTMIN+6	41) SIGRTMIN+7	42) SIGRTMIN+8
#  43) SIGRTMIN+9	44) SIGRTMIN+10	45) SIGRTMIN+11	46) SIGRTMIN+12	47) SIGRTMIN+13
#  48) SIGRTMIN+14	49) SIGRTMIN+15	50) SIGRTMAX-14	51) SIGRTMAX-13	52) SIGRTMAX-12
#  53) SIGRTMAX-11	54) SIGRTMAX-10	55) SIGRTMAX-9	56) SIGRTMAX-8	57) SIGRTMAX-7
#  58) SIGRTMAX-6	59) SIGRTMAX-5	60) SIGRTMAX-4	61) SIGRTMAX-3	62) SIGRTMAX-2
#  63) SIGRTMAX-1	64) SIGRTMAX	

MAX_WGET_TRIES=5 
TL_INSTALL_SCRIPT="install-tl-unx.tar.gz"
TL_NET="http://mirror.ctan.org/systems/texlive/tlnet"
GENERIC_URL="${TL_NET}/$TL_INSTALL_SCRIPT"
#tl_install_url={$GENERIC_URL}
#LOCAL_SYSTEM=`uname -m`
# A server shouldn't need more than $MAX_TIME sec for download of $TL_INSTALL_SCRIPT
# 2,5MB at 1MB/s =~ 20 sec
MAX_TIME=20
WGET_TIMEOUT=20

# We need english messages from the program calls and the dot for decimals.
unset LC_ALL
LANG=C

echo -n "Create directory $TEMP_DIR"
mkdir -p "$TEMP_DIR"
echo " ... done"
cd "$TEMP_DIR"
if ! command -v wget >/dev/null 2>&1; then
    echo "$0: need the wget package installed to run this. Please install it." >&2
    exit 1
fi

#
# First we get the install script from a mirror with testing of the
# download speed. We save the mirror's URL.
#

for i in `seq 0 $MAX_WGET_TRIES`; do
  while true; do
    x=1
    /bin/rm -f $TL_INSTALL_SCRIPT*
    echo -n "Get the install script from a CTAN mirror ..."
    /usr/bin/wget --timeout=$WGET_TIMEOUT $GENERIC_URL &> wgetLog
    if [ $? -eq 0 ] ; then    
      echo " done"
      thisURL=`grep -i location wgetLog| cut -d" " -f2`
#      thisURL=$(echo $wgetLog | sed -e 's#^.*Found Location: \([^ ]*\) .*$#\1#')
      tl_install_url=${thisURL%/*}
#      tl_install_url=$(echo $thisURL | sed -e "s#\(.*\)$TL_INSTALL_SCRIPT#\1#")
      thisTime=`grep "100%"  wgetLog | cut -d"=" -f2 | tr -d "s"` | cut -d"." -f1
#      thisTime=$(echo $wgetLog | sed -e 's#^.* \([^ ]*\)$#\1#')
#      thisTime=$(printf %0.f $thisTime)
      if [ $TEXLIVE_VERBOSE -gt 0 ]; then
        echo "thisURL: $thisURL"
        echo "tl_install_url: $tl_install_url"
        echo "thisTime: $thisTime sec"
      fi
      if (( thisTime > MAX_TIME )); then
        echo "Slow server! Next try!"
      else
        x=0
        echo -e "Success! This is a good server:\n  $tl_install_url"
        break
      fi
    else
      echo "Server not accessible. Next try!"
    fi
  done
  if [ $x -eq 0 ]; then 
    break
  fi
  echo "I'll use : $tl_install_url"
done

if [ $i -eq $MAX_WGET_TRIES ]; then 
  echo "More than $MAX_WGET_TRIES tries without effect. I'll give it up!"
  ExitError
fi

echo -n "Unpack the shell script"
gzip -d -c < $TL_INSTALL_SCRIPT | tar xf - 
echo " ... done"

#echo -n "Get the current version of TeXLive ... "
#TLCONFIG="${tl_install_url}/tlpkg/TeXLive/TLConfig.pm"
#TEXLIVE_VERSION=`wget -O- -q ${TLCONFIG} | sed -ne '/^ *\$ReleaseYear *=/s/.*= *\([0-9]*\) *;$/\1/p'`
#echo "done"

TEXLIVE_INSTALL_PREFIX="$TEXLIVE_DIR"

echo -n "go into the install directory ... "
workingdir=`tar ztf install-tl-unx.tar.gz | head -1`
cd "$workingdir"
echo "done"
echo -n "get the TeXLive version: "
TEXLIVE_VERSION=`./install-tl -version | grep version | cut -d " " -f 5`
#`./install-tl -version | sed -r 's#^.+ ([^ ]) *#\1#'` 

echo "$TEXLIVE_VERSION"
TL_PLATFORM=`./install-tl -print-platform`
echo "We have the platform: $TL_PLATFORM"
PROFILE_NAME="${TEXLIVE_DIR}/tl-${TEXLIVE_VERSION}.profile"
echo -n "Create profile ${PROFILE_NAME} for TeXLive ... "
createTLProfile
echo "done"

if [ $TEXLIVE_DEMO -eq 0 ]
then
echo "We will delete an existing local TeX installation. Have to run it with sudo ... "
case $LOCAL_LINUX_DISTRO in
  0) sudo zypper rm -y texlive;;
  1) sudo apt-get purge texlive ;;
esac
echo "done"
fi

echo "Now we start the main install procedure. Time enough to get a cup of coffee ... "
echo "Repository: $tl_install_url"
echo "Profile   : $PROFILE_NAME"
if [ $TEXLIVE_DEMO -gt 0 ]
then
  echo "sorry, no cup of coffee, we have only the demonstration mode ... :-)"
else
  ./install-tl -repository $tl_install_url --profile=$PROFILE_NAME
fi
echo "TeXLive installation fished :-)"

echo -n "Create path setting and alias names ... "
if [ $CREATE_PROFILE_FILES -eq 0 ] ; then
  cp ~/.bashrc ~/.bashrc.eitl 2> /dev/null
  echo "export PATH=$TEXLIVE_DIR/$TEXLIVE_VERSION/bin/$TL_PLATFORM:\$PATH" >> ~/.bashrc
  echo "export MANPATH=$TEXLIVE_DIR/$TEXLIVE_VERSION/texmf/doc/man:\$MANPATH" >> ~/.bashrc
  echo "export INFOPATH=$TEXLIVE_DIR/$TEXLIVE_VERSION/texmf/doc/info:\$INFOPATH" >> ~/.bashrc
  echo "unset TEXINPUTS" >> ~/.bashrc
  echo "unset TEXMFCONFIG" >> ~/.bashrc
  source ~/.bashrc
fi
echo "alias updmap='updmap-sys'" >> ~/.alias
echo "alias fmtutil='fmtutil-sys'" >> ~/.alias
echo "done" 
source ~/.alias

echo "Set new path for local actions ... "
export PATH=$TEXLIVE_DIR/$TEXLIVE_VERSION/bin/$TL_PLATFORM:$PATH 
echo $PATH
echo "done"
if [ $TEXLIVE_DEMO -lt 2 ]
then
echo "Now install the non free fonts ..."
wget -q http://tug.org/fonts/getnonfreefonts/install-getnonfreefonts
texlua ./install-getnonfreefonts
getnonfreefonts -a
echo "... done"
fi

rm -f ./install-getnonfreefonts


if [ $TEXLIVE_DEMO -eq 0 ]
then
echo "Now we install two GUIs, TeXmaker and TeXworks ... "
echo "At first we have to fool the system, that its own TeX is installed."
echo "For installing packages we have to be a superuser. Running sudo ... "
case $LOCAL_LINUX_DISTRO in
  0)
     wget -q http://mirror.ctan.org/support/texlive/texlive-dummy/openSUSE/texlive-dummy-2012.9999-1.noarch.rpm
     sudo rpm -U ./texlive-dummy-2012.9999-2.noarch.rpm
     sudo rm -f /etc/profile.d/zzz-texlive*
     sudo zypper install -y texworks
     sudo zypper install -y texmaker ;;
  1) wget http://archiv.dante.de/~herbert/Ubuntu/texlive-dummy_1.0_all.deb
     wget -q http://archiv.dante.de/~herbert/Ubuntu/texlive-dummy.ctl
     sudo dpkg -i texlive-dummy_1.0_all.deb &> /dev/null
     sudo apt-get install ./texlive-dummy_1.0_all.deb 
     sudo apt-get install texworks
     sudo apt-get install texmaker
esac
fi

if [ $CREATE_PROFILE_FILES -gt 0 ] ; then
  echo "Create as root system profiles /etc/zzz-texlive.(c)sh ... "
  createSHProfile
  createCSHProfile
  sudo rm -f /etc/profile.d/zzz-texlive*
  sudo mv zzz-texlive.sh /etc/profile.d/
  sudo mv zzz-texlive.csh /etc/profile.d/
  echo "done"
fi
echo -n "We remove all temporary files and directories ... "
rm -rf "$TEMP_DIR"
echo "... done"

cd ~

#echo "I'll run the TeXLive Update Manager, to get the latest file versions ... "
#$TEXLIVE_DIR/$TL_YEAR/bin/$TL_PLATFORM/tlmgr --self --all update > /dev/null
#echo "... done"
clear
echo "*** Now logout and login again ***"
echo "Then all is done and TeXLive should work!"

exit 0


#http://tug.org/fonts/getnonfreefonts/install-getnonfreefonts
#ftp://dante.ctan.org/tex-archive/support/texlive/texlive-dummy/openSUSE/texlive-dummy-2012.9999-1.noarch.rpm



