:
# --------------------------------------------------------------------
# FUNCTION:
# Configuration for  nls2 package according to the actual pathname 
# and to the arguments on the command-line.
# --------------------------------------------------------------------
# USAGE:
# ./configure [-h | --help ] 
# or:
# ./configure [-host <Splus|R|nls2C> ] 
#             [-load <0|1|2>] 
#             [-system <unix|linux>] 
#             [-command <path-command>]
#             [-nosrc]
# This script is called by our script INSTALL and automatically by R CMD INSTALL
# In that last case, you can introduce arguments by the option:
#    --configure-args=<arguments-list>
# Example:
# R CMD INSTALL --configure-args="-system unix"
# (No space character around the sign "=")
# --------------------------------------------------------------------
# ARGUMENTS:
# See  html/install.html
# --------------------------------------------------------------------
# SIDE-EFFECTS:
#  Creation of the customized versions of files and directories:
#  all of the files and directories, the name of which is suffixed by '.in',
#  are modified into copies of same names, the suffix '.in' been removed.
# The directory 'inst' is created: it contains all is required for execution
# and for restoration of the distribuable package.
# --------------------------------------------------------------------
# DETAILS: (french)
# Ce script est appel par le script INSTALL ou, automatiquement, par
# R CMD INSTALL.
# Ce qu'il fait:
# - si on n'a pas prcis de commandes en argument, fixe la commande:
# Splus, si l'hte est Splus, et R, sinon 
# (dans le cas nls2C, on ignore la commande)
# - si l'hte n'est pas R: on force load  2 et on prvient qu'il faut
# customiser src/MyMakevars
# - copie le dir R.in dans un dir nomm R pour y modifier certaines
# balises conventionnelles dans les fonctions R tout en gardant l'original.
# - pour la mme raison, copie les src/<nom>.in dans src/<nom>
# et le dir demo.in dans demo.
# - teste R_PACKAGE_DIR: cette variable est affecte
# automatiquement par R CMD INSTALL. Si elle n'est pas affecte,
# c'est que le script n'est pas appel par R CMD INSTALL et on 
# installe dans le dir courant.
# - modifie R/init.R et src/nl/Messagenls2.c, pour y insrer le nom rl
# du dir d'installation
# - modifie les fichiers de demo: si le script n'est pas appel 
# par R CMD INSTALL, on y insre le nom rl du dir d'installation, 
# et on transforme les 'library(nls2)' et 'data()', par des 'attach'.
# Dans le cas inverse, on transforme les 'library(nls2)' en 
# 'library(nls2, lib.loc=le nom rl du dir d'installation)'
# - modifie src/Basic/nltypes.h pour insrer ieeefp ou ieee754 selon
# le systme (unix ou linux)
# - modifie src/Makefile: si load=2, on y inclut src/MyMakevars
# sinon (on est tjrs dans le cas R, lorsque load!=2), on y inclut
# RHOME/etc/Makeconf
# - modifie src/Makevars: si load=0, on remplace 'R' par le nom 
# rl de cette commande dans 'R CMD SHLIB' et, sinon, 
# on y met les variables $(CC), $(PKG_CPPFLAGS) (ces variables sont dfinies,
# soit dans RHOME/etc/Makeconf, soit dans src/MyMakevars).
# - modifie src/Makefile, si load!=0: les compils ne sont pas dans
# src/subdir, comme c'est le cas quand c'est R CMD INSTALL qui fait la
# compilation, mais dans  src: on modifie la commande du Makefile qui
# les dplace dans libs.
# - modifie R/loadnls2.s, si load!=0:  il faudra que cette fonction R
# compile les sources de l'utilisateur, alors que ce n'est pas
# ncessaire quand ils sont chargs par R CMD SHLIB
# - modifie src/Basic/nltypes.h, si l'hte est Splus: le type
# TFuncInt, qui est celui des arguments entiers des programmes appels 
# par les fonctions R, est alors 'long int'
# - cration du dir 'loaduser': on y met tout ce qui sera utile
#  la compilation des programmes de l'utilisateur:
# le fichier Makefile: recopie de celui de src
# les fichiers Makevars et  MyMakevars: ceux de src, modifis pour
# tenir compte des emplacements rls des dir,
# les *.h  inclure dans les  programmes de l'utilisateur: ceux de src
# -  On met dans un dir nomm 'inst', tout ce qui n'est pas standard,
# afin que R CMD INSTALL ne les dtruise pas: FILEMESS, loaduser,
# etc...
# - cration du dir 'tests', pour rpondre aux standards de R
# (R CMD INSTALL est cens excuter ce qui est dans ce dir): on y
# met toutes les dmos (fichiers demo/*.R) sauf ceux ncessitant Nag,
# que l'on concatne dans un fichier nomm 'nls2.R'
# 
# --------------------------------------------------------------------
# Last release: Oct 2003
# --------------------------------------------------------------------
# --------------------------------------------------------------------
# Definition of  function erreur()
# Print an error message and exit
# --------------------------------------------------------------------
erreur() 
  {
   echo "usage : $0 [-h|--help] | [-host <Splus|R|nls2C>] [-load <0|1|2>] [-system <unix|linux>] [-command <path-command>] [-nosrc]"
echo " See INSTALL"
echo " By default: -host R -system linux -command R"
echo ""
echo ""
 exit 1 
  }
# --------------------------------------------------------------------

# --------------------------------------------------------------------
# Main script:
# --------------------------------------------------------------------
echo "-----------------"
echo "EXECUTE CONFIGURE"
echo "-----------------"

# --------------------------------------------------------------------
# Initialisations:
# --------------------------------------------------------------------
lhost="R"
yahost=0
los="linux"
yasystem=0
lacde=0
yacde=-1
load=0
yaload=-1
nosrc=0

# --------------------------------------------------------------------
# Decode the arguments on the command-line:
# --------------------------------------------------------------------
for i in $*
             do
               case $i in
		 -h|--help)erreur; exit;;
                 -host)  yahost=1;;
		  -load) load=1; yaload=1;;
		 -system)  yasystem=1;;
		 -command) lacde=1; yacde=1;;
		  -nosrc) nosrc=1;;
                 *)  if [ $yacde -gt 0 ]
			then
				cde=$i
				yacde=0
			else if [ $yaload -eq 1 ]
		       then
                         load=$i;
                         yaload=0;
		       else if [ $yahost -eq 1 ]
		       then
                         lhost=$i;
                         yahost=0;
   		       else if [ $yasystem -eq 1 ]
		       then
                         los=$i;
                         yasystem=0
			else
  	            		echo "Invalid option: $i" ; erreur 
			fi; fi;fi;
			fi;;
                esac
             done


if [ $yacde -ne 0 ]
then
# cas o on n'a pas fourni de cde
	if [ $lhost = "Splus" ]
	then
		cde="Splus"
	else
		cde="R"
	fi
fi

# --------------------------------------------------------------------
# Verifications
# --------------------------------------------------------------------
echo "Options:"
echo "host=$lhost system=$los load=$load cde=$cde nosrc=$nosrc"

if [ $lacde -eq 1 -a $yacde  -ne 0 ]
	then
	echo "command missing after the -command option"
	erreur
fi
if [ $yaload -eq 1 ]
	then
	echo "load value missing after the -load option"
	erreur
fi

if [ $yahost  -ne 0 ]
	then
	echo "host missing after the -host option"
	erreur
fi


if [ $yasystem  -ne 0 ]
	then
	echo "system missing after the -system option"
	erreur
fi
if [ $lhost != "R" ]
then
  if [ $load -ne 2 ]
	then
	load=2
	echo "Warning: -load option is automatically set to 2  when -host = $lhost"
fi
fi

if [ $load -eq 2 ]
	then
        echo "-------------------------------------------------------------"
	echo "-load 2: WE SUPPOSE THAT YOU HAVE CUSTOMIZED  THE FILE src/MyMakevars"
        echo "-------------------------------------------------------------"
fi

if [ $lhost != "R" -a $lhost != "Splus" -a $lhost != "nls2C" ]
	then
	echo "Invalid value $lhost for option -host"
	erreur
fi

if [ $los != "unix" -a $los != "linux" ]
	then
	echo "Invalid value $los for option -system"
	erreur
fi

# --------------------------------------------------------------------
# End of verifications
# --------------------------------------------------------------------


# --------------------------------------------------------------------
# Copy the files "*.in" in their actual version
# before transformation
# --------------------------------------------------------------------
# Detruire les directorys cible (R et demo) avant
# de les reconstruire, pour viter pbes en cas d'install
# successives
if test -d R
   then rm -r R
fi
cp -pr ./R.in  R
cp ./R/init.R.in  ./R/init.R
cp ./R/loadnls2.s.in  ./R/loadnls2.s
cp ./src/nl/Messagenls2.c.in  ./src/nl/Messagenls2.c
cp ./src/Basic/nltypes.h.in  ./src/Basic/nltypes.h
cp ./src/Makevars.in  ./src/Makevars
cp ./src/Makefile.in ./src/Makefile
if test -d demo
  then rm -r demo
fi
cp -pr ./demo.in demo

# --------------------------------------------------------------------
# Determine the variable 'nls2dir':  the pathname of the installation directory
# --------------------------------------------------------------------
	echo ""
	echo ${R_PACKAGE_DIR="R_PACKAGE_DIR_not_set"}
# If the script is invoked by  R CMD INSTALL, the variable
# R_PACKAGE_DIR is automatically equal to the pathname of the
# installation directory.
# Otherwise, we set  R_PACKAGE_DIR to an arbitray value:
# It will mean that the script is invoked by our script INSTALL
# which installs in the current directory, and then, nls2dir is the
# return value of the system command 'pwd'

	if [ $R_PACKAGE_DIR = "R_PACKAGE_DIR_not_set" ]
	then
		nls2dir=`pwd`;
	else
		nls2dir=${R_PACKAGE_DIR};
	fi

# ------------------------------------------------------------------
# Replace  conventional patterns by the value of 'nls2dir'
# 1/ in file 'init.R': to affect the pathname of the installation directory
# to a R variable called .Nls2dir.  'init.R' is used :
#  - in file 'loadnls2.s': this function needs to know where are the  files
# to link with the user-programs and where are the 'Makefile' and 'Makevars' files
# used for compilation.
#  - in the 'data' files: to set the pathnames of the formal-model files to their
# actual values.
#  - in the 'demo' files: to know where are the executable commands which create
# the C-source files which calculate the user-models from their formal-descriptions.
# 2/ in file 'Messagenls2.c' which needs to know where is the file 'FILEMESS'
# which contains the messages.
# --------------------------------------------------------------------

echo "Replace PATRONDIR by $nls2dir"

# ici, c'est % le sparateur de champ pour sed
 eval truc=s%PATRONDIR%$nls2dir%g

for i in  R/init.R  src/nl/Messagenls2.c  ; do
		sed -e $truc < $i > toto$$
		 mv toto$$ $i
done

# --------------------------------------------------------------------
# Put the pathname of the installation directory in the 'demo' files.
# --------------------------------------------------------------------
echo "Modify files of the directory 'demo'"

# 1/ If the script is not invoked by  R CMD INSTALL, nls2 is not
# a R library, and we must replace the commands 'library(nls2)'
# and 'data(example-name)' by commands 'attach':
# --------------------------------------------------------------------
# AB: 26/10/2007: rajout du " avant .Rdata et COUCOU pour que
# le remplacement ne se fasse pas X fois en cas d'installations
# rptes

if [ $R_PACKAGE_DIR = "R_PACKAGE_DIR_not_set" ]
	then
        if [ $lhost = "Splus" ]
	then
         eval truc=s%"COUCOU%"$nls2dir/data/.Data%;
         eval truc2=s%".RData%"$nls2dir/.Data%;
        else
         eval truc=s%"COUCOU%$"nls2dir/data/.RData%;
         eval truc2=s%".RData%"$nls2dir/.RData%;
	fi

	for i in ./demo/*.R 
	 do
	 yal=`grep -c "library" $i`;
	 if [ $yal != 0 ]
	 then
		sed -e 's%library(nls2,lib.loc=%attach(%' < $i | sed -e 's%NLS2LOC%.RData%'  | sed -e $truc2  > toto$$
sed -e 's%data(.*)%attach("COUCOU")%' < toto$$ | sed -e $truc >  $i
	 fi
	done
else
# --------------------------------------------------------------------
# 2/ If the script is  invoked by  R CMD INSTALL, nls2 is a R library
# but may have been installed in a non-standard location.
# So we use the 'library' command with the 'lib.loc' argument in the 'demo' files.
# Here, we replace the conventional NLS2LOC pattern by the actual pathname
# of the directory which contains nls2, i.e the result of the system command 'dirname' 
# --------------------------------------------------------------------

lalib=`dirname $nls2dir`
echo "Replace NLS2LOC by $lalib in the demo files"
eval truc=s%NLS2LOC%$lalib%g
for i in demo/*.R ; do
	sed -e $truc < $i > toto$$
		 mv toto$$ $i
done
echo  ""

fi
# --------------------------------------------------------------------
# We need to know where is the C function: 'finite()'
# Note: We do not use R_finite (provided with the R package)
# because we want nls2 to be available on sites where R is not installed.
# It is more easy to always use the system files 'ieee*.h' 
# than to redefine  R_finite in some cases only.
# --------------------------------------------------------------------
echo "Modify src/Basic/nltypes.h to include the ieee*.h file"

if [ $los = "linux" ]
then
	sed -e 's/FINITE/<ieee754\.h>/' < src/Basic/nltypes.h > toto$$
else
	sed -e 's/FINITE/<ieeefp\.h>/' < src/Basic/nltypes.h > toto$$
fi
mv toto$$ src/Basic/nltypes.h

# --------------------------------------------------------------------
# In the src/Makefile, we need to know the compilation
# and link commands and options, and the suffix of the shared-library.
# We include the file which contains them.
# --------------------------------------------------------------------

echo "Modify src/Makefile"

# --------------------------------------------------------------------
# 1/ If load=2, this file is 'src/MyMakevars'
# (It is supposed that the installator has previously customized it)
# --------------------------------------------------------------------
if [  $load -eq 2 ]
then
	eval truc=s%RCONFIG=.*%RCONFIG=$nls2dir/src/MyMakevars%
	sed -e "$truc" < ./src/Makefile > toto$$
	mv toto$$  ./src/Makefile 
        echo ""

else
# --------------------------------------------------------------------
# 2/ If load=0 or load=1, this file is R_HOME/etc/Makeconf
# (Remember: load=0 and load=1 are presently possible when R is available only)
# Note: When load=0, we do not use the compilation and link commands 
# of R_HOME/etc/Makeconf but R CMD SHLIB.
# However, we need to include R_HOME/etc/Makeconf to know the suffix
#  of the shared-library
# --------------------------------------------------------------------

        echo ${z=`$cde RHOME`}
# 2012/4/4: exception UBUNTU : the file Makeconf 
# can be in other location than in RHOME/etc/Makeconf
# Replace : $z/etc/Makeconf by the correct location in the
# following sentence
	aexec="sed -e 's%RCONFIG=.*%RCONFIG= $z/etc/Makeconf%' < ./src/Makefile > toto$$"
	echo "Execute: $aexec"
	eval $aexec
# ADDED: 2007/05/02
# 2016/12/06: remove the following because the directory 'share'
# is no more in the R_HOME hierarchy

# 2012/4/4: exception UBUNTU :  the directory
# share can be in other location than in RHOME/share
# Replace : $z/share by the correct location in the
# following sentence
# aexec="sed -e 's%R_SHARE_DIR=.*%R_SHARE_DIR= $z/share%' < toto$$ > ./src/Makefile "
# Example Ubuntu:
# aexec="sed -e 's%R_SHARE_DIR=.*%R_SHARE_DIR= /usr/share/R/share%' <toto$$ > ./src/Makefile " 

aexec="cp toto$$  ./src/Makefile "
 	echo "Execute: $aexec"
 	eval $aexec
# REMOVED: 2007/05/02	mv toto$$ ./src/Makefile
fi 
# --------------------------------------------------------------------
# When load=0, CMD SHLIB is used: 
# We need to put the exact name of the R command before.
# --------------------------------------------------------------------

if [ $load -eq 0 ]
then
	echo "Replace the name of the command by $cde in src/Makevars"
	aexec="sed -e 's%CDE=.*%CDE=$cde%g' < src/Makevars > toto$$"
	echo "Execution of $aexec"
	eval $aexec
	mv toto$$ src/Makevars 
	echo ""
else 
# --------------------------------------------------------------------
# When load >0, the compilation commands and flags
# are named $(CC), $(PKG_CPPFLAGS), etc,..
# in the file included in the src/Makefile, i.e either
# `R RHOME`/etc/Makeconf (when load=1) or  src/MyMakevars (when load=2).
# We update the file src/Makevars (src/Makevars is also included in  src/Makefile),
# according with these variables.
# --------------------------------------------------------------------

	echo "Set the compilators in  src/Makevars"
	# Modify these sentences if not suitable on your site:
	# -------------------------------------
	sed -e 's%C=.*%C=$(CC) -c $(PKG_CPPFLAGS) %' < src/Makevars |
	sed -e 's%F=.*%F=$(FC) -c $(PKG_CPPFLAGS) %' > titi$$

	sed -e 's%CPSI=.*%CPSI=$(CC) -c $(BINCL) $(PSIINCL) %' <  titi$$ |
	sed -e 's%CINV=.*%CINV=$(CC) -c  $(BINCL) $(INVINCL) %' > toto$$
	sed -e 's%SHLIB_LD=%#SHLIB_LD=%' < toto$$ > src/Makevars
# --------------------------------------------------------------------
# When compilation is done by CMD SHLIB, the object-files are
# automatically in the directory of the source-files, 
# (i.e in src/sub-directory-name)
# whereas, when compilation is done by system compilators,
# they are in the directory in which the compilation command
# is launched. (i.e in src).
# We modify the command of the Makefile which move them to
# the nls2libs directory.
# --------------------------------------------------------------------

	echo "Transformation for 'load>0' in file src/Makefile"
	sed -e 's%(srcdir)/.*/\*.o%(srcdir)/*.o%' < src/Makefile > toto$$
	mv toto$$  src/Makefile
# --------------------------------------------------------------------
# When link is not done by CMD SHLIB but a system linker, 
# compilation of the source-files may be required before.
# In the function 'loadnls2' -- this function creates and loads 
# the shared-library which calculates the user-model --
# we indicate, via the LOAD variable, that compilation should
# be done.
# --------------------------------------------------------------------

	echo "Transformation for 'load>0' in file R/loadnls2.s"
	sed -e  's/LOAD <- .*/LOAD <- 1/' < ./R/loadnls2.s > toto$$
	mv toto$$ ./R/loadnls2.s
	echo ""
fi # fin if [ $load -gt 0 ]


# --------------------------------------------------------------------
# In SPlus version, the integer arguments of the C-programs 
# called by SPlus-functions must be declared 'long int'
# --------------------------------------------------------------------

if [ $lhost = "Splus" ]
then
	echo "Transformation for SPlus in src/Basic/nltypes.h: int --> long int"
	sed -e 's/typedef int TFuncInt/typedef long int TFuncInt/' < src/Basic/nltypes.h > toto$$
	mv toto$$ src/Basic/nltypes.h
	echo ""
fi # fin if [ $lhost = "Splus" ]


# --------------------------------------------------------------------
# Creation of the directory loaduser:
# This directory will contain all is required for the function
# 'loadnls2' to compile and link the user-model, i.e the Makefile and
# Makevars files and some of the include-files.
# --------------------------------------------------------------------

# --------------------------------------------------------------------
# 1/ We copy the src/Makefile:
# --------------------------------------------------------------------

echo "Create the directory loaduser"
test -d ./loaduser || mkdir ./loaduser
cp ./src/Makefile ./loaduser/.

# --------------------------------------------------------------------
# 2/  We modify the src/Makevars  because it contains
# locations which will be no more correct
# after installation:
# The top-dir will be no more '..' but $nls2dir, 
# the 'inst' directory will be transferred one level above,
# the other required files will be in the 'loaduser' directory.
# --------------------------------------------------------------------

cp ./src/Makevars  ./loaduser/.
eval truc=s%top_dir=.*%top_dir=$nls2dir%
sed -e "$truc" < ./loaduser/Makevars > toto$$
eval truc=s%/inst%%g
sed -e $truc < toto$$ > ./loaduser/Makevars
sed -e 's%src/Basic%loaduser%g' < ./loaduser/Makevars |
 sed -e 's%src/analder%loaduser%g' > toto$$ 
sed -e 's% $(AINCL)%%' < toto$$ > ./loaduser/Makevars

# --------------------------------------------------------------------
# 3/ When load=2, the file 'MyMakevars' is also required
# for compilation:
# We put it in the directory 'loaduser':
# --------------------------------------------------------------------
if [ $load -eq 2 ]
then
	cp ./src/MyMakevars ./loaduser/.
# --------------------------------------------------------------------
# We modify the file 'Makefile' used by 'loadnls2':
# Absolute pathname of 'MyMakevars' is required in this file.
# Note: It is not the case for the other file included in 'Makefile',
# the file Makevars. This file is found, even when its location
# is not absolute!
# --------------------------------------------------------------------

	eval truc=s%RCONFIG=.*%RCONFIG=$nls2dir/loaduser/MyMakevars%
	sed -e "$truc" < ./loaduser/Makefile > toto$$
	mv toto$$ ./loaduser/Makefile
fi

# --------------------------------------------------------------------
# 4/ We copy the include-files used in the C-programs which calculate
# the user-model:
# --------------------------------------------------------------------
cp ./src/Basic/*.h ./loaduser
echo ""

# --------------------------------------------------------------------
# We create the directory 'inst' in which we must put  all we want to keep:
# By convention, R CMD INSTALL remove every non-standard files and directories
# which are not in this directory.
# --------------------------------------------------------------------
echo "Create the directory inst"
test -d ./inst || mkdir ./inst
cp ./FILEMESS ./inst/.
cp ./COPYING ./inst/.
mv ./loaduser ./inst/.
mv ./html ./inst/.
mv ./doc ./inst/.
mv crCalib ./inst/.

# --------------------------------------------------------------------
# When deletion of the source-files is not asked, we put them
# in the directory 'inst'.
# The files not required in the script INSTALL are moved,
# the other are copied, so this script can find them at their
# original location.
# --------------------------------------------------------------------
if [ $nosrc -eq 0 ]
then
  cp -pr ./src ./inst
  mv ./CONTENTS ./inst/.
  cp  ./INSTALL ./inst/.
  cp ./configure ./inst/.
  cp -pr ./R.in ./inst/.
  cp -pr ./demo.in ./inst/.
  test -f  ./.Rbuildignore && cp -pr ./.Rbuildignore ./inst/.
fi


echo ""
# --------------------------------------------------------------------
# We create the directory 'tests' which should contain R-code to test the installation:
# R CMD INSTALL is supposed to run it automatically.
# In fact, it is not true: I do not succeed to make this execution automatic,
# whatever the way I tried.
# However, I keep this directory for the case I understand why the
# tests are not automatically executed.
# I join all the 'demo' which do not need Nag in a single file, named 'nls2.R'.
# --------------------------------------------------------------------

echo "Create the directory tests"
test -d ./tests || mkdir tests
cp ./demo/*.R ./tests/.
# Remove the examples which need Nag:
rm ./tests/mag.R ./tests/ej.R ./tests/simul.R
cat ./tests/*.R > ./tests/nls2.tout
rm ./tests/*.R
mv ./tests/nls2.tout ./tests/nls2.R

# --------------------------------------------------------------------
# Delete the temporary files, in case some remain:
# --------------------------------------------------------------------
test -f ./toto$$ && (rm -r ./toto$$)
test -f ./titi$$ && (rm -r ./titi$$)
echo ""
# --------------------------------------------------------------------

echo "----------------"
echo "END OF CONFIGURE"
echo "----------------"
echo ""
# --------------------------------------------------------------------
