#!/bin/bash

###
### @(#) generate-letter-config -- Generate letterheads
###
### Time-stamp:  <2019-11-19 11:10:00 tmjb>
###
###
### @(#) $Keywords: TU CLausthal, TUC, Corporate Design, CD, LaTeX, KOMA-Script, Letter, Brief, Letterhead, Briefkopf, Installation $
###
###
###          File: /Users/tmjb/lib/texmf/tex/latex/TUC/TUC-Letter/Letterheads/generate-letter-config.sh
###       Project: TU CLausthal Corporate Design for Letters
###   Description: This script will create a bunch of letterhead
###                definition files.  It will ask for the missing
###                entries
###       Version: 0.8.0
###        Author: tmjb -- Jan Braun <jan.braun@tu-clausthal.de>
###    Maintainer: tmjb -- Jan Braun <jan.braun@tu-clausthal.de>
### Creation-Date: Wed Nov 16 2016 -- Jan Braun <braun@rz.tu-clausthal.de>
###     Copyright: (c) 2016 Jan Braun
###


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

### ------------------------------------------------------- &Variables ---
## Filename and directory to use
TEXMFDIR=/Users/tmjb/Library/texmf
LCODIR=$TEXMFDIR/tex/latex/TUC/TUC-Letter/Letterheads/
ts=`date "+%Y-%m-%d %H:%M:%S"`
LATEXDATE=`date "+%Y/%m/%d"`
TIMESTAMP="$ts $USER"
REV="0.8.0"
self=`basename $0`

    

### ------------------------------------------------------- &Functions ---

### ........................................................... &usage ...
###
### print out this short help text.
usage () {
    cat <<EOF

$self generates a configuration file, to be used with scrlettr2.cls
from LaTeX, to produce a letterhead for Clausthal University of
Technology.

Usage:
       $self [-h|--help]
       $self [-t|--testprint | -d|--dir <config-dir>] -p|--personal <username> -i|--inst <institute>
       $self [-t|--testprint | -d|--dir <config-dir>] -i|--inst <institute> -f|--faculty <faculty>
       $self [-a|--all | -t|--testprint]

$self will either try to create configuration files for all know
institutes or it will create the configuration file for a single
institute.

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

    -p | --personal: generate personal letter head
    -i | --inst <filename> short name of the institute
    -f | --faculty <faculty> faculty name
    -a | --all: generate all files

    -d | --dir <config-dir>: Path to store the config file in
    -t | --testprint: generate a LaTeX file, to check if the
                      configuration file works as aspected

Optional Arguments
    <config-dir> path, where the config file shall be stored
                 in.  Usually that will be something like 
                 \$TEXMFHOME

Mandatory Arguments
    <username> short name of the user
    <institute> short filename of the institute
    <faculty> faculty, the institute belongs to

Usually $self will be called, to create the users personal letterhead
configuration to be used with the TUC-Letter class.  $self will check,
if the given <institute> abbreviation could be found in the local
TeX installation.  If that is the case, it will only ask questions
for details needed to create the personal letter head configuration.
If the letter configuration file for the institute can't be found,
$self will also ask details about the institute itself.  The given
username will also be the name of the created configuration filename,
thus you must not add ".lco"

$self can also be called with the short file name and category of the
institute, for which to generate the scrlettr2 configuration file.
You must not give the filename extension ".lco", as $self will
automatically add that itself.

Lets assume, you want to create a brandnew configuration file for the
newly established "Institut for Penguinresearch".  The offical
abbreviation of this institute was defined to be "ipr".  The institute
shall be located into the "faculty-4".

In that case, the $self should be called

     $self -i ipr -f faculty-4

$self will ask some questions, i.e.: the full name of the institute,
its institutehead, the  building ID, office telephone and fax number
and the office mail address as well as the institute URL.

Afterwards it stores the new configuration file as
Letterheads/<faculty>/<filename>.lco.  If you don't specify the -d or
--dir option, $self will use \$TEXMFHOME as default.  This default was
set by your LaTeX installation.  In your case, it defaults to
$TEXMFHOME.

When the configuration file for the Penguin Reasearch institute is
already present, you can use $self to create your personal letter
configuration file by calling

    $self -p $USER -i ipr 

If you want to store the newly configured ipr or personal letterheada
file in /usr/local/texmf/tex/latex/config directory, than you'll have
to call $self like this:

     $self -d /usr/local/texmf/tex/latex/config -i ipr -f faculty-4

or

     $self --dir /usr/local/texmf/tex/latex/config -i ipr -f faculty-4

You can also use the -t or --testprint option.  If you specify this
option, $self will also create an testletter.tex file in your actual
working directory.  Run LaTeX on that file, to produce a blank
letterhead, to check if every variable was set correctly.  The -d and
--dir-switch do not affect the directory, in which the LaTeX document
will be created!

     $self -t -i ipr -f faculty-4

or 

    $self --testprint -i ipr -f faculty-4

The -a or --all switch will produce confguration files for all known
institutes.  It will run in a loop and create a file for each listed
institute, asking the above listed questions.  After it completed the
first institute, it will start a fresh turn for the next institute.
In that case, it will try to store the configuration files in the
systemwide LaTeX configuration directory, which is normaly defined in
\TEXMFLOCAL, which is in your case $TEXMFLOCAL.
You usually need adminstrative permissions, to write in that
directory.  

If you don't want to generate the config files in that directory, you
still can override the default by means of the -d or --dir option.

You may combine the -a or --all switch with the -t or --testprint
switch as well.  In that case, a somewhat bigger LaTeX testfile will
be produced, containing an empty letter for each created config file.

This is $self, version $REV

EOF
}


