#!/bin/bash

###
### @(#) install-tuc-cd.sh -- Try to install the TUC CD classes and packages into a TeXLive TDS structure
###
### Time-stamp:  <2017-11-29 11:11:49 tmjb>
###
###
### @(#) $Id: $
### @(#) $Keywords: TEXLive, TDS, TUC, Technische Universität Clausthal, Clausthal University of Technology, TUC-CD, Corporate Design $
###
###
###          File: /Users/tmjb/Documents/LaTeX/Source/TUC/tuc-cd/install-tuc-cd.sh
###       Project: TUC-CD
###     Description: This script tries to determine, where your locals
###                TeXLive-Systems stores its local, site wide TeX
###                files ($TEXMFLOCAL).  If you are allowed to write
###                to this directory, it will genererate the needed
###                subdirectories and will store the TUC-CD styles and
###                classes as well as the according documentation into
###                that directories.  If it succedded successful, it
###                will update the TeX database of files.  If you
###                aren't allowed to write into the site wide local
###                TeX directory, it will store the class- and package
###                files as well as the documentation into your
###                personal TeX directory ($TEXMFHOME).
###       Version: $Revision: $
###        Author: tmjb -- Jan Braun <braun@rz.tu-clausthal.de>
###    Maintainer: tmjb -- Jan Braun <braun@rz.tu-clausthal.de>
### Creation-Date: Mon Nov 27 2017 -- Jan Braun <braun@rz.tu-clausthal.de>
###     Copyright: (c) 2017 Jan Braun
###

### ------------------------------------------------------ &Change Log ---
###
### $Log: $


### ======================================================== &Preamble ===

## The name of this script, as called from the user.  Basename strips
## the path and returns only the name of the script itself.
self=`basename $0`

### Some variables, that are used on different locations of this
### script.

## This variables define the remaining part of the path to the
## documentation directory and to the LaTeX files.  Of course, you
## have to start with the base of the installation directory.
DOCDIR=doc/tex/latex/TUC
LTXDIR=tex/latex/TUC

## TeXLive is using some scripts to manage different things.  It is a
## good idea, to store the name of the needed scripts in this
## variables, just in case, they might change in the future.  If this
## happens, just adopt these variables, instead of rewriting this
## script.
TLMGR="tlmgr"
UPDATEDB="mktexlsr"
CHECKDB="kpsewhich"

## Running the TLMGR script is time consuming.  Instead of running
## this script multiple times, run it once and store the results in
## a temporary file.  This variables define, which diretory to use and
## how to name the temporary file.
TMPDIR="/tmp"
date=`date +%Y-%m-%d-%h-%M-%s`
TMPFILE="texlive-conf-$date"


### ======================================================= &Functions ===

### ----------------------------------------------------------- &Usage ---
###
### How to use this script
function usage () {
    cat <<EOF
Usage:
	$self [-h|--help]
	$self [-c|--check]

$self install LaTeX classes and packages for 
Clausthal University of Technology Corporate Design 

Options:
	-h|--help: this short info

	-c|--check: Check if TUC-CD package is successfully installed


$self will try install the classes and packages, which belong to the
TUC-CD package  into a direcotry, which is read by your local TeXLive
installation.  

It first checks, if you are allowed, to write into the local and
system wide installation directory, which is usally called
TEXMFLOCAL.  If you are allowed to write to this directory, it will
create
   1) $TEXMFLOCAL/tex/latex/TUC/
and install the LaTeX files, packages and classes into that
directory.
   2) $TEXMFLOCAL/doc/tex/latex/TUC/
to copy the according documentation files.  If it succeeded correctly,
it will update the database of your TeX-System, in order to find the
freshly installed files.

If you are not allowed, to use the site wide directory, it will copy
the LaTeX files as well as the documentation files into your personal
TeX directory, which is TEXMFHOME.

You can use $self afterwards, to check if the LaTeX file
tuc-thesis.cls will be found by LaTeX, by adding the option --check or
-c (for short).  This will run kpsewhich latex tuc-thesis.cls, which
you can also run manually, if you prefer.

Return-Values:
$self will return 0 if no error occured.

It will return 1, if it could not find the copied TUC-CD files.

In every other erronous case, it will return 2 or higher.


EOF
}



### ----------------------------------------------------- &Get-Options ---
###
### Get the command line options

function get_options () {
    while [ $# -gt 0 ]; do
	case $1 in
	    -h|--help)
		usage
		exit 0
	    ;;
	    -c|--check)
		check_install
		exit 0
	    ;;
	    *)
		usage
		exit 2
	esac
    done
}



### ---------------------------------------------------- &Search-Local ---
### 
### Search for the local site wide TeX directory, called TEXMFLOCAL.
### In the rare case, that there is more than one directory, which can
### hold the local site wide TeX files, the tool tlmgr will return
### something like this result:
### "TEXMFLOCAL=/usrlocal/texmf/texmf-local:/opt/texmf-local".  This
### is a usual multiple path definition, where each possible path is
### delimited by an colon ":".  To keep things simple, I decied to
### just test for the first path element, by stripping everything from
### the first colon to the end of the line (which is regexp ":.*$").
### The beginnin text "TEXMFLOCAL=" must alos be removed from the
### result.  Hence I call SED with two scripts.  I tried to combine
### the regexps into one regexp: "'s/TEXMFLOCAL=\(.*\):.*$/\1/'" but
### that did not work reliably to me.  Maybe the regexp should be more
### defined?

function search_local () {
    TEXMFLOCAL=`cat $TMPDIR/$TMPFILE | grep TEXMFLOCAL | sed -e 's/TEXMFLOCAL=//' -e 's/:.//'`
}



### ----------------------------------------------------- &Search-Home ---
### 
### Search for the HOME TeX directory, called TEXMFHOME.  Same
### technique as with TEXMFLOCAL, see above.

function search_home () {
    TEXMFHOME=`cat $TMPDIR/$TMPFILE | grep TEXMFHOME | sed -e 's/TEXMFHOME=//' -e 's/:.*$//'`
}



### ------------------------------------------------------ &Check-Conf ---
### 
### Check, if any kind of TeXLive is present on this computer.  Do so,
### by running the TeXlive Manager to read its current configuration.
### Store the result (if any) in the temporary file.

function check_conf () {
    echo -n "Checking for TeXLive ... "
    if ! $TLMGR conf > $TMPDIR/$TMPFILE 2> /dev/null ; then
	echo "Fehler: konnte die Konfiguration des TeXLive-Systems nicht auslesen!"
	exit 2
    fi

    ## Now use this file and get the site wide and personal TeX
    ## directories.
    echo -n "searching for directories ... "
    search_local
    search_home
}



### -------------------------------------------------------- &Clean-Up ---
###
### Clean up before ending this script.

function clean_up () {
    rm $TMPDIR/$TMPFILE
}



### --------------------------------------------------- &Check-Install ---
### 
### Check, if the files have been installed successfully.  To do this,
### use the kpsesearch command and search for one of the freshly
### installed files.

function check_install () {
    $CHECKDB latex tuc-thesis.cls > /dev/null 2>&1
    if [ $? -eq 1 ]; then
	## Success
	echo "Installation erfolgreich"
    else
	## Fail!
	echo "FEHLER: Dateien konnten nicht gefunden werden!"
	exit 1
    fi
}



### ------------------------------------------------------ &Copy-Files ---
### 
### Copy the LaTeX files into the LaTeX directory and the
### documentation into the doc directory

function copy_files () {
    cp -rp doc $INSTDIR/$DOCDIR || exit 3
    cp -rp latex $INSTDIR/$LTXDIR || exit 3
    echo "done!"
    
    ## Don't to forget to update the database.  In some rare cases,
    ## the system might be configured such, that even the local user
    ## directories are hashed!  So run it even when the files have
    ## been installed into the HOME directories.  Running the update
    ## is a good idea in any case.
    update_db
}



### ----------------------------------------------- &Check-Permissions ---
### 
### Check, if the user is allowed to use the site local diretory.  To
### check, just create a new temporary directory, which will be
### deleted immediately afterwards.  To ensure, the site doesn't
### contain this rather stupid directory, this function will also
### check, if a diretory with similar name will exist.  In case it
### exist, it won't check the permissions in the site wide directory,
### but use the users HOME directory as installation directory.

function check_permissions () {
    INSTDIR=''
    testdir="$TEXMFLOCAL/testdir-$date"

    ## Check, if the testdir does not exist!
    if [ ! -d $TEXMFLOCAL/$testdir ]; then
	if mkdir $TEXMFLOCAL/$testdir 2> /dev/null ; then
	    ## Hurray!  The user is permitted, to write to site local
	    ## directory
	    ##
	    ## Remove the otherwise useless testdir!
	    rmdir $TEXMFLOCAL/$testdir
	    INSTDIR=$TEXMFLOCAL
	else
	    ## use the HOME dir to install the files.
	    INSTDIR=$TEXMFHOME
	fi	       
    fi
    echo -n "Installing in $INSTDIR ... "
}



### ----------------------------------------------------- &Create-Dirs ---
### 
### Create the needed dirs, if they are missing.  By using the "-p"
### option, each directory of the given path, that is non existant,
### will be created.  (Otherwise, only the last directory of the given
### path will be created, only if the complete path is existing!)

function create_dirs () {
    if [ ! -d $INSTDIR/$DOCDIR ]; then
	mkdir -p $INSTDIR/$DOCDIR || exit 2
    fi
    if [ ! -d $INSTDIR/$LTXDIR ]; then
	mkdir -p $INSTDIR/$LTXDIR || exit 2
    fi
}



### ------------------------------------------------------- &Update-DB ---
###
### Update the database

function update_db () {
    echo -n "Updating database ... "
    $UPDATEDB > /dev/null 2>&1 || exit 4
    echo "done!"
}



### ============================================================ &Main ===
get_options $*

check_conf

check_permissions

create_dirs

copy_files

clean_up

echo
exit 0

### ============================================================= &EOF ===
