#/usr/bin/env bash

DESTDIR=no
while [ $# -ne 0 ]  ; do
    argsp=$args
    args="$args '$1'"
    case "$1" in
	-[h?]*) echo usage $0 ""
	    exit 0;
	    ;;
	DIRMPI=*) MPI=`echo $1|sed 's/[A-Z0-9]*=//'` ;; 
	DESTDIR=*) DESTDIR=`echo $1|sed 's/[A-Z0-9]*=//'` ;; 
    *);;
    esac; 
    shift
done
prefix=$(grep '"prefix"' config.status|awk -F'"' '{print $4}')
bindir=$(grep '"bindir"' config.status|awk -F'"' '{print $4}')
ff_prefix_dir_lib=$(grep '"ff_prefix_dir_lib"' config.status|awk -F'"' '{print $4}')
echo prefix=$prefix
echo lib=$prefix/lib
echo biblib=$bindir
echo rlib=../lib
execrlib=@executable_path/$rlib
if [ test $(dirname $bindir) != "prefix" ] ; then
	echo wrong place to change dylib for install
fi
echo "DESTDIR=$DESTDIR ."
if test "$DESTDIR" = no ; then
	echo "usage $0 DESTDIR=/tmp/ff++ MPI=MPIcompiledir"
	exit 1;
fi
if [ ! -f src/Graphics/sansrgraph.cpp ] ; then
  echo " Not in FreeFrem++ current dir :$PWD"
  exit 1;
fi
mkdir -p "$DESTDIR"
DESTDIR=`realpath $DESTDIR`

dylib_of() {
 
 #  otool -L $*|egrep -v '/System/Library/Frameworks/|/usr/lib/'| awk -F '[ *:]' 'NR>2 {if($1) {print $1}}'|sed 's/	*//g'  | sort -u | >&2 grep -v "$DESTDIR"
  otool -L $*|egrep -v '/System/Library/Frameworks/|/usr/lib/|@rpath'| awk -F '[ *:]' 'NR>2 {if($1) {print $1}}'|sed 's/	*//g'  | sort -u | grep -v "$DESTDIR";
}
if [ ! -d $DESTDIR ]  ; then
  echo dir $DESTDIR is no created
  exit 1;
fi
MPIRUN=`awk '$1=="MPIRUN" {print $3}'  Makefile`
MPICC=`awk '$1=="MPIRUN" {print $3}'  Makefile`
FC=`awk '$1=="FC" {print $3}'  Makefile`
FF_prefix_petsc=`awk '$1=="FF_prefix_petsc" {print $3}'  Makefile`

# install lib fortran
# install mpi
# install petsc 
# install ggplugin libs
if [ -n "$DIRMPI" -a -d  "$DIRMPI" ] ; then
( cd $DIRMPI; make install DESTDIR=$DESTDIR )
if [ $? -ne 0 ] ; then
  echo error install MPI 
  exit 1; 
fi
fi
make 
make 
# build the lis of external 
Get-list-dylib-use
make install DESTDIR="$DESTDIR"

// get relativ path of 
MKL=no
ffcpf=/tmp/copy-dylib.$$.txt
rm $ffcpf 
for i in $(cat etc/list-dylib|grep -v /intel/) ;do
	d=$(dirname $i)
	dl=$(dirname $i)
	bi=$(basename $i)
	case $i in
	*/ff-petsc/*)
		echo mkdir -p $DESTDIR/$d;
		echo cp $i $DESTDIR/$d;;
	/usr/local/ff++/*)
		echo mkdir -p $DESTDIR/$lib;
		echo cp $i $DESTDIR/$lib
		echo $DESTDIR/$lib/$i $bi $execrlib  >> $ffcpf 
		;;
	*libmkl_*)	MKL=yes;;	
   esac
done
if test $MKL = "yes" ; then
	for i in $(list-dylib-mkl) ;do
		bi=$(basename $i)
		echo cp $i $DESTDIR/$lib
		echo $DESTDIR/$lib/$i $bi $execrlib >> $ffcpf
	done
fi
#  update lib in distrib ..
bin/change-dylib $ffcpf $DESTDIR/$lib/*dylib
bin/change-dylib $ffcpf $DESTDIR/$lib/*dylib
bin/change-dylib $ffcpf $DESTDIR/$lib/*dylib
bin/change-dylib $ffcpf  $(find $DESTDIR/$ff_prefix_dir_lib -name '*dylib')
for i in FreeFem++		FreeFem++-mpi	FreeFem++-nw	bamg		cvmsh2			ffglut			ffmedit;do
	bin/change-dylib $ffcpf $DESTDIR/$bindir/$i 
done



