#!/bin/bash
# Installation script for ShLaTeX
# Warning : you must be root to run this script !
# This script must be run in the ShLaTeX directory.

# variables d'installation
user=`whoami`;
version="1.2b-en";

# fichiers d'installation
gpl="../GPL.TXT";
src="../src";
tex8to7="../src/tex8to7.c";
man="./man/shlatex.1.bz2";
shlatex="./ShLaTeX";
todo="../TODO.TXT";
fichInstall="$gpl $tex8to7 $man $shlatex $todo";

# r�pertoires d'installation
cheminMan="/usr/share/man/man1";
cheminExec="/usr/bin";
cheminScript="/usr/share";
repInstall="$cheminMan $cheminExec $cheminScript";

# v�rification de l'identit� de l'appelant
if [ ! $user == "root" ]
then
	echo -ne "> Error : you must be 'root' to run this script\n";
	echo -ne "    See the README.TXT file for further details.\n";
	exit 1;
fi

# v�rification de l'abscence de cette version n'est pas d�j� install�e
if [ -d "$cheminScript/shlatex-$version" ]
then
	echo "ShLaTeX $version is already installed on your system."
	echo "Before re-installing, you have to uninstall."
	exit 2;
fi

# v�rification de l'existence des r�pertoires cibles, cr�ation le cas �ch�ant
for rep in $repInstall
do
	if [ ! -d "$rep" ]
	then
		echo -ne "> Avertissement : impossible de trouver \"$rep\", cr�ation du r�pertoire...\n";
		mkdir -p "$rep"
	fi
done

# v�rification de l'existence des fichiers d'installation
for fich in $fichiersInstall
do
	if [ ! -f "$fich" ]
	then
		echo -ne "> Erreur : impossible de trouver le fichier \"$fich\", ce fichier est n�cessaire pour l'installation !\n";
		exit 3;
	fi
done

cat $gpl | more

echo -ne "\n\n"

rpse="-";
until [ "$rpse" == "y" -o "$rpse" == "n" ]
do
	read -p "Do you agree the terms of the GNU GPL licence (y/n) ? " rpse
done

if [ ! "$rpse" == "y" ]
then
	echo "> Installation cancelled."
	exit 1;
fi

clear

echo -ne "> Installation in progress...\n"
echo -ne "> Compiling...\n"
gcc $tex8to7 -o tex8to7
echo -ne "> Installation of tex8to7...\n"
cp ./tex8to7 "$cheminExec/tex8to7"
rm -f tex8to7
chmod 755 "$cheminExec/tex8to7"
echo -ne "> Installation of the man page...\n"
cp $man "$cheminMan/shlatex.1.bz2"
chmod 644 "$cheminMan/shlatex.1.bz2"
echo -ne "> Installation of the script...\n"
mkdir "$cheminScript/shlatex-$version"
cp -fR * $gpl $src $todo "$cheminScript/shlatex-$version"
chmod -R 755 "$cheminScript/shlatex-$version"
if [ ! -L "$cheminExec/ShLaTeX" ]
then
	ln -s "$cheminScript/shlatex-$version/ShLaTeX" "$cheminExec/ShLaTeX"
fi
ln -s "$cheminScript/shlatex-$version/ShLaTeX" "$cheminExec/ShLaTeX-$version"
echo -ne "> Test in progress...\n"
cd "$cheminScript/shlatex-$version/test"
chmod 755 ./test
./test
echo -ne "> Done.\n\n"