#!/bin/ksh
#set -xv
#-
echo "This script must be run while in the modipsl/modeles/OPA directory"
cd WORK
pwd
#MODEL_LIB=../../../lib/libopa.a
#MODEL_LIB=`grep MODEL_LIB AA_make.ldef | sed 's/ //g' | sed 's/MODEL_LIB=//g' `
liste_cle=$(egrep '^# *if[!( &]*def|^# *elif' *.[Fh] *.[Fh]90 | grep key_ | sed 's/||/\
/' | sed 's/\&\&/\
/' | sed 's/^.*key_/key_/' | sed 's/ *[) ] *$//' | sort -u )
#-
#-
#- 3) Ecriture du AA_make
#-
#- enteteFait_AA_make     
#-
cat > tampon <<end
#
.SUFFIXES: .f90 .F90 .F
#
# Target
all: 		diroce \$(EXEC_BIN)
		@cp SRC_FILE_LIST.temp SRC_FILE_LIST
		@echo OPA model is OK
# cleaning objects, libraries and executables
clean:
		\$(RM) model.o \$(MODDIR)/oce/*.mod \$(MODEL_LIB) \$(SXMODEL_LIB) \$(EXEC_BIN)
		@echo OPA model \(.o .mod libraries and executables are removed\)
# dependancies
diroce:
		@if [ ! -d ../../../lib/oce ] ; then mkdir ../../../lib/oce ; fi

\$(EXEC_BIN) :	libioipsl key keyverif src_file_list \$(MODEL_LIB) \$(IOIPSL_LIB) model.o
		\$(F_L) \$(L_X) -o \$(EXEC_BIN) model.o \$(SXMODEL_LIB) \$(OASISMPI2_LIB) \$(IOIPSL_LIB) \$(NCDF_LIB) \$(LIBMPI) \$(LIBMP)

libioipsl :
	(cd ../../IOIPSL/src ; \$(M_K) -f Makefile )

# main program
model.o :	model.f90
		@\$(F_C) \$(F_O) -c model.f90

# if the make script is stopped, one doesn't destroy library
.PRECIOUS : \$(MODEL_LIB)
#-Q- sxnec .PRECIOUS : \$(SXMODEL_LIB)

# library dependancies
\$(MODEL_LIB):	\$(LIB_OBJ)
		@echo
		@echo La bibliotheque est a jour
		@echo

# Rules
.DEFAULTS:

# rules for the .f90 files
.f90.a :           
		@\$(F_C) \$(P_P) \$(F_O) \\
#-Q- fjvpp		-Z \$*.L \\
#-Q- sxnec		-R2 \\
#-Q- aix		-qsource \\
		\$*.f90 || { mv \$(PREF)\$*.L \$(TMP) ; false ; exit ; }
#-Q- sxnec		@\$(A_X) \$(SXMODEL_LIB) \$*.o  > /dev/null
		@\$(A_C) \$(MODEL_LIB) \$*.o  > /dev/null
		@\$(RM) \$*.[of]
		@if [ -f \$*.mod ] ; then mv \$*.mod \$(MODDIR)/oce ; fi
#-Q- aix		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- linux		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
		@mv \$(PREF)\$*.L \$(TMP)

# rules for the .F90 files
.F90.a :           
		@\$(F_C) \$(P_P) \$(F_O) \\
#-Q- fjvpp		-Z \$*.L \\
#-Q- sxnec		-R2 \\
#-Q- aix		-qsource \\
		\$*.F90 || { mv \$(PREF)\$*.L \$(TMP) ; false ; exit ; }
#-Q- sxnec		@\$(A_X) \$(SXMODEL_LIB) \$*.o  > /dev/null
		@\$(A_C) \$(MODEL_LIB) \$*.o  > /dev/null
		@\$(RM) \$*.[of]
		@if [ -f \$*.mod ] ; then mv \$*.mod \$(MODDIR)/oce ; fi
#-Q- aix		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- linux		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
		@mv \$(PREF)\$*.L \$(TMP)

# rules for the .F files
.F.a :           
		@\$(F_C) \$(P_P) \$(F_O) \\
#-Q- fjvpp		-Z \$*.L \\
#-Q- sxnec		-R2 \\
#-Q- aix		-qsource \\
		\$*.F || { mv \$(PREF)\$*.L \$(TMP) ; false ; exit ; }
#-Q- sxnec		@\$(A_X) \$(SXMODEL_LIB) \$*.o  > /dev/null
		@\$(A_C) \$(MODEL_LIB) \$*.o  > /dev/null
		@\$(RM) \$*.[of]
		@if [ -f \$*.mod ] ; then mv \$*.mod \$(MODDIR)/oce ; fi
#-Q- aix		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- linux		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
		@mv \$(PREF)\$*.L \$(TMP)

# rules for the library from the .f files 
.f.a : 		
		@\$(F_C) \$(F_O) \\
#-Q- fjvpp		-Z \$*.L \\
#-Q- sxnec		-R2 \\
#-Q- aix		-qsource \\
		\$*.f|| { mv \$*.L \$(TMP) ; false ; exit ; }
#-Q- sxnec		@\$(A_X) \$(SXMODEL_LIB) \$*.o  > /dev/null
		@\$(A_C) \$(MODEL_LIB) \$*.o  > /dev/null
		@\$(RM) -f \$*.o
#-Q- aix		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- linux	@mv \$(PREF)\$*.lst \$(PREF)\$*.L
		@mv \$*.L \$(TMP)
#
end
#-
#- dependances
#-
exec 1> AA_make
MAIN="model"
echo '# $Header$'
echo '# some variables'
echo 'TMP = ../../../tmp'
echo 'L_X = $(L_O) $(L_C) -ftrace'
echo '#-Q- sxnec  # Compiler options for the ORCA model   -   std'
echo '#-Q- sxnec  F_O = -dw -Wf\"-A idbl4\" -sx5 -ftrace -C vopt -Wf"-init stack=nan" -Wl"-f nan" -Wf"-P nh" -Wf,-pvctl noassume loopcnt=10000 -L transform -I $(MODDIR) -I $(MODDIR)/oce'

echo '#-Q- linux  # Compiler options for the ORCA model'
echo '#-Q- linux  F_O = -Mlist -O2 -byteswapio -r8  -module $(MODDIR)'
echo '#-Q- aix    # Compiler options for the ORCA model (aix version)'
echo '#-Q- aix    F_O =  -qrealsize=8 -qsave -qsuffix=f=f90 -qsuffix=cpp=F90 -qsource -I$(MODDIR)/oce -I $(MODDIR) -I $(IOIPSL_MOD) -q64 -O4 -qlargepage -qmaxmem=-1 -brename:.flush,.flush_ -brename:.mpi_send,.mpi_bsend'
echo '#-Q- aix   L_X = $(L_O) $(L_C) '

echo 'PREF='
echo '#-Q- sxnec	PREF=i.'
echo ''
# Write the cpp key list with one key by line
echo 'KEY_LIST = \c'
for i in ${liste_cle}
do
 echo "\\"
 echo "     $i \c"
done

echo ''
echo '# .o file list in the library'
echo 'LIB_OBJ = \c'
#
# allons chercher tous les .f du repertoire courant
# construction de la liste des objets LIB_OBJ

for i in `ls *.f`
do
  bn=`basename $i .f`
  if [ "${bn}" != "${MAIN}" ] 
  then 
    echo "\\"
    echo "		\$(MODEL_LIB)($bn.o)\c"
  fi
done

# allons chercher tous les .f90 du repertoire courant
# construction de la liste des objets LIB_OBJ
# one dependancy by line
for i in `ls *.f90`
do
  bn=`basename $i .f90`
  if [ "${bn}" != "${MAIN}" ] 
  then 
    echo "\\"
    echo "		\$(MODEL_LIB)($bn.o)\c"
  fi
done

# allons chercher tous les .F90 du repertoire courant
# construction de la liste des objets LIB_OBJ

for i in `ls *.F90`
do
  bn=`basename $i .F90`
  if [ "${bn}" != "${MAIN}" ] 
  then 
    echo "\\"
    echo "		\$(MODEL_LIB)($bn.o)\c"
  fi
done

# allons chercher tous les .F du repertoire courant
# construction de la liste des objets LIB_OBJ

for i in `ls *.F`
do
  bn=`basename $i .F`
  if [ "${bn}" != "${MAIN}" ] 
  then 
    echo "\\"
    echo "		\$(MODEL_LIB)($bn.o)\c"
  fi
 done

echo ""

cat tampon
rm tampon

#
for fic in `ls *.f90 *.F90  *.F `
do
    if [ "${fic}" != "${MAIN}.[Ff]" ]
    then
	i=0
	j=0
	dep=""
	inc=""
	inc2=""
	inc3=""
	luse0=""
	luse1=""
	luse2=""
	luse3=""
# on cherche les includes type modele de glace LLN
	for inc in `sed -n 's/^[  	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $fic | sort -u`
	do
	    dep="$dep\n$inc"
	done

# on cherche les includes (et les includes des includes et ainsi de suite pour 3 niveaux max)
	for inc in `sed -n 's/^#[ 	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $fic | sort -u`
	do
	    j=1
	    dep="$dep\n$inc"
		for inc2 in `sed -n 's/^#[ 	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $inc | sort -u`
		do
		    dep="$dep\n$inc2"
		    # on cherche les include  dans le fichier deja include (3eme niveau! balaise!)
		    for inc3 in `sed -n 's/^#[  	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $inc2 | sort -u`
		    do
			dep="$dep\n$inc3"
		    done
		done
	done

# on cherche les USE dans les include
	for inc in `sed -n 's/^#[ 	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $fic | sort -u`
	do
		for fuse0 in `sed -n 's/^[ 	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $inc | sort -u`
		do
	        if [ $fuse0 != "ioipsl" ] 
                then
		    lfuse0=$fuse0.f90
		    [ -f $fuse0.F90 ] && lfuse0=$fuse0.F90
		    luse0="$luse0\n$lfuse0\n\$(MODEL_LIB)($fuse0.o)"
                fi
		done

# on cherche aussi les USE dans les include des include on les ajoute a luse0

		for inc2 in `sed -n 's/^#[ 	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $inc | sort -u`
		do
		    for fuse0 in `sed -n 's/^[ 	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $inc2 | sort -u`
		    do
	            if [ $fuse0 != "ioipsl" ] 
                    then
		        lfuse0=$fuse0.f90
		        [ -f $fuse0.F90 ] && lfuse0=$fuse0.F90
		        luse0="$luse0\n$lfuse0\n\$(MODEL_LIB)($fuse0.o)"
                    fi
		    done
  	        done
	done

# on cherche les USE (et les USE des USE et ainsi de suite pour 3 niveaux max)
	for fuse1 in `sed -n 's/^[ 	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $fic | sort -u`
	do
	if [ $fuse1 != "ioipsl" ] 
        then
	    lfuse1=$fuse1.f90
	    [ -f $fuse1.F90 ] && lfuse1=$fuse1.F90
	    luse1="$luse1\n$lfuse1\n\$(MODEL_LIB)($fuse1.o)"
		for fuse2 in `sed -n 's/^[ 	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $lfuse1 | sort -u`
		do
	        if [ $fuse2 != "ioipsl" ] 
                then
		    lfuse2=$fuse2.f90
		    [ -f $fuse2.F90 ] && lfuse2=$fuse2.F90
		    luse2="$luse2\n$lfuse2\n\$(MODEL_LIB)($fuse2.o)"
		    # on cherche les USE  dans le fichier deja USE (3eme niveau! balaise!)
		    for fuse3 in `sed -n 's/^#[  	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $lfuse2 | sort -u`
		    do
		    if [ $fuse3 != "ioipsl" ] 
                    then
			luse3="$luse3\n$lfuse3\n\$(MODEL_LIB)($fuse3.o)"
                    fi		    
                    done
                fi
		done
        fi
	done
#- la variable dep contient l'ensemble des dependances mais peut-etre en double ou plus
#-
	for depele in `echo $luse3 | sort -u` `echo $luse2 | sort -u` `echo $luse1 | sort -u` `echo $luse0 | sort -u` `echo $dep | sort -u`
	do
	    [ ${i} = "0" ] && echo "\$(MODEL_LIB)(`echo $fic|awk -F. '{print $1}'`.o) :	\c"
	    echo "\\"
 	    echo "	$depele \c"
 	    let i=i+1 # pour signaler le premier
	done

#-
#- on ajoute la dependance avec la librairie ioipsl si besoin cad si le source contient use ioipsl
        grep -i 'use *ioipsl' ${fic} >/dev/null && ( echo "\\" ; echo "	../../../lib/libioipsl.a \c")

#- on ajoute la dependance avec KEY_CPP si il y a des include cpp
	if [ ${j} != "0" ] 
        then 
	  echo "\\"
	  echo "	KEY_CPP \c" 
	fi
#- on finit la dependance avec le fichier lui-meme et on ecrit les regles de creation
	if [ ${i} != "0" ] 
        then 
	     echo "\\"
       	     echo "	$fic"
         fi
    fi
echo $fic done >/dev/tty
done
echo '# key changing control'
echo "key: "
echo "	@echo CHANGEMENT de CLES CPP oui/non ?"
echo "	-@if [ \"\`cat KEY_CPP\`\" != \"\$(P_P)\" ] ; then \\"
echo "		echo CPP options changed ; echo \"\$(P_P)\" > KEY_CPP ; fi "
#-
#
# regle pour verifier les cles
# EK novembre 2000
# adaptation : ED + MAF decembre 2000
#
echo
echo "keyverif:"
echo '	@echo VERIFICATION DES CLES'
echo '	@echo CLES UTILISEES  : '
echo '	@for v in ` echo $(P_P) | sed  -e s/-Wp,-D//g` ; \'
echo '	do \'
echo '	echo $$v ;\'
echo '        w=`echo $$v | cut -c1-3` ; \'
echo '        if [ $$w = `echo "key"` ] ; then \'
echo '        r=n ; \'
echo '        echo " $(KEY_LIST) " | (grep $$v >/dev/null 2>&1) || r=o ; \'
echo '           if [ $$r != "n" ] ; then \'
echo '              echo "UNKNOWN KEY" ;\'
echo '              false ;  \'
echo '              exit ;  \'
echo '           fi \'
echo '        fi \'
echo '	done'
# Checking if the number of routines have been changed
echo '# Checking the number of routines'
echo "src_file_list: "
echo '	@echo CHECKING THE NUMBER AND NAMES OF SOURCE FILES '
echo '	@\$(RM) `ls | fgrep -v -f .patron` '
echo '	@if [ -d ../OCE_SRC ] ; then \'
echo '	    echo "   use OCE_SRC files"            ; \'
echo '	    ln -sf ../OCE_SRC/*.[Ffh]90          . ; \'
echo '	    ln -sf ../OCE_SRC/DYN/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/TRA/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/TRD/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/DIA/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/DOM/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/OBC/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/FLO/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/LDF/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/ZDF/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/SOL/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/DTA/*.[Ffh]90      . ; \'
echo '	    ln -sf ../OCE_SRC/SBC/*.[Ffh]90      . ; \'
echo '  fi '
echo '	@if [ -d ../ICE_SRC ] ; then \'
echo '	    echo "   use ICE_SRC files"              ; \'
echo '      ln -sf ../ICE_SRC/*.[Ffh]90            . ; \'
echo '  fi '
echo '	@if [ -d ../TRC_SRC ] && [ ! -d ../SRC_OFFLINE_TRC ] ; then  \'
echo '	    echo "   use TRC_SRC files"              ; \'
echo '      \$(RM) *.passivetrc.h ; \'
echo '      ln -sf ../TRC_SRC/*.[Ffh]          . ; ln -sf ../TRC_SRC/SMS/*.[Ffh]     . ; \'
echo '      fi '
echo '	@if [ -d ../SRC_OFFLINE_TRC ] ; then \'
echo '	    echo "   use TRC_SRC and SRC_OFFLINE_TRC files"              ; \'
echo '      ln -sf ../TRC_SRC/*.[Ffh] ../TRC_SRC/SMS/*.[Ffh] . ; \'
echo '      ln -sf ../SRC_OFFLINE_TRC/*.[Ffh] . ;  \'
echo '      fi '
echo '	@\$(RM) tmplist'
echo '	@ls -1 | fgrep -v -f .patron  >tmplist'
echo '	@cmp tmplist SRC_FILE_LIST.temp || { echo some routines have been added or suppressed ; \'
echo '	sdiff -s tmplist SRC_FILE_LIST.temp ; cp tmplist SRC_FILE_LIST.temp ; \'
echo '	\$(RM) model.o \$(MODEL_LIB) \$(SXMODEL_LIB) \$(EXEC_BIN) ; \'
echo '	echo "Rebuilding the AA_make files" ; \'
echo '	cd ..  ; ../UTIL/fait_AA_make ; echo " " ; \'
echo '	echo "THE ins_make COMMAND in modipsl/util MUST BE RERUN PLEASE DO SO BEFORE gmake" ; \'
echo '	echo "========================================== " ; \'
echo '	../../util/ins_make -t sxnec ; echo " " ;  false ; exit ; }'