### ..................................................... &get_options ...
###
### Check the number of options.
get_options () {
    while [ $# -gt 0 ]; do
        case "$1"  in
            -d|--dir)
                DIR=$2
                shift
                ;;
            -a|--all)
                ALL=true
                ;;
	    -t|--testprint)
		TEST=true
		;;
	    -i|--inst)
		institute=$2
		shift
		;;
	    -f|--faculty)
		faculty=$2
		shift
		;;
	    -p|--personal)
		personal=$2
		shift
		;;
	    -v|--version)
		print_version
		exit 0
		;;
            -h|--help)
                usage
                exit 0
                ;;
        esac
        shift
    done
    # Just  a short check, if every mandatory argument was specified!
    if [ ! $ALL ]; then
	if [ ! -z $personal ] ; then
	    if [ -z $institute ] ; then
		usage
		exit 1
	    else
		file=$USER
	    fi
	else
	    if [ -z $faculty -a -z $institute ]; then
		usage
		exit 1
	    fi
	fi
    fi
}


### ................................................... &print_version ...
### 
### print the version of this script.
function print_version() {
    cat <<EOF

This is file $self, version $REV.

For more information try

    $self --help

EOF
}


### ...................................................... &get_config ...
### 
### Try to get the configuration by testing tlmgr.  Run the tlmgr and
### store its output in an temporary file, to speed up the process.

function get_config() {
    tmdir="/tmp"
    confdate=`date "+%Y$m%d%H%M%S"`
    tmpconf="$tmdir/tlmgr-conf-$confdate.conf"
    
    if [ ! -f $tmpconf ]; then
	if which tlmgr > /dev/null 2>&1 ; then
	    echo -n "Checking actual configuration ... "
	    tlmgr conf > $tmpconf
	    TEXMFHOME=`grep < $tmpconf TEXMFHOME`
	    TEXMFLOCAL=`grep < $tmpconf TEXMFLOCAL`
	    if ! rm -f $tmpconf ; then
		echo "ERROR: Could not delete temporary configuration file!"
		exit 2
	    fi
	    echo "done"
	fi
    else
	echo "ERROR: Temporary configuration file does exist!"
	echo "ERROR: Remove or rename $tmpconf by hand and try again."
	exit 3
    fi
}



### ................................................... &write_lcofile ...
###
### write a single file and -- while doing that -- fill in some
### variables.
write_lcofile () {
    cat > $LCODIR/$LCOFILE  <<EOF
%%%
%%% @(#) $file.lco -- Briefkopf-Definitionen für $inst
%%%
%%%     Time-stamp:  <$TIMESTAMP>
%%%
%%%
%%% @(#) \$Keywords: TU CLausthal, TUC, Corporate Design, CD, LaTeX, KOMA-Script, Letter, Brief, Letterhead, Briefkopf, $inst $
%%%
%%%
%%%           File: $TEXMFLOCAL/tex/latex/TUC/TUC-Letter/Letterheads/$faculty/$file.lco
%%%        Project: TU Clausthal Corporate Design for Letters
%%%    Description: Diese Datei definiert eine Reihe von Variablen, die
%%%                 zur Erstellung eines individuellen Briefkopfes für
%%%                 das Institut $inst benötigt werden.
%%%         Author: tmjb -- Jan Braun <braun@rz.tu-clausthal.de>
%%%     Maintainer: tmjb -- Jan Braun <braun@rz.tu-clausthal.de>
%%%  Creation-Date: Wed Nov 16 2016 -- Jan Braun <braun@rz.tu-clausthal.de>
%%%      Copyright: (c) 2016--2019 Jan Braun
%%%
%%%

%%%
%%% ===================================================== &Definitions ===

%%% ---------------------------------------------------- &General Info ---
%% 
%% Was wird in dieser Datei zur Verfügung gestellt?  (Datum, Name der
%% Datei, Kurzbeschreibung
\ProvidesFile{$file.lco}[$LATEXDATE $REV $file.lco (Letter head definition for $inst, Clausthal University of Technology)]

%% Die allgemeinen Angaben zur TU Clausthal werden mit Hilfe des
%% nachfolgenden Befehls geladen
\LoadLetterOption{tuc}

%%% --------------------------------------------- &Institute Variables ---
%% 
%% Name des Institutes oder Einrichtung
\setkomavar{institute}{$inst}
%% 
%% Direktor/Leiter des Instituts oder der Einrichtung
\setkomavar{institutehead}{$head}
%% 
%% Die Angaben der beiden nachfolgenden Variablen entstammen der
%% Webseite
%% http://www.tu-clausthal.de/info/campuskarte/index.de.php?Verzeichnis=1  
%% 
%% Die neue Gebäude-Nummer
\setkomavar{buildingid}{$id}
%% 
%% Die Besuchsanschrift des Gebäudes.  Der Eintrag kann mehrere Zeilen
%% enthalten.  Die Zeilen sind wie üblich mit dem doppelten Backslash
%% voneinander zu trennen.
\setkomavar{visitoraddress}{$addr\\\\38678 Clausthal-Zellerfeld}%
%% 
%% Angaben zum Telefon, Fax, der Mailadresse des Geschäftszimmers,
%% sowie zur Webseite des Instituts
EOF
    if [ -z "$tel" ]; then
	cat >> $LCODIR/$LCOFILE <<EOF
\setkomavar{officephone}{}%
EOF
    else
	cat >> $LCODIR/$LCOFILE <<EOF
\setkomavar{officephone}{(0\,53\,23)\,72-$tel}%
EOF
    fi
    if [ -z "$fax" ]; then
	cat >> $LCODIR/$LCOFILE <<EOF
\setkomavar{officefax}{}%
EOF
    else
	cat >> $LCODIR/$LCOFILE <<EOF
\setkomavar{officefax}{(0\,53\,23)\,72-$fax}%
EOF
    fi
    if [ -z "$mail" ]; then
	cat >> $LCODIR/$LCOFILE <<EOF
\setkomavar{officeemail}{}%
EOF
    else
	cat >> $LCODIR/$LCOFILE <<EOF
\setkomavar{officeemail}{\url{$mail}}%
EOF
    fi
    if [ -z "$url" ]; then
	cat >> $LCODIR/$LCOFILE <<EOF
\setkomavar{instituteurl}{}%
EOF
    else
	cat >> $LCODIR/$LCOFILE <<EOF
\setkomavar{instituteurl}{\url{$url}}%
EOF
    fi
    cat >> $LCODIR/$LCOFILE <<EOF

%%% ============================================================= &EOF ===

%%% Local Variables:
%%% mode: LaTeX
%%% TeX-master: 
%%% TeX-parse-self: nil
%%% TeX-auto-save: t
%%% End:

EOF
}



### .......................................... &write_personal_lcofile ...
### 
### Write the information into a file.

function write_personal_lcofile() {
    cat > $localpath/$file.lco <<EOF
%%%
%%% @(#) $file.lco -- Briefkopf-Definitionen für $fromname
%%%
%%%     Time-stamp:  <$ts>
%%%
%%%
%%% @(#) \$Keywords: TU CLausthal, TUC, Corporate Design, CD, LaTeX, KOMA-Script, Letter, Brief, Personal Letterhead, persönlicher Briefkopf, $inst $
%%%
%%%
%%%           File: $localpath/$file.lco
%%%        Project: TU Clausthal Corporate Design for Letters
%%%    Description: Diese Datei definiert eine Reihe von Variablen, die
%%%                 zur Erstellung eines individuellen Briefkopfes für
%%%                 den Nutzer $fromname benötigt werden.
%%%         Author: tmjb -- Jan Braun <braun@rz.tu-clausthal.de>
%%%     Maintainer: tmjb -- Jan Braun <braun@rz.tu-clausthal.de>
%%%  Creation-Date: $LATEXDATE -- $fromname <$frommail>
%%%      Copyright: (c) 2016--2019 Jan Braun
%%%
%%%

%%%
%%% ===================================================== &Definitions ===

%%% ---------------------------------------------------- &General Info ---
%% 
%% Was wird in dieser Datei zur Verfügung gestellt?  (Datum, Name der
%% Datei, Kurzbeschreibung
\ProvidesFile{$file.lco}[$LATEXDATE $REV $file.lco (Letter head definition for user $fromname, Clausthal University of Technology)]

%% Die allgemeinen Angaben zur TU Clausthal werden mit Hilfe des
%% nachfolgenden Befehls geladen
\LoadLetterOption{$inst_lco}

%%% ---------------------------------------------- &Personal Variables ---
%% 
%% Some individual variables
EOF
    if [ ! -z "$department" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{department}{$department}
EOF
    fi
    if [ ! -z "$departmenthead" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{departmenthead}{$departmenthead}
EOF
    fi
    if [ ! -z "$fromname" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{fromname}{$fromname}
EOF
    fi
    if [ ! -z "$fromphone" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{fromphone}{+49\,53\,23\,/\,72-$fromphone}
EOF
    fi
    if [ ! -z "$fromfax" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{fromfax}{+49\,53\,23\,/\,72-$fromfax}
EOF
    fi
    if [ ! -z "$fromshortmobilephone" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{fromshortmobilephone}{+49\,53\,23\,/\,72-$fromshortmobilephone}
EOF
    fi
    if [ ! -z "$frommobilephone" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{frommobilephone}{$frommobilephone}
EOF
    fi
    if [ ! -z "$fromemail" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{fromemail}{\href{mailto:$fromemail}{$fromemail}}
EOF
    fi
    if [ ! -z "$signature" ] ; then
	cat >> $localpath/$file.lco <<EOF
\setkomavar{signature}{$signature}
EOF
    fi
    cat >> $localpath/$file.lco <<EOF

%%% ============================================================= &EOF ===

%%% Local Variables:
%%% mode: LaTeX
%%% TeX-master: 
%%% TeX-parse-self: nil
%%% TeX-auto-save: t
%%% End:

EOF
}



### ............................................ &get_personal_details ...
### 
### Ask the user some questions.  Try to guess some defaults if
### possible.  Store this file in the users personal configuration
### file, which defaults to $TEXMFHOME/tex/latex/config/.

function get_personal_details() {
    file=$1
    inst_lco=$2
    confdir="tex/latex/config"

    ## If the user defined a certain directory via the -d switch, use
    ## that (if possible), otherwise try to find out, if one of the
    ## defined pathes of TEXMFHOME could be used.
    if [ -z $DIR ] ; then
	## Check, if the given file already exists
	if kpsewhich latex $file.lco > /dev/null 2>&1 ; then
	    echo "WARNING: Configuration file \"$file.lco\" does already exist!"
	    echo
	    while true; do
		echo -n "WARNING: Do you want to overwrite this file? [Y/N]"
		read answer
		case $answer in
		    n|N)
			echo "ERROR: Aborting ... "
			exit 4
			;;
		    j|J|y|Y)
			PATH=`kpsewhich latex $file.lco`
			break
			;;
		esac
		
	    done
	else
	    ## the personal configuration should reside in TEXMFHOME. 
	    ## Check, if that directory exists.  Some people might to
	    ## tend, to define more than one directory in TEXMFHOME.
	    IFS=':' read -ra texmfhome <<< "$TEXMFHOME"
	    for path in "${texmfhome[@]}"; do
		if [ -d $path ] ; then
		    # check if there is a conf directory
		    if [ -d $path/$confidr ] ; then
			# Can we write into it?
			if touch $path/$confdir/foobar 2> /dev/null ; then
			    rm $path/$confdir/foobar 2> /dev/null
			    localpath=$path/$confdir
			else
			    echo "WARNING: Could not write into $path/$confdir ..."
			    break
			fi
		    else
			# Can we create that directory?
			if ! mkdir -p $path/$confdir 2> /dev/null ; then
			    break
			else
			    localpath=$path/$confidr
			fi
		    fi
		fi
	    done
	    ## If there we could detect a writable directory in
	    ## TEXMFHOME, there should be a non zero localpath.
	    if [ -z $localpath ] ; then
		echo "ERROR: Could not find a place to save the config file!"
		exit 4
	    fi
	fi
    else
	## Check, if the user defined directory is writable
	if touch $DIR/foobar 2> /dev/null ; then
	    rm -f $DIR/foobar 2> /dev/null
	    localpath=$DIR
	else
	    echo "ERROR: No write permission for user defined directory $DIR!"
	    echo "ERROR: Aborting ... "
	    exit 4
	fi
    fi

    # This should be the file to write
    personalfile="$localpath/$file.lco"
    ## Go on with $localdir
    ## get all the personal information needed.
    clear
    echo
    echo -n "               In welcher Abteilung arbeiten Sie? "
    read department
    echo -n "         Wer ist der Leiter der Abteilung (Name)? "
    read departmenthead
    echo -n "                             Wie lautet Ihr Name? "
    read fromname
    echo -n "     Wie lautet Ihre teleonische Durchwahlnummer? "
    read fromphone
    echo -n "                   Wie lautet Ihre Fax-Durchwahl? "
    read fromfax
    echo -n "Gibt es eine Durchwahl für Ihr Mobiltelefon? "
    read fromshortmobilephone
    if [ -z "$fromshortmobilephone" ] ; then
	echo -n " Wollen Sie stattdessen Ihre Mobilnummer angeben? "
	read frommobilephone
    fi
    echo -n "                   Wie lautet Ihre E-Mailadresse? "
    read fromemail
    echo -n "                  Wie möchten Sie unterschreiben? "
    read signature

    # convert the telephone and telefaxnumbers to be grouped
    fromphone=`echo $fromphone | sed 's!\([0-9][0-9]\)!\1\\\,!g' \
        | sed 's!\\\,$!!'`     
    fromfax=`echo $fromfax | sed 's!\([0-9][0-9]\)!\1\\\,!g' \
        | sed 's!\\\,$!!'`
    fromshortmobilephone=`echo $fromshortmobilephone | sed 's!\([0-9][0-9]\)!\1\\\,!g' \
        | sed 's!\\\,$!!'`
    frommobilephone=`echo $frommobilephone | sed 's!\([0-9][0-9]\)!\1\\\,!g' \
        | sed 's!\\\,$!!' | sed 's!\\\,-!!g'`
    # replace ". " to ".\ "
    department=`echo $department | sed 's!\. !.\\\ !g'`
    departmenthead=`echo $departmenthead | sed 's!\. !.\\\ !g'`
    fromname=`echo $fromname | sed 's!\. !.\\\ !g'`

    # if the mailaddress does not contain a @, add the complete rest
    if [ ! -z "$fromemail" ]; then
	if ( echo $fromemail | grep -v @) > /dev/null ; then 
	    fromemail="$fromemail@tu-clausthal.de"
#	elif ( echo $fromemail | grep -v "tu-clausthal.de" ) ; then
#		fromemail="${fromemail}.tu-clausthal.de"
	fi
    fi
    
    ## write the personal configuration file
    echo
    echo -n "Writing $personalfile ..."
    write_personal_lcofile
    echo " done"
}

### ..................................................... &get_details ...

get_details () {

    file=$1
    cat=$2
    LCOFILE=$faculty/$institute.lco

    # get all the information needed.
    clear
    echo 
    echo -n "Vollständiger Name für $institute: "
    read inst
    echo -n "Direktor für $inst: "
    read head
    echo -n "Gebäude-ID: "
    read id
    echo -n "Besuchsadresse für Geb.-ID $id: "
    read addr
    echo -n "Durchwahl des Office-Telefons: "
    read tel
    echo -n "Durchwahl des Office-Fax: "
    read fax
    echo -n "Mailadresse des Office: "
    read mail
    echo -n "Webseite für $inst: "
    read url
    echo
    echo

    # convert the telephone and telefaxnumbers to be grouped
    tel=`echo $tel | sed 's!\([0-9][0-9]\)!\1\\\,!'`
    fax=`echo $fax | sed 's!\([0-9][0-9]\)!\1\\\,!'`
    head=`echo $head | sed 's!\. !.\\\ !g'`

    # if the mailaddress does not contain a @, add the complete rest
    if [ ! -z $mail ]; then
	if ( echo $mail | grep -v @) > /dev/null ; then 
	    mail="$mail@tu-clausthal.de"
	else
	    if ( echo $mail | grep -v "tu-clausthal.de" ) ; then
		mail="${mail}.tu-clausthal.de"
	    fi
	fi
    fi

    # check the webadress to be correct.  An entry starting with a /
    # is ment to be the end of "https://www.tu-clausthal.de".  If it
    # ends in a trailing dot, only "tu-clausthal.de/" should be
    # added.
    if (echo $url | grep ^/ ) > /dev/null ; then
	url="https://tu-clausthal.de$url"
    else
	if (echo $url | grep .$) > /dev/null ; then
	    url="https://${url}.tu-clausthal.de/"
	fi
    fi
    
    # write the information into its config file
    echo -n "Generating configuration file for $1 in $2 ... "
    write_lcofile
    echo "done "
    read
}

### ============================================================ &Main ===

## Get the command line options
get_options $*

## Determine the configuration
get_config

if [ $ALL ]; then
    ## in case, option -a|--all is given, then run through all
    ## faculties and every institute. 
    for faculty in Zentrale-Einrichtungen Fakultaet-1 Fakultaet-2 Fakultaet-3 ; do
	case $faculty in
 	    Zentrale-Einrichtungen)
 		institutes="praes   dez1   dez2   dez3   dez4   dez5   alm   izc   zhd   j   presse   tt   wbv   czm   efzn   gsb   ub   pr   rz   situc" 
 		;;
 	    Fakultaet-1)
 		institutes="fak1   iaac   iec   iept   imet   naw   ioc   pc   puk   itc   itvp   iww"
 		;;
 	    Fakultaet-2)
 		institutes="fak2   ifad   ibb   iber   ielf   ievb   ite   igp   geophys   igmc   iuw   wiwi"
 		;;
 	    Fakultaet-3)
 		institutes="fak3   iasor   icvt   iei   ifi   imab   imw   ifm   mvt   ippt   isaf   isse   itm   itv   itr"
 		;;
	esac
	for file in $institutes; do
 	    get_details $institute $faculty
	done
    done
else
    ## Create only one config file, either personal or for the
    ## institute itself.
    if [ ! -z $personal ]; then
	get_personal_details $personal $institute
    else
	get_details $institute $faculty
    fi
fi


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

### Local Variables:
### mode: sh
### End:
