#
# **************************************************************
# *                  SIMUSOL PROYECT                           *
# *                                                            *
# *         dia-simusol for SIMUSOL                                    *
# *                                                            *
# *                                                            *
# *   Developed by                                             *
# *   Diego.Saravia@gmail.com, 2016                            *
# *   and could be used with GPL                               *
# *   or every free license with copyleft needed.              *
# *   http://www.simusol.org                                   *
# **************************************************************

# This file is part of simusol-pack
#
#    dia-simusol is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Table is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Table.  If not, see <http://www.gnu.org/licenses/>.

BASETMP := $(shell $(shellpath) mktemp -d |sed -e's/\n//'|sed -e's/^\/tmp\///')
# con := permanece cte
$(info BASETMP: ${BASETMP}) 
#BASETMP=`mktemp -d`;

# debe instalar dia y dia-simusol en /usr/local
# y lo de dia en /usr si hay un dia alli
# asi el dia-simusol y el dia comun tienen todo lo que pueden del simusol

# PREFIX  puede ser modificada (override) com argumento en la linea de comando
# make PREFIX=/pepito
# instala   sheets y shapes dia, documentos
USERID=$(shell id -u)

#PACK=$(shell  ls *.summa| sed -e s/\.summa$$//)
#package_version_architecture.package-type
#package-name-1.0-0~201~ubuntu14.04.1
UBUNTU=$(shell cat /etc/issue| grep Ubuntu)
$(info UBUNTU: ${UBUNTU}) 
USERACTUAL=$(shell id -un)
USERBASE=$(shell ls -l Makefile| awk -F' ' '{print $$3}' )
$(info User Id is $(USERID) - $(USERACTUAL) - ${USER} - Su ${SUDO_USER} - BASE ${USERBASE})
define findfirst
$(shell $(shellpath) test -x /usr/$1  && echo /usr;\
                 test -x /usr/local/$1  && echo /usr/local;\
                 test -x ~/$1  && echo ~;)
endef

# el prefix del dia normal, el ejecutable del dia que instala simusol  debe ser dia-simusol
PREFIXDIA=$(call findfirst,bin/dia)
$(info PREFIXDIA: ${PREFIXDIA})

SUDO=sudo

#NAME=dia-simusol
VERSION=2017-0.1
# SACARLA version  DE SUMMA
PACK=$(shell  ls *.summa| sed -e s/\.summa$$//)
PACKV=$(shell echo -n $(PACK)|sed -e  's/\-/_/')
# PACKV corrije, si el nombre tiene - lo pasa a _, no es conveniente nombres de paquetes con - en las tgz o tar.gz
# tgz se usa en paquetes AI o SRC/BIN/DOC/DEV, AI es de arquitectura independiente, si no lo es se divide en cuatro SRC BIN DEV y DOC
DIRICON=$(PACK)
$(info PAQUETE: ${PACK} , ${DIRICON}) 


#Create a root owned .desktop file in /etc/xdg/autostart folder for all users to access, and for Exec= line , create a symbolic link to the program you want users to access. For instance,
#ln -s /usr/share/applications/gedit.desktop /home/$USER/Desktop/gedit-link
#The link will be created on user's desktop every time they log in.

# solo correr bajo SUDO o sea userid = 0 
# como dia se instala en /usr solo lee sheets en /usr
#http://askubuntu.com/questions/522949/adding-my-launcher-to-the-unity-launcher-automatically-how

# no sirve lo anterior, porque al hacer dist, se debe usar /usr/local y no ser root

# no uso mas el punto para los paquetes HOME
PREFIX=/usr/local
SPREFIX=\/usr\/local

#PREFIXDOC=${PREFIX}${DOT}${DOC}
#PREFIX=${PREFIXP}/share
#PREFIXS=${PREFIXP}/lib
#PREFIXD=/usr/share
#DOT=/
#DOC=doc/simusol
# mientras dia se insatle como paquete usar /usr, si no /usr local
#PREFIXDIA=/usr
#PREFIXDIASIMUSOL=/usr/local
#PREFIXSIM=${PREFIXS}${DOT}simusol
#PREFIXDIA=${PREFIXD}${DOT}dia
#PREFIXDOCS=${PREFIX}${DOT}${DOC}



USERS=`ls /home`



BINDIR=bin
#ETCRES=etc/simusol
ETCDIR=/etc
SHAREDIR=share
#/dia-simusol/data
PKGDIR=share/dia-simusol/pkg-data



BINDIRSRC=bin/
#ETCDIRSRC=etc/
SHAREDIRSRCDIA=share/
SHAREDIRSRC=share/
PKGDIRSRC=


IBINFILES=$(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep ^\./$(BINDIRSRC) | grep -v '^\#' | grep -v '~$$')

ISHAREFILESDIA=$(shell $(shellpath) cd dia; find -type f -not -wholename '*.svn*'| grep ^\./$(SHAREDIRSRCDIA) | grep -v '^\#' | grep -v '~$$')
ISHAREFILES=$(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep ^\./$(SHAREDIRSRC) | grep -v '^\#' | grep -v '~$$')

#IETCFILES=$(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep ^\./$(ETCDIRSRC) | grep -v '^\#' | grep -v '~$$')

IPKGFILES =$(shell /bin/ls -l $(PKGDIRSRC) 2>/dev/null | grep '^-' |  awk -F' ' '{print $$9}' | grep -v '^\#' | grep -v '~$$'| grep -v 'listado.ls')

ISHAREDIRSDIA=$(shell $(shellpath)  cd dia; find -type d -not -wholename '*.svn*'| grep ^\./$(SHAREDIRSRCDIA) )

ISHAREDIRS=$(shell $(shellpath) find  -type d -not -wholename '*.svn*'| grep ^\./$(SHAREDIRSRC) )

IFILDESKTOP=$(shell find  -type f -not -wholename '*.svn*'| grep  ".desktop" )   # launchers/


$(info IBINFILES $(IBINFILES))
$(info ISHAREFILES $(ISHAREFILES))
$(info ISHAREDIRS $(ISHAREDIRS))
$(info ISHAREFILESDIA $(ISHAREFILESDIA))
$(info ISHAREDIRSDIA $(ISHAREDIRSDIA))
$(info IETCFILES $(IETCFILES))
$(info IPKGFILES $(IPKGFILES))

define installdirs
	@echo D Ultimoarg============================= $3
	@for FILE in $1  ; do \
	   if test x"$$FILE" != x"." ; then \
	    FILEP=`echo -n $$FILE|sed -e  's/\.\/$3//' ` ;\
	    install  -d $2/$$FILEP;\
	    echo "D:$2/$$FILEP" >> listado.ls ;\
	   fi;\
	done;
endef

define installfiles
	@echo F Ultimoarg============================ $3
	@for FILE in $1 ; do \
	   if test x"$$FILE" != x"." ; then \
	    FILEP=`echo -n $$FILE|sed -e  's/\.\/$3//' ` ;\
	    if test x"$5" = x ; then \
		FILEC=$$FILE; \
	      else \
                FILEC=`echo $$FILE|  sed -e  's/^\./\.\/$5/'`; \
	      fi;\
	    install $$FILEC  $2/$$FILEP;\
	    echo "A:$2/$$FILEP" >> listado.ls ;\
	   fi;\
	done;
endef

#	$(call copytree,$(PREFIXDIA),$(ETCDIR),$(SUDO))
define copytree
	echo NN $1
	$3 mkdir -p $1/share
	$(call installdirs,${ISHAREDIRS},$1,,$3)
	$(call installfiles,${ISHAREFILES},$1,,$3,)
	$3 mkdir -p $1/${BINDIR}
	$(call installfiles,${IBINFILES},$1,,$3,)
	$3 mkdir -p $1/${PKGDIR}
	$(call installfiles,${IPKGFILES},$1/${PKGDIR},,$3,)
	$(call installfiles,${IPKGFILES},$1,,$3,)
        $3 mkdir -p $2
	$(call installfiles,${IETCFILES},$2,,$3,)
endef




### eliminar en el .dia de cada usuario todo pero ver si el usuario no tiene algo propio
# es complejo




all: install



install:
	$(call installdirs,${ISHAREDIRSDIA},$(PREFIXDIA),,$(SUDO))
	$(call installfiles,${ISHAREFILESDIA},$(PREFIXDIA),,$(SUDO),dia)
	$(call copytree,$(PREFIX),$(ETCDIR),$(SUDO))
	chown ${USERBASE}:${USERBASE} listado.ls 
	make inslaunchers
	install -d ${PREFIX}/simusol/ls
	mv  ${PREFIX}/simusol/ls/${PACK}.ls ${PREFIX}/simusol/ls/${PACK}.ls.viejo 2>/dev/null; exit 0;
	install listado.ls ${PREFIX}/simusol/ls/${PACK}.ls
	echo BORRE TODO LO QUE TENGA EN SU DIRECTORIO OCULTO .dia, a menos que ud sepa que tiene algo de su interes.

#

installdist:
	echo PACKAGE DISTRIBUTION FILE ${PACK} (architecture independent)
	rm -rf /tmp/$(BASETMP) ; 
	mkdir -p /tmp/$(BASETMP) ;
	$(call installdirs,${ISHAREDIRSDIA}, /tmp/${BASETMP},,$(SUDO))
	$(call copytree, /tmp/${BASETMP}, /tmp/${BASETMP}/$(ETCRES),) 
	cd  /tmp/${BASETMP}; tar -zcvf $(CURDIR)/../${PACKV}-${VERSION}-AI.tgz .

dist:
	echo SOURCE DEVELOPMENT DISTRIBUTION FILE ${PACK}
	rm -rf /tmp/$(BASETMP)
	mkdir -p /tmp/$(BASETMP)/${PACK}-${VERSION}
	cp -La .  /tmp/${BASETMP}/${PACK}-${VERSION} 
	tar -C /tmp/${BASETMP} -zcvf $(CURDIR)/../${PACKV}-${VERSION}.tar.gz ${PACK}-${VERSION}


SERVERUSER=www-data
SERVERSUBIR=simusol.org
SERVERDIR=/var/www/simusol.org/public_html/downloads

upload: dist 
	md5sum  ../${PACKV}-${VERSION}.tar.gz>../${PACKV}-${VERSION}.tar.gz.md5
	wget -O SP.md5 http://www.simusol.org/downloads/${PACKV}-last.tar.gz.md5; exit 0;
	touch SP.md5 ;
	DIF=`diff SP.md5  ../${PACKV}-${VERSION}.tar.gz.md5` ;\
	rm -f diff SP.md5 ; \
	if test x"$$DIF" != x ; then \
	   echo "DIF= $$DIF"; \
	   scp ../${PACKV}-${VERSION}.tar.gz.md5  ../${PACKV}-${VERSION}.tar.gz $(SERVERUSER)@$(SERVERSUBIR):$(SERVERDIR) ;\
	   ssh $(SERVERUSER)@$(SERVERSUBIR) "cd $(SERVERDIR); rm -f ${PACKV}-last.tar.gz; ln -s ${PACKV}-${VERSION}.tar.gz ${PACKV}-last.tar.gz; rm -f ${PACKV}-last.tar.gz.md5; ln -s ${PACKV}-${VERSION}.tar.gz.md5 ${PACKV}-last.tar.gz.md5";\
	fi;
	rm -f *.md5; exit 0




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


#ESUSER solo para verificar que esta en passwd
#echo ESUSER"$$ESUSER"X;\
#	    echo "sed -i'' -e 's/YYY/${SPREFIXDOCS}/'  ${PREFIX}/share/${DIRICON}/launchers/$$KKK" ;\
#    sed -i'' -e 's/YYY/${SPREFIXDOCS}/'  ${PREFIXP}/share/${DIRICON}/launchers/$$KKK;\

inslaunchers:
	for FILE in ${IFILDESKTOP} ; do \
	   if test x"$$FILE" != x"." ; then \
	    echo "JJJ $$FILE"; \
	    KKK=`echo $$FILE | sed -e's/\.\/share\/dia-simusol\/launchers\///'`; echo "MMMMMM $$KKK"; \
	    install  $$FILE  /usr/share/applications/$$KKK;\
	    chmod -x  /usr/share/applications/$$KKK;\
	    echo "sed -i'' -e 's/XXX/${SPREFIX}/'      ${PREFIX}/share/${DIRICON}/launchers/$$KKK" ; \
	    sed -i'' -e 's/XXX/${SPREFIX}/'      ${PREFIX}/share/${DIRICON}/launchers/$$KKK;\
	   fi;\
	   for USER in ${USERS} ; do \
	       ESUSER=`grep "^$$USER:" /etc/passwd| awk -F':' '{print $$1}'`; \
	       if test x"$$ESUSER" != x ; then \
	         echo "	icon_install  $$USER ${PREFIX}/share/${DIRICON}/launchers " ;\
	         icon_install  $$USER ${PREFIX}/share/${DIRICON}/launchers;\
	       fi; \
	     done;\
	done;


#USERS=`ls /home`		
#if test x$(USERID) = x0 ; then #
#	    for USER in ${USERS} ; do 
#             echo USER $$USER; 
#	     if test -d /home/$$USER ; then 
#	      echo BUENUSER $$USER; 
#             ESUSER=`grep "^$$USER:" /etc/passwd| awk -F' ' '{print $$1}'`;
#	      echo BUENUSER $$USER $$ESUSER; 
#	      
#                # instalar en un usuario	       
#	      fi;
#	     done;
#	    else 
 #                # instalar en un usuario	       
#	    fi;
#	done; 

