#!/bin/sh

SRCF="SQLTeX.pl"
TMPF="SQLTeX.tmp"
SQLT="SQLTeX"
RFIL="SQLTeX_r.dat"
TAB="\011"

PI=`which perl` || PI=""

## Is Perl installed ?
if test -z "$PI"
then
   echo "Perl is either not installed on this system, or not included in your path"
   echo "Please check and correct this error - you need Perl to use SQLTeX"
   exit
fi

## Does the source file exist ?
if ! test -f $SRCF
then
   echo "Error - the file $SRCF does not exist in the current directory"
   exit
fi

## Where should SQLTeX be installed ?
CUSR=`whoami`
if test $CUSR = "root"
then
   DDIR="/usr/local/bin"
else
   DDIR=`pwd`
fi
while test -z "$IDIR"
do
   echo -n "Where should SQLTeX be installed [$DDIR] ? "
   read IDIR
   if test -z "$IDIR"
   then
      IDIR="$DDIR"
   fi
   if ! test -d $IDIR
   then
      echo "$IDIR does not exist or is not a directory"
      IDIR=""
   fi
done

echo "#!$PI -w" > $TMPF
echo "" >> $TMPF
cat $SRCF >> $TMPF
chmod +x $TMPF
mv $TMPF $IDIR/$SQLT

Write_r_File () {
	echo -E -n "$1" >> $IDIR/$RFIL
	echo -e -n $TAB >> $IDIR/$RFIL
	echo -E "$2" >> $IDIR/$RFIL
}

## Create the replacement file if it does not yet exist
if ! test -e $IDIR/$RFIL
then
	touch $IDIR/$RFIL
	echo -e "; This file contains all characters or character sequences that" >> $IDIR/$RFIL
	echo -e "; will be be replaced by SQLTeX when the occur in the response" >> $IDIR/$RFIL
	echo -e "; of an SQL query." >> $IDIR/$RFIL
	echo -e "; It is mainly used for escaping the (La)TeX special characters," >> $IDIR/$RFIL
	echo -e "; but any value can be added here." >> $IDIR/$RFIL
	echo -e "; The first column is the character (sequence) that will be replaced." >> $IDIR/$RFIL
	echo -e "; The second column is the value to replace col 1 with." >> $IDIR/$RFIL
	echo -e "; Columns are sepated with one or more tab- characters." >> $IDIR/$RFIL
	echo -e ";" >> $IDIR/$RFIL
	echo -e "; Note all values are case sensitive; if you add the line:" >> $IDIR/$RFIL
	echo -e ";   LaTeX	\LaTeX\ " >> $IDIR/$RFIL
	echo -E "; the word \"latex\" will be untouched, but \"LaTeX\" will be replaced." >> $IDIR/$RFIL
	echo -e ";" >> $IDIR/$RFIL
	Write_r_File "$" '\$'
	Write_r_File "_" "\_"
	Write_r_File "%" "\%"
	Write_r_File "&" "\&"
	Write_r_File "<" "\texttt{<}"
	Write_r_File ">" "\texttt{>}"
	Write_r_File "{" "\{"
	Write_r_File "}" "\}"
	Write_r_File "#" "\#"
	Write_r_File '~' "\~{}"
	Write_r_File '\' "\ensuremath{\backslash}"
else
	echo "Replace file already exists---not overwritten"
fi

echo "Installation complete---type $SQLT -h for help"