#!/bin/bash

# debe ser sudo


######################################################################################



#bin/postinst.sh "." NOMAKE "" "/usr/share/doc/sceptresimusol" "false" sceptresimusol
#bin/postinst "${PREFIX}" MAKE "${DESTDIR}" "${PKGDIR}" "$ANSWER1" sceptresimusol

#$(PREFIX)/bin/postinst "${PREFIX}" MAKE "${DESTDIR}" "${PKGDIR}" "$ANSWER1" sceptresimusol


#con NOMAKE en el tercer argumento, compila e instala (es para paquetes independientes de arquitectura de distros), luego de instalarse se compila
# es decir en distros con el make no hace nada, y con el make install copia las fuentes a src

#con cualquier otra cosa en el tercer argumento, por ejemplo instalacion de fuentes, solo instala y hace mandb y ldconfig, es para ejecturase con el sudo make install

PREFIX=$1
NOMAKE=$2
DESTDIR=$3
PKGDIR=$4
ANSWER1=$5
PACK=$6
PROG=postinst

echo PREFIX $PREFIX NOMAKE $NOMAKE DESTDIR  $DESTDIR PKGDIR $PKGDIR  ANSWER1 $ANSWER1 PACK $PACK PROG $PROG


if test x"$1" = x--help ; then
    echo $PROG-$PACK parte de las post de deb y rpm
    echo a partir de dirac
    exit 0
    fi

if test x"$1" = x--version ; then
    echo $PROG-$PACK
    echo a 
    exit 0
    fi


function compilasrc {
    
    PREFIX=$1
    NOMAKE=$2
    DESTDIR=$3
    PACK=$4
    
    
    echo function compliasrc PREFIX $PREFIX NOMAKE $NOMAKE DESTDIR $DESTDIR  PACK $PACK


    #usar vpath y compilar en tmp, instalar y borrar
    #source ${PREFIX}/share/sceptresimusol/COMPILE.LIB


    # repetidos en compila-sceptresimusol, leer
    MAKE=make
    FC=gfortran
    FFLAGS="-fno-automatic  -finit-local-zero -O -W -Wall -Wextra -g"

    SRCDIR=${PREFIX}/src 
    ACTUALUSER=`id -nu`


#    ultimo sed, por seguiridad que no existan dos directorios, un blanco
    
if test x$NOMAKE = xNOMAKE ; then
     BASETMP=`mktemp -d |sed -e's/\n//'|sed -e's/^\/tmp\///' |sed -e 's/ //g' `
     DIRCOMP=/tmp/${BASETMP}/compila
     echo COMPILANDO en ${DIRCOMP}
     mkdir -p ${DIRCOMP}
     chmod -R 777  /tmp/${BASETMP}
 
     #ls -l ${DIRCOMP}
     #su $USERNAME -s /bin/sh -c "/usr/bin/compila-sceptresimusol '$DIRCOMP' '${SRCDIR}/packages/${PACK}' '$PREFIX'  '$DESTDIR' '$PKGDIR' "

     if test x"$ACTUALUSER" = xroot ; then
         USERNAME=
         USERID=0

         for USERDIR in /home/* ; do
           U2=`cat /etc/passwd| grep "$USERDIR" | cut -d: -f1 | head -n1`
           if test x"/home/$U2" = x"$USERDIR" ; then
                NU2=`cat /etc/passwd| grep "$USERDIR" | cut -d: -f3 | head -n1`
	        if test x"$NU2" != x"0" ; then
	          USERID=$NU2
	          USERNAME=$U2
	          break;
	          fi
                fi	
           done

         echo UNUSUARIO: $USERID - $USERNAME
         if test x"$USERNAME" != x ; then
	   chown -R $USERNAME /tmp/${BASETMP}
           su $USERNAME  -c "cp -a  ${SRCDIR}/packages/${PACK}/*  $DIRCOMP"
           su $USERNAME  -c "make -C \"$DIRCOMP\" \"PREFIX=$PREFIX\"  \"DESTDIR=$DESTDIR\" \"PKGDIR=$PKGDIR\" compila "
	 fi
     else
	 echo "cp -a  ${SRCDIR}/packages/${PACK}/*  $DIRCOMP"
         cp -a  ${SRCDIR}/packages/${PACK}/*  $DIRCOMP
	 ls $DIRCOMP
         make -C "$DIRCOMP" "PREFIX=$PREFIX"  "DESTDIR=$DESTDIR" "PKGDIR=$PKGDIR"  compila
  fi	 
else
   echo FUENTES EN $DIRCOMP
   DIRCOMP=${SRCDIR}/packages/${PACK}
fi


#! cambio de -e habia -x

if test ! -e $DIRCOMP/compila ; then
    ls $DIRCOMP
    echo ERROR: $(PACK) no esta compilado salir
    exit 1;
fi



#echo NO OLVIDE BORRAR ARCHIVOS EJECUTABLES ESPECIALMENTE DE /usr/local  o de /home/USER/bin
# ya esta con finbinlib

make -C "$DIRCOMP" "PREFIX=$PREFIX"  "DESTDIR=$DESTDIR" "PKGDIR=$PKGDIR"  install

# hace mas que clean
if test x$NOMAKE = xNOMAKE ; then
    echo Borra compila
    rm -rf /tmp/${BASETMP}/compila
    rmdir /tmp/${BASETMP}
  fi

}

 
#findbinlib provisto por summapack



PREFIX=$1
NOMAKE=$2
DESTDIR=$3
PKGDIR=$4
ANSWER1=$5
echo PACK $PACK PREFIX $PREFIX NOMAKE $NOMAKE DESTDIR  $DESTDIR PKGDIR $PKGDIR  ANSWER1 $ANSWER1


#$(PREFIX)/bin/postinst-sceptresimusol "${PREFIX}" MAKE "${DESTDIR}" "${PKGDIR}" "$ANSWER1"

# bin/postinst-sceptresimusol.sh "/usr" "" MAKE "" true

#con NOMAKE en el tercer argumento, compila e instala (es para paquetes independientes de arquitectura de distros), luego de instalarse se compila
# es decir en distros con el make no hace nada, y con el make install copia las fuentes a src

#con cualquier otra cosa en el tercer argumento, por ejemplo instalacion de fuentes, solo instala y hace mandb y ldconfig, es para ejecturase con el sudo make install

if test -d ${PREFIX}/src  ; then
    #&& ! -e ${PREFIX}/src/package/$(PACK)/compila  es complicado porque adentro lo copia a un tmp, debe resolverse adentro esto
    # estudiar bien .phony compila  y demas
    compilasrc  "$PREFIX"  "$NOMAKE"  "$DESTDIR" "$PACK"
fi


#PREFIX=.

#usar vpath y compilar en tmp, instalar y borrar
#source ${PREFIX}/share/sceptresimusol/COMPILE.LIB



# repetido en config
BUSCA="plotgnu postinst-$PACK repite $PACK tests"
BUSCALIB=''
#BUSCALIB="lib*for.so* lib*for.so* sceptre2.o libsceptre.a  libsceptreaux.a"
#

if test -e lib ; then 
    cd lib; DIRPM=`ls */* | tr "\n" " "`;
else
    DIRPM=
fi

#findbinlib provisto por summapack

if test x$ANSWER1 = xtrue ; then
    SALIDA=`findbinlib "$BUSCA" "$BUSCALIB" BORRA "$DIRPM" "$PACK"`
    if test x"$SALIDA" != x ; then
	echo Mueve versiones de archivos instaladas previamente a /tmp/${PACK}moved,	
        echo hechas con los paquetes fuentes, en ubicaciones especiales:
	echo $SALIDA
        # ya sabiamos que habia ANSWER1 es TRUE   
        for FILE in $SALIDA; do
	  echo FUE MOVIDO $FILE  
	  done;
        fi  
    fi    
  
if test x$NOMAKE != xNOMAKE ; then
   mandb >/dev/null 
 fi




USERS=`ls /home`

# cual install-sceptresimusol usa?

#elif test -e /usr/local/share/$PACK ; then
#    SHAREDIR="/usr/local/share/$PACK"
#elif test -e /usr/share/$PACK ; then
#    SHAREDIR=/usr/share/$PACK
#else#

#fi    

# ojo si se hace como sudo, ejecutar como cada usuarios

if test x"$USERID" = x0 ; then
       # instalo todos los usuarios menos root
       for USER in ${USERS} ; do    
	       ESUSER=`grep "^$USER:" /etc/passwd| awk -F':' '{print $1}'`; 
	       if test x"$ESUSER" != x ; then
		 echo installuserfiles  $USER $PACK $PREFIX
	         installuserfiles  $USER $PACK $PREFIX
       	         #echo "	icon_install  $USER ${PREFIX}/share/${PACK}/launchers " ;
	         #icon_install  $USER ${PREFIX}/share/${PACK}/launchers;
	       fi; 
	     done;
else
        # no soy root, solo instalo al usuario (prefix=/home)    
        echo installuserfiles  $USERACTUAL $PACK $PREFIX
        installuserfiles  $USERACTUAL $PACK $PREFIX
fi    



echo FIN postinst



#install -s -m 755 ${SRCDIR}/phase1/sceptre1       ${BINDIR}
#install -s -m 755 ${SRCDIR}/auxpro/ngp_gnu        ${BINDIR}
#install -m 644    ${SRCDIR}/phase2/sceptre2.o        ${LIBDIR}
#install -m 644    ${SRCDIR}/phase2/libsceptre.a      ${LIBDIR}
#install -m 644    ${SRCDIR}/auxpro/libsceptreaux.a   ${LIBDIR}

#postinst
#pretest-sceptresimusol.pl  sceptresimusol-install

#BINFILES="${SRCDIR}/${PACK}/phase1/sceptre1 ${SRCDIR}/${PACK}/auxpro/ngp_gnu "

#LIBFILES="${SRCDIR}/${PACK}/phase2/libsceptre.a ${SRCDIR}/${PACK}/phase2/sceptre2.o ${SRCDIR}/${PACK}/auxpro/libsceptreaux.a ${SRCDIR}/${PACK}/extras/libtabularfor.so.1.0.1  ${SRCDIR}/${PACK}/extras/libradiafor.so.1.0.1" 

# 






#LIBDIR=/lib
#BINDIR=/bin
#for FILE in ${BINFILES} ; do#
#		FILEP=`basename  ${FILE}`;
#		install -m 755  ${FILE} $PREFIX/$BINDIR/$FILEP  ;
#		echo "A:${PREFIX}${BINDIR}/${FILEP}" >> listado.ls ;
#		echo "A:${PREFIX}${BINDIR}/${FILEP}" ;
#		done;

#for FILE in ${LIBFILES} ; do
#		FILEP=`basename  ${FILE}`;
#		echo XX $FILE XX $FILEP  XX ${PREFIX} XX ${LIBDIR} ;
#		install -m 644  $FILE $PREFIX/$LIBDIR/$FILEP  ;
#		echo "A:${PREFIX}${LIBDIR}/${FILEP}" >> listado.ls ;
#		echo "A:${PREFIX}${LIBDIR}/${FILEP}"  ;
#		done;

#ls


