#!/usr/bin/make -fXXX.
# GPLV3+  Diego.Saravia@gmail.com
ojoVERSION=0.56
#, se cruza con simusol-make.summa



# instalar summapack y pack o simpack
#### ojo ejecutar "sudo make -f simusol-make sedmakefile" o como se llame para autoinstalar


#dia --nosplash --size=1024 -e ttt.png tanquebgui.dia 

# size in pixels not sure

### PROBLEMAS SI SE USA sudo make install
# deja regalitos en el home del usuario ~/lib ~/.dia ~/.cpanm .simusolbash .bashrc .bashprofile
# .gnupg
# .gnuplot-wxt supongo que el ejemplo de simusol-gui todos estos propiedad de root
# usar sudo su; luego make install
# asi solo queda INSTALA_COMPANION
# la mayoria de los problemas lib, cpanm etc se causan por el ejemplo gui

# esto es para win32

# C:\Dwimperl\perl\bin\wperl.exe C:\cygwin\bin\simusol-gui.pl

#> to the very end of /etc/profile.  It's probably not the 'right' way to do it,
#> but who cares.  It works fine.

#Well, the "official" way of doing this is to delete your ~/.bash_profile
#and reinstall the "base-files" package (or simply "cp -p
#/etc/defaults/etc/skel/.bash_profile ~").  Alternatively, you can simply
#"ln -s ~/.bashrc ~/.bash_profile".
#http://puracoding.wordpress.com/2007/09/28/cygwin-wont-read-bashrc/
#http://tobiascohen.com/2009/08/26/making-cygwin-look-at-your-bashrc/
#function path(){
#    old=$IFS
#    IFS=:
#    printf "%s\n" $PATH
#    IFS=$old
#}
#http://www.cyberciti.biz/faq/redhat-linux-pathmunge-command-in-shell-script/
#pathmunge () {
#        if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then
#           if [ "$2" = "after" ] ; then
#              PATH=$PATH:$1
#           else
#              PATH=$1:$PATH
#           fi
#        fi
#}

#poner esto en el .bash_profile
#[[ -r ~/.bashrc ]] && . ~/.bashrc

#http://stackoverflow.com/questions/415403/whats-the-difference-between-bashrc-bash-profile-and-environment

#it was on ./cygwin/etc/skel/.bash_profile

# bash profile ~./bash_profile
# source the system wide bashrc if it exists
#if [ -e /etc/bash.bashrc ] ; then
#  source /etc/bash.bashrc
#fi

# source the users bashrc if it exists
#if [ -e "${HOME}/.bashrc" ] ; then
#  source "${HOME}/.bashrc"
#fi


#http://padre.perlide.org/download.html

#http://cygwin.com/ml/cygwin/2007-01/msg00520.html  cygports
#http://www.mpi-inf.mpg.de/~dfischer/manual/manual_topic38.html
#http://upx.sourceforge.net/
#http://search.cpan.org/~autrijus/PAR-0.85_01/script/pp
#http://www.andre-simon.de/doku/wxwidgets/devpak_install.html
#http://www.wxperl.co.uk/strawberry.html
#http://search.cpan.org/dist/Wx-Perl-Packager/bin/wxpar
#http://www.nntp.perl.org/group/perl.wxperl.users/2010/08/msg7474.html
#http://wiki.tcl.tk/11329

# gnuplot sudo apt-get install  libgd2-xpm-dev
# ./configure --without-x

#emacs cygwin
#http://www.khngai.com/emacs/cygwin.php

# ojo cygwin vi que firewall de windows bloquio acceso de perl.exe a internet, tambien cygwin

#PERL_MM_USE_DEFAULT=1 perl -MCPAN -e 'install My::Module'
#It should make CPAN answer the default to all prompts.
#cpan> o conf prerequisites_policy follow
#cpan> o conf commit


#Ultima version: http://www.simusol.org.ar/downloads/Makefile

#Instrucciones de instalacion de SimuSol:
# make install | sudo make install
#http://xn--cgi.ws/Li
# esta make se instala a si mismo, unico archivo que es necesario bajar a mano, autoinstalable

SHELL=/bin/bash
PATH := ${HOME}/bin:/usr/local/bin:${PATH}
DESTINO=.

#PATH=/bin:$(PATH);
#WHOME =`perl -MWin32 -MFile::Basename -e 'print Win32::GetFolderPath(0x0000)`

#SM: sedmakefile

ifeq (Cygwin,$(shell /bin/uname -o))
          FC=g77
          shellpath = 
          WAPP  = $(shell perl -MWin32 -MFile::Basename -e 'print Win32::GetFolderPath(0x0026)'|sed -e's/^\([A-Z]:\)/\L\1/'|sed -e's/:\\/\//'|sed -e's/\\/\//g'|sed -e's/ /\\ /g')
          PREFIXDIAW=/cygdrive/$(WAPP)/Dia

define SIMUSOLBASH
pathmunge () {
        if ! echo $$PATH | /bin/egrep -q "(^|:)$$1($$|:)" ; then
           if [ "$$2" = "after" ] ; then
              PATH=$$PATH:$$1
           else
              PATH=$$1:$$PATH
           fi
        fi
}
pathmunge /usr/bin
pathmunge /usr/local/bin
pathmunge ~/bin
pathmunge `cygpath -S` after
pathmunge `cygpath -W` after
endef

installcompanion: cyginstallcompanion
#is: cygcpanm installsoftware


######################################ojo esto suele ser install desde las fuentes
sedmakefile:
	@echo Instalo Makefile $(ESTEMAKE) en /bin/simusol-make
	@install -d /bin
	@install $(ESTEMAKE) /bin/simusol-make; exit 0;
	@$(call sedmake,,)

else
          FC=gfortran
          shellpath=
          WAPP=

define SIMUSOLBASH
pathmunge () {
        if ! echo $$PATH | /bin/egrep -q "(^|:)$$1($$|:)" ; then
           if [ "$$2" = "after" ] ; then
              PATH=$$PATH:$$1
           else
              PATH=$$1:$$PATH
           fi
        fi
}

pathmunge /usr/bin
pathmunge /usr/local/bin
pathmunge ~/bin
pathmunge /usr/x11R6/bin after

endef


installcompanion: lininstallcompanion 


sedmakefile:
	@echo Instalo Makefile $(ESTEMAKE) en ${PREFIX}/bin/simusol-make
	@install -d ${PREFIX}/bin
	@install $(ESTEMAKE) ${PREFIX}/bin/simusol-make; exit 0;
	@$(call sedmake,${PREFIX},${SPREFIX})

endif

#ifeq (Cygwin,$(shell /bin/uname -o))
#else
#endif

export SIMUSOLBASH


#	echo 'PATH=~/bin:/usr/local/bin:/usr/bin:$$PATH:.:/usr/x11R6/bin' >>~/.bashrc
#	echo PATH=~/bin:/usr/local/bin:/usr/bin:'$$PATH':.:/usr/x11R6/bin:`cygpath -S`:`cygpath -W`' >>~/.bashrc

#	echo '[[ -r ~/.bashrc ]] && . ~/.bashrc' >>~/.bash_profile



#DESTINO para overload, donde pone el paquete


#ToDo

#SIMPACK CONTENDOR ver shapedir
# avisar en la interfaz si es vacio
# cambiar copying.doc por  docs
# verificar porque instala soft y cuando
# debiera crear su propia .summa y licencias etc si es necesario
# como parte de los objetivos, si se ejectua y no esta instalado, instalarse, y copiar su summa donde debe. en simusol/share
# tambien subir al repo como gz y zip
# se cambia dia y no cambia 
# se hace clean y tampoco 
# solo haciendo cleanall se reejecuta


# errores vistos con cygwin
# creo que el cpan solo funciona bien luego de arrancar windows despues de instalar cygwin
# REVISAR SUDO
# xdg-icon sacar para cygwin
# cambiar Makefile del sceptre para usar g77
# el make confunde el objetivo install con el archivo  INSTALL  del paquete

####################################################################################################
define HELPMSG
 Este es un Makefile genérico para un paquete/proyecto dia, basta copiarlo en un directorio vacio,
 en una maquina que no tiene sceptre, simusol, simpack, simusol-gui, skeleton 
 o dia, firefox, gcc, etc para que instale todo lo que se requiere, cree la estructura standard para
 un proyecto, el archivo .summa y de no existir, un .dia vacio.

Descarga e Instalación en cualquier GNU/Linux, en Windows instale LiberaWin.exe

Requiere tener instalado gnu-make.
Descargue el Makefile maestro de los proyectos/paquetes de Simusol:
Última version: http://www.simusol.org.ar/downloads/Makefile

Ubíquelo dentro de cualquier directorio (donde no exista otro Makefile), y  para instalar Simusol
ejecute:

          sudo make install|update  (como root para todos los usuarios)
          make install|update       (para un solo usuario)

algunos paquetes podran no ser instalados sin sudo.
a partir de la instalacion se puede ejecutar como simusol-make
update actualiza, install solo instala si no esta.

para instalar en la maquina de desarrollo hacer make upmake (upload make, lo hara subir al sitio y lo instalar en otros paquetes e instalara simusol-make)

para instalar los programas de simusol, changebash y acompañantes  simusol-make install
para modificar profile y bashrc                                    simusol-make changebash
para instalar los programas de simusol                             simusol-make installsimusolall
para instalar los programas de los que depende simusol             simusol-make installcompanion
para hacer update de simusol, changebash y acompañantes            simusol-make update
para hacer update los programas de simusol                         simusol-make updatesimusolall
para hacer update de los programas de los que depende simusol      simusol-make updcompanion


a partir de la instalacion debe quedar un icono en el escritorio, 
con él se accede a la interfaz gráfica.

 para usarlo:
     Utilice la interfaz gráfica o
     Para iniciar un proyecto cree un directorio con el nombre que quiera darle al proyecto,
     ejecute 

         simusol-make 

     o copie este Makefile alli, y ejecute make, luego edite el dia y con 

         simusol-make view

      vea los resultados 

 Esta ayuda:                          
             make  help 
             simusol-make help

 para ejecutar llamar:                
             cd pp1; simusol-make
             simusol-make dirpro=pp1
             simusol-make dirpro=pp1 wdir=
             cd pp1; make

 para ver resultados llamar:          simusol-make 
 para etapas individuales llamar:     simusol-make [simusol|sceptre|graf|view|display|installpack|pack]
 o para simulaciones individuales     simusol-make simulacion1.sceptre|simulacion1.simul|simulacion1.view 
 donde simulacion1.dia o simulacion1.d se procesan

 para  projects/simulacion2.dia      simusol-make projects/simulacion2.view

# usar simul1.simusol, simul1.sceptre .view
# pasar dia a ddia

cleanmake                          son los controles de ejecucion del make que van al directorio corriente 
cleantest cleantmp cleanresults    son los lugares donde almacena los resultados generalmente el corriente 
                                   pero puede ser cambiado con wdir=
cleanss cleanwdir cleanmake        donde trabaja simusol/sceptre generalmente /tmp/pruebamake

                                                  clean: cleanss cleantmp cleanmake
                                               cleandep: cleanss cleantmp cleantest cleanmake
                                               cleanall: cleanss cleanwdir cleanmake



 para borrar intermedios makefile llamar:         simusol-make cleanmake
 para borrar intermedios simusol/sceptre llamar:  simusol-make cleanss
                                                  simusol-make cleanssresults|cleansstest|cleansstmp
 para borrar archivos escritos                    simusol-make cleanwdir
                                                  simusol-make cleanresults|cleantest|cleantmp

 para dejar de ver resultados llamar: make dirpro=estees killmuestra




 relativos a los proyectos y simpack
 para verificar que el paquete sea correcto   make test
 para instalar el paquete  en el arbol        make installpack  
 para generar un .s.tgz con el paquete        make pack
 para poner el paquete en el repo local       make repo
 para subir el paquete al sitio               make upload

 esto hacia la interfaz, no lo recuerdo muy bien como
 make backup
 make rmbackup
 make comparar
 make listabackup


      
      Los proyectos suelen tener el mismo Makefile en su directorio, en tal sentido es un archivo autoinstalable, que instala y coordina el uso de SimuSol. Si Ud. recibe un paquete SimuSol, y lo desempaqueta con tar/gzip,  tiene acceso a Internet y este servidor esta funcionando, ejecutando make install, tambien podra instalar SimuSol.

     En algunos sistemas, si ud es el primer usuario que instala SimuSol, requerirá si o si, instalarlo como Supervisor, ya que el makefile instala software que no sabe operar sin instalarse en áreas de su computadora que el usuario no puede cambiar.

    Si la instalacion fue exitosa, aparecerá un icono apropiado para ejecutar la interfaz gráfica.

Nota: el Makefile se instala como ejecutable bajo el nombre simusol-make, por lo que funcionara ejecutandolo en cualquier directorio de proyecto con el objetivo adecuado,

    "simusol-make help"

 proporciona mas información.

Ha sido probado en Ubuntu 11.10 y Suse 11.4, con Suse 11.3 y anteriores hay que tocar un poco el Makefile, en su interior esta comentado el código necesario

endef
export HELPMSG
#
##################################################################################################
# para instalar sceptre, simusol, simpack, simusol-gui sin internet colocar 
# sus paquetes en ~/.simusol/pkg o similar
# si alguna instalacion falla para volver a instalar hacer make delsceptre 
# o el que corresponda.
#
# solo instala dia y otros si hay un archivo INSTALAdia, 
# este archivo es creado por las rutinas que instalan simusol sceptre simpack simusol-gui, 
# de forma que este siempre actualizado cuando se instala alguno de estos, 
# en realidad puede no instalarlo si esta bajado ... ver bien
#

# verificar que los summa son de simusol para trabajar

# esto es lo de simpack


# si no hay summa, la crea  de skeleton, con nombre y version

# averiguar si puede hacer sudo por lo de cpan y los paquetes del sistema, 
# si puede instalar todo con sudo 

# un paquete dia se forma a partir de un directorio conteniendo diferente material organizado de cierta forma  
# https://simusol.org.ar/?Repositorio_de_Paquetes%2C_CSSAN:El_estandar_para_paquetes_de_SimuSol

#Al menos debe tener un archivo dia en ese directorio

# si hay un solo .dia o el dia se llama igual que el summa o el directorio  

# uso sudo -n ya que operara con interfaz grafica y es un lio si no!
# configurarse el sudo asi o ejecutar un sudo antes de este makefile
#$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
ESTEMAKE=$(realpath $(MAKEFILE_LIST))
LOCALMAKE=$(MAKEFILE_LIST)
$(info ESTEMAKE $(ESTEMAKE) LOCALMAKE $(LOCALMAKE))

#al comienzo para que los sed actuen solo aca son los tres primeros XXX



dirpro = $(CURDIR)   # directorio donde esta el proyecto original
wdir=$(CURDIR)       #directorio de trabajo

# wdir es creado antes de usarlo, si dirpro es overlayed pero no existe, realpath no funcionara ni avisa, queda vacio
# en wdir escribe los resultados si se los quiere poner en el arbol inicial poner wdir=rdirpro como parametro

$(shell $(shellpath) mkdir -p $(dirpro) 2>/dev/null)
$(shell $(shellpath) mkdir -p $(wdir) 2>/dev/null)
rdirpro= $(realpath $(dirpro))
rwdir= $(realpath $(wdir))

LISTADO=$(rdirpro)/listado.ls

sdirpro=$(shell $(shellpath) echo $(rdirpro) | sed -e 's/\//\\\//g' )

# cada vez que lo invocas lo hace?
BASETMP = $(shell $(shellpath) mktemp -d |sed -e's/\n//')

#$(info base ${BASETMP})
# PREFIX  puede ser modificada (override) com argumento en la linea de comando
# make PREFIX=/pepito 

PREPACK=$(basename $(notdir $(shell $(shellpath)  ls $(rdirpro)/*.summa 2>/dev/null)))


#DIASRAIZ = $(shell $(shellpath) ls $(rdirpro)/*.dia 2>/dev/null)
#DIASPROJ = $(shell $(shellpath) find $(rdirpro)/projects -type f -not -wholename '*.svn*' 2>/dev/null| grep '\.dia$$')
#DRAIZ = $(shell $(shellpath) ls $(rdirpro)/*.d 2>/dev/null)
#DPROJ = $(shell $(shellpath) find $(rdirpro)/projects -type f -not -wholename '*.svn*' 2>/dev/null| grep '\.d$$')

DIASRAIZ = $(shell $(shellpath) cd $(rdirpro); ls *.dia 2>/dev/null)
#DIASPROJ = $(shell $(shellpath)  cd $(rdirpro); find -L projects -type f -not -wholename '*.svn*' 2>/dev/null| grep '\.dia$$')
DIASPROJ = $(shell $(shellpath)  cd $(rdirpro); ls projects/*.dia  2>/dev/null)

DRAIZ = $(shell $(shellpath)  cd $(rdirpro); ls *.d 2>/dev/null)
# si borro .dia aun encuentra .d en results/test por eso no busca en subdirs de projects
# igual habilitar esto implica cambiar el listado de .dia de la interfaz grafica
#DPROJ = $(shell $(shellpath)  cd $(rdirpro); find -L projects -type f -not -wholename '*.svn*' 2>/dev/null| grep '\.d$$')
DPROJ = $(shell $(shellpath)  cd $(rdirpro); ls projects/*.d 2>/dev/null)

# sort para remover duplicados

DIA=$(sort $(DIASRAIZ) $(DIASPROJ))

SOURCES=$(sort $(DIASRAIZ) $(DIASPROJ) $(DRAIZ) $(DPROJ))

SCEPTRE=$(sort $(patsubst %.dia,%.sceptre,$(DIASRAIZ) $(DIASPROJ)) $(patsubst %.d,%.sceptre,$(DRAIZ) $(DPROJ)))

SIMUL=$(sort $(patsubst %.dia,%.simul,$(DIASRAIZ) $(DIASPROJ)) $(patsubst %.d,%.simul, $(DRAIZ) $(DPROJ)))

GRAF = $(sort $(patsubst %.dia,%.graf,$(DIASRAIZ) $(DIASPROJ)) $(patsubst %.d,%.graf, $(DRAIZ) $(DPROJ)))

VIEW = $(sort $(patsubst %.dia,%.view,$(DIASRAIZ) $(DIASPROJ)) $(patsubst %.d,%.view, $(DRAIZ) $(DPROJ)))

# variable DISPLAY es usada por X server

DISPLAYIMAGES = $(sort $(patsubst %.dia,%.display,$(DIASRAIZ) $(DIASPROJ)) $(patsubst %.d,%.display, $(DRAIZ) $(DPROJ)))

TOINSTALL=$(sort $(patsubst %.dia,%.dia.install,$(DIASRAIZ) $(DIASPROJ)) $(patsubst %.d,%.d.install,$(DRAIZ) $(DPROJ)))

$(info PREFIXDIAW  $(PREFIXDIAW))
$(info rdirpro $(rdirpro))
$(info DIASRAIZ $(DIASRAIZ))
$(info DIASPROJ $(DIASPROJ))
$(info DRAIZ $(DRAIZ))
$(info DPROJ $(DPROJ))
$(info DIA $(DIA))
$(info SIMUL $(SIMUL))
$(info SCEPTRE $(SCEPTRE))
$(info VIEW $(VIEW))

# verificar que no hay un dia con el mismo nombre que un d y que el d no salga del dia


PRIMERRDIA=$(shell $(shellpath)  echo $(DIASRAIZ)  | tail -n1 | sed -e s/\.dia$$// )
PRIMERPDIA=$(shell $(shellpath)  echo $(DIASPROJ)  | tail -n1 | sed -e s/\.dia$$// )
PRIMERRD=$(shell $(shellpath)  echo $(DRAIZ)  | tail -n1 | sed -e s/\.dia$$// )
PRIMERPD=$(shell $(shellpath)  echo $(DPROJ)  | tail -n1 | sed -e s/\.dia$$// )



cproyecto = $(notdir $(rdirpro))


# verificar todos los directorios para arriba en busca de un summa y colocar eso como dirpro

ifeq ($(PACK),)
  ifeq ($(PREPACK),)
    $(info CREARE .summa buscando proyectos, ¿hay un dia o d llamado como el directorio?)
     PACK = $(shell $(shellpath) if test -e $(rdirpro)/$(cproyecto).dia ; then \
                              echo $(cproyecto); \
                            else\
                              if test -e $(rdirpro)/projects/$(cproyecto).dia ; then\
                                 echo $(cproyecto); \
			        else \
                                  echo '';\
			      fi;\
                    fi)
     ifeq ($(PACK),)
     PACK = $(shell $(shellpath) if test -e $(rdirpro)/$(cproyecto).d ; then\
                              echo $(cproyecto); \
                            else\
                              if test -e $(rdirpro)/projects/$(cproyecto).d ; then\
                                 echo $(cproyecto); \
			        else \
                                  echo '';\
			      fi;\
                    fi)
     endif
     ifeq ($(PACK),)
        PACK=$(PRIMERDIA)
     endif
     ifeq ($(PACK),)
        PACK=$(PRIMERD)
     endif
     ifeq ($(PACK),)
       PACK=$(cproyecto)
     endif
   else
    PACK=$(PREPACK)
    $(info SUMA PREEXISTENTE: $(PREPACK))
   endif
 else
  ifeq ($(PREPACK),)
    $(info CREAR .summa POR ARGUMENTO: $(PACK))
   else
    $(info Existe $(PREPACK).summa no creare $(PACK).summa pedido por argumento) 
endif
endif

$(info PAQUETE: $(PACK) CURDIR: $(CURDIR) DIRPRO: $(rdirpro) )




VERSION=$(shell $(shellpath)  cat ${PACK}.summa 2>/dev/null| awk -F= '/BASEVERSION/ {print $$2}')
TYPE=$(shell $(shellpath)  cat ${PACK}.summa 2>/dev/null |  awk -F= '/SIMUSOLTYPE/ {print $$2}')

ifeq ($(VERSION),)
    VERSION = 0.1
endif
ifeq ($(TYPE),)
    OTHER = other
endif


# poner PACKC como objetivo del PACK ver...
PACKC=${PACK}-${VERSION}-${TYPE}

$(info PAQUETE: ${PACK} - ${PACKC})






#	echo 'PATH=~/bin:/usr/local/bin:$$PATH' >>~/.bashrc

# comprobar si no estan ya en el path 





#	echo 'PATH=~/bin:$$PATH' >>~/.bashrc

#Digest::MD5 falla
#clipboard falla
#ver selfupgrade


# no anda en cygwin
# no check porque redirecciona a https
# si es update hacer sin if
#if ! test -e /usr/bin/cpanm ; then \
# wget -O cpanm  http://cpanmin.us ;\
# sudo install cpanm /usr/bin ;\
#fi; 
#wget -O - http://cpanmin.us | perl - --self-upgrade
#
# If you don't have curl but wget, replace `curl -L` with `wget -O -`.

#aqui sigue a simusol, ahora quizas lo logico seria instalar todo en /usr/local siempre
# que se es root
USERID=$(shell $(shellpath) id -u)
NUID=1
NUID=$(shell $(shellpath) /bin/echo $$NUEVOUID)
 #$(info User Id is $(USERID))
UUU=0
ifeq ($(USERID),0)
UUU=1
endif
ifeq ($(NUID),0)
UUU=1
endif

# ojo con ls /home y skel?????

# PREFIXD porque dia puede estar instalado por paquete del sistema pero simusol no, es lo habitual
#dia no busca en el /usr donde no esta
# como lo va a instalar despues al dia, dejo como defecto el /usr
# en cambio el simusol es al reves

ifeq ($(UUU),1)
                $(info Running as root)
                ifeq (exists, $(shell $(shellpath) test -d /usr/share/simusol  && echo exists ))
	                PREFIX=/usr
	                SPREFIX=\/usr
                      else 
			PREFIX=/usr/local
			SPREFIX=\/usr\/local
                endif
                ifeq (exists, $(shell $(shellpath) test -d /usr/local/share/dia  && echo exists ))
	                PREFIXD=/usr/local
	                SPREFIXD=\/usr\/local
                      else 
			PREFIXD=/usr
			SPREFIXD=\/usr
                endif
	        DOT=/
	        DOC=doc/simusol/pkgs/$(PACK)
	        SHARE=/share
		SUDO=
		USERS=`ls /home`
           else
                $(info Running as user: $(USERID) - $(NUID))
		PREFIX=${HOME}
		SPREFIX=$(shell $(shellpath) echo ${HOME} | sed -e 's/\//\\\//g' )
	        PREFIXD=${PREFIX}
	        SPREFIXD=${SPREFIXD}
                #$(info SPREFIX $(SPREFIX))
	        DOT=/.
	        DOC=simusol/docs/$(PACK)
	        SHARE=
                ifeq (Cygwin,$(shell $(shellpath) uname -o))
                  SUDO=
                 else
                  SUDO=$(shell $(shellpath) sudo -n ls / 2>/dev/null |tail -n1 )  
                  SUDOPR=$(shell $(shellpath) sudo -n ls / 2>&1 |tail -n1)
                endif
                $(info SUDO: $(SUDO) PR: $(SUDOPR))	
		USERS=$(shell id -un)
          endif

ifeq (Cygwin,$(shell uname -o))
   OS=CYGWIN
   #PREFIX=
   #DOC=doc/simusol
   #SPREFIX=
   #DOT=/
   #SHARE=/usr/share
   #EXT=.pl
else
   #EXT=
endif

#si necesita pass forzar que la pida si es necesario

PREFIXSIM=${PREFIX}${SHARE}${DOT}simusol
PREFIXDIA=${PREFIXD}${SHARE}${DOT}dia
PREFIXDOCS=${PREFIX}${SHARE}${DOT}${DOC}


#/home/dsa/.simusol/pkg/
# no uso /tmp/simpack porque el simpack lo elimina

DOWN = ${PREFIXSIM}/pkg
$(shell mkdir -p $(DOWN)  2>/dev/null)
# esto hace prefixsim

$(shell mkdir -p $(PREFIXDIA)  2>/dev/null)
$(shell mkdir -p $(PREFIXDOCS)  2>/dev/null)

ifeq (exists, $(shell $(shellpath) test -s ~/.simusol/projects/vacio.dia && echo exists ))
   VACIO=~/.simusol/projects/vacio.dia
  else
   ifeq (exists, $(shell $(shellpath) test -s /usr/local/share/simusol/projects/vacio.dia && echo exists ))
     VACIO=/usr/local/share/simusol/projects/vacio.dia
    else
     ifeq (exists, $(shell $(shellpath) test -s /usr/bin/simusol/projects/vacio.dia  && echo exists ))
        VACIO=/usr/share/simusol/projects/vacio.dia
       else 
        VACIO=
        #$(info No esta instalado skeleton)
     endif
   endif
endif

$(info VACIO $(VACIO))


#esto deja regalitos en el home del usuario si se usa sudo, ya no

# no se pone simusolbash en etc, porque no vale la pena, asi se lo pongo a todos igual
changebash:
	if test x${OS} != xCYGWIN; then \
	   if test x$(USERID) = x0 ; then \
	    echo "$$SIMUSOLBASH" > /etc/simusolbash ;\
	    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; \
	      if test x"$$ESUSER" != x ; then \
	       su $$USER -c "cp /etc/simusolbash  /home/$$USER/.simusolbash ; ";\
	       if test x"`cat /home/$$USER/.bashrc | grep simusolbash`" = x ; then \
	            echo "cambio bashrc";\
	            su $$USER -c "echo '[[ -r /home/$$USER/.simusolbash ]] && . /home/$$USER/.simusolbash' >>/home/$$USER/.bashrc" ; \
	            fi ;\
	        if test x"`cat /home/$$USER/.bash_profile | grep simusolbash`" = x ; then \
	            echo "cambio bash_profile";\
	            su $$USER -c "echo '[[ -r /home/$$USER/.simusolbash ]] && . /home/$$USER/.simusolbash' >>/home/$$USER/.bash_profile" ; \
	            fi;\
	        if test -d /home/$$USER/Escritorio ; then \
	          echo "Es escritorio";\
	        fi ;\
	        fi;\
	     fi;\
	    done;\
	    else \
	        echo "NO ROOT" ;\
	  	echo "$$SIMUSOLBASH" > ~/.simusolbash ;\
	        if test x"`cat ~/.bashrc | grep simusolbash`" = x ; then \
	            echo '[[ -r ~/.simusolbash ]] && . ~/.simusolbash' >>~/.bashrc ; \
	            fi ;\
	        if test x"`cat ~/.bash_profile | grep simusolbash`" = x ; then \
	            echo '[[ -r ~/.simusolbash ]] && . ~/.simusolbash' >>~/.bash_profile ; \
	            fi;\
        fi;\
	else \
	   echo SICYG ;\
	   echo "$$SIMUSOLBASH" > ~/.simusolbash ;\
	   if test x"`cat ~/.bashrc | grep simusolbash`" = x ; then \
	            echo '[[ -r ~/.simusolbash ]] && . ~/.simusolbash' >>~/.bashrc ; \
	            fi ;\
	   if test x"`cat ~/.bash_profile | grep simusolbash`" = x ; then \
	            echo '[[ -r ~/.simusolbash ]] && . ~/.simusolbash' >>~/.bash_profile ; \
	            fi;\
	fi;


#if test -d /home/$$USER/Desktop ; then \
#    su $$USER -c "cp /home/$$USER/Desktop/$$FILEP /home/$$USER/Escritorio" ;\
#fi; \



# lo ideal es si sos root hacerlo en /etc/profile a ambos
# no se para que x11 en cygwin!

#When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

#When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc.

#As far as I understand, a login shell means a session where you log in to the system and directly end up in Bash, like a remote ssh session or logging in through a non-graphical text terminal. A non-login shell is then the type of shells you open after logging in: typically in a graphical session when you open a new terminal window.

#How I think things are supposed to work (for a typical setup):

#    .profile is for things that are not specifically related to Bash, like environment variables PATH and friends, and should be available anytime. For example, .profile should also be loaded when starting a graphical desktop session.
#    .bashrc is for the configuring the interactive Bash usage, like Bash aliases, setting your favorite editor, setting the Bash prompt, etc.
#    .bash_profile is for making sure that both the things in .profile and .bashrc are loaded for login shells. For example, .bash_profile could be something simple like

#    . ~/.profile
#    . ~/.bashrc

#    As stated in the man page excerpt above, if you would omit .bash_profile, only .profile would be loaded.



#echo 'PATH=~/bin:$$PATH' >>~/.bashrc


#proyecto es el dia!
nproyecto = $(notdir $(proyecto))
dproyecto = $(dir $(proyecto) )
sproyecto=$(shell $(shellpath) echo $(proyecto) | sed -e 's/\//\\\//g' )
drproyecto = $(shell $(shellpath) echo $(proyecto) | sed -e 's/^$(sdirpro)\///' )
davirtual=$(CURDIR)$(shell $(shellpath)  echo /$(dir drproyecto)  | sed -e 's/\.\/$$//'  | sed -e 's/\/$$//')

$(info DRDIA: $(drproyecto) DAVIRTUAL: $(davirtual)) 

# xless tarda un ratito en mostrar >>

#no se usan:
#TESTERROR=0

# installsoftware
all:  summa view
	@echo Termine make all del proyecto: $(proyecto)


infovar:
	@echo GOALS $(MAKECMDGOALS) CURDIR $(CURDIR)

# cuando llamo al make como ejecutable siempre se pone a si mismo como goal, no se porque


# podria poner ZZZ en condicionalall y reemplazarlo durante la instalacon con all

ifeq ($(MAKECMDGOALS),XXX.)
condicionalall: all
	@echo Hago make all
else
condicionalall: 
	@echo Hago los otros goals
endif

XXX.: condicionalall


help:
	@echo "$$HELPMSG"

summa:  
	 $(info OBJETIVO SUMMA)
ifeq ($(PACK),)
        $(info "No esta definido el nombre del paquete")
	exit 1;
else
	$(info Proyecto $(PACK))
endif
        # si finalmente no encontro un dia pone en proyecto.dia un vacio
	$(info SCEPTRE $(SCEPTREBIN)) 
	$(info SIMPACK $(SIMPACK)) 
	$(info SIMUSOL $(SIMUSOL)) 
	$(info SIMUSOL-GUI $(SIMUSOLG)) 
	$(info VERIFICA $(PACK))
	@cd $(rdirpro); \
	if  test x`echo $(VIEW) | wc -w` = x0 ; then \
	  if test x${VACIO} != x  ; then \
	   mkdir -p projects  2>/dev/null ;\
	   cp ${VACIO} projects/$(PACK).dia ;\
	  else \
	   echo No hay vacio, skeleton no esta instalado ; \
	   exit 1; \
	 fi; \
        fi; \
	if ! test -s $(PACK).summa  ; then \
	       echo "No hay archivo $(PACK).summa, creo estructura";\
	       rm -rf skeleton ;\
	       simpack k ;\
	       rm -f skeleton/Makefile ;\
	       rm -f skeleton/projects/vacio.dia ;\
	       mv skeleton/* . 2>/dev/null ;\
	       mv skeleton.summa $(PACK).summa;\
	       rm -rf skeleton ;\
               sed -i'' -e 's/BASEVERSION=[\.0-9]\+/BASEVERSION=0.1/'  $(PACK).summa;\
               sed -i'' -e 's/skeleton/${PACK}/g'  $(PACK).summa;\
	       if ! test -s Makefile ; then \
	         cp $(ESTEMAKE) Makefile; \
	       fi ;\
	       echo He creado  $(PACK).summa ;\
	fi

# skeleton lleva Makefile, pero si se esta ejecutando esta ... 
# es bueno que un paquete lleve esta Makefile, si alguien lo recibe y no tiene simusol instalado ....\
#rsync -av --exclude='*.svn*' --exclude='*/.*' ./ ${BASETMP}/${PACKC};     

simusol: $(SCEPTRE)

# poner aqui $(SIMUL) es importante porque marca los simul cono no intermediarios y no los borra
sceptre: $(SIMUL) 

#no hace falta especicficar

#$(CURDIR)/$(drproyecto).d

#compila: $(CURDIR)/$(drproyecto).compila

#ejecuta: $(CURDIR)/$(drproyecto).simul

#cuando sceptre se instale bien verificar los posibles lugares
# ojo con sceptres modernos no estan ahi, si no estan ahi avisar que hay que instalr sceptre

# si el origen es .d y no hay .dia cra uno vacio y no lo procesa mas.


#$(CURDIR)/$(drproyecto).d:  $(proyecto).dia
#mkdir -p $(dproyecto)/tmp ;  \
#cp $(proyecto).dia  $(dproyecto)/tmp ;\
#cd $(dproyecto)/tmp ; \

EJECUTASIMDIR=$(CURDIR)
EJECUTASIMDIR=/tmp/pruebamake

#VPATH=$(EJECUTASIMDIR)
#mkdir -p $(davirtual); \


# solo para el caso en que estoy en un vpath y no hay nada
%.ddia:
	echo "Trabajar sobre:  $@"
	mkdir -p $(dir $@) 2>/dev/null; exit 0;
	touch $@

# no usamos .d porque se puede llegar a borrar un fuente al intentar borrar el make


#arreglar origen de modellib, eso lo pone el instalador de sceptre!

# ojo eso de dia --nosplash ... no funciona porque luego simusol3.pl borra todo png y eps en results, arregalr simusol3
%.sceptre: %.ddia
	echo "Entro en dia->d"  $< ; \
	if test ! -e ~/lib/modellib.dat ; then \
	  mkdir -p ~/lib  2>/dev/null ;\
	  cp /usr/local/lib/modellib.dat  ~/lib ;\
	  cp /usr/local/lib/usrlib.a  ~/lib ;\
	fi ;\
	nombrefile=$(notdir $(patsubst %.ddia,%,$<)) ;\
	relapath1=$(patsubst $(EJECUTASIMDIR)/,,$(patsubst ./,,$(dir $<))) ;\
	relapath=`echo $$relapath1 | sed -e 's/\/$$//'`;\
	if test x$$relapath = x ; then \
	     dirp=$(rwdir) ;\
	     ddir=$(CURDIR) ;\
	     dirrp=$(rdirpro);\
	   else \
	     dirp=$(rwdir)/$$relapath ;\
	     ddir=$(CURDIR)/$$relapath ;\
	     dirrp=$(rdirpro)/$$relapath ;\
	fi; \
	if test -s $$dirrp/$$nombrefile.dia ; then \
	VLANG=$$LANG; LANG=us_US;\
	ESVACIO=`md5sum -t  $$dirrp/$$nombrefile.dia 2>/dev/null | cut -d' ' -f1` ;\
	echo "Su md5 es $$ESVACIO $<, la del vacio: f9ef9c3659127467164d5d5d9a8d197c";\
	LANG=$$VLANG;\
        if test x$$ESVACIO != xf9ef9c3659127467164d5d5d9a8d197c ; then \
	  echo "==> Procesando $$nombrefile en $$dirp para hacer $@" ;\
	  echo "ejecuta curdir: $(CURDIR)" ;\
	  rm $$dirp/$$nombrefile/tests/$$nombrefile.d ;\
	  echo "Haciendo diapng"; \
	  echo "---> mkdir -p $$dirp/$$nombrefile/results; dia --nosplash --size=1024 -e $$dirp/$$nombrefile/results/$$nombrefile.png $$dirrp/$$nombrefile.dia" ;\
	  mkdir -p $$dirp/$$nombrefile/results; \
	  dia --nosplash --size=1024 -e $$dirp/$$nombrefile/results/$$nombrefile.png $$dirrp/$$nombrefile.dia ;\
	  dia --nosplash -e $$dirp/$$nombrefile/results/$$nombrefile.eps $$dirrp/$$nombrefile.dia ;\
	  echo "---> simusol1.pl -o $$dirp/$$nombrefile $$dirrp/$$nombrefile" ;\
	  simusol1.pl -o $$dirp/$$nombrefile $$dirrp/$$nombrefile ;\
	  if test -e $$dirp/$$nombrefile/tests/$$nombrefile.d ; then \
	      touch   $$ddir/$$nombrefile.sceptre  ;\
	     else \
	      exit 1; \
	  fi ;\
	 else \
	  echo "DIA ES VACIO:  $$ddir/$$nombrefile.dia ";\
	  rm -f $< ;\
	fi ;\
	else \
	  echo "No existe dia  $$ddir/$$nombrefile.dia ";\
	  rm -f $< ;\
	  exit 1; \
	fi

#crea .caj  .d  .ls3  .paraplot
#dirp donde escribe
#ddir donde mete lo del makefile
#dirrp donde lee


#mkdir -p $$dirp/$$nombrefile ;\
#	  mkdir -p $$dirp/$$nombrefile/tmps ;\
#	  mkdir -p $$dirp/$$nombrefile/results ;\
#	  mkdir -p $$dirp/$$nombrefile/tests ;\
#	  mkdir -p $(EJECUTASIMDIR) ;\
#	  cd $(EJECUTASIMDIR) ;  \
#	  if test x$(EJECUTASIMDIR) != x ; then \
#	       rm -rf $(EJECUTASIMDIR)/*;\
#	  fi;\
#	  cp $$dirrp/$$nombrefile.dia  . ;\
# echo EJECUTASIMDIR $(EJECUTASIMDIR),
#	  mv $$nombrefile.d   $$dirp/$$nombrefile/tests ;\
#          mv $$nombrefile.paraplot $$nombrefile.caj  $$dirp/$$nombrefile/tests ;\



#  touch  $$ddir/$$nombrefile.sceptre;\


# >> $(CURDIR)/$(PACK).muestra; \

#mv $$nombrefile.d   $(CURDIR)/$$nombrefile.d  ;\
#EJECUTASIMDIR es donde el simusol se ejecuta
#CURDIR es donde el Make se ejecuta y pone sus cosas (y el entorno grafico)
#dirpro es el directorio del proyecto 

clean: cleantmp cleanmake cleanpack cleanss cleandiavacio cleangui

cleangui:
	rm *.gui 2>/dev/null; exit 0;

cleandiavacio:
#borrar en la raiz y en projects todos los dias vacios

#	rm -f ${PACK}-*-${TYPE}.s.tgz 2>/dev/null; exit 0;
cleanpack:
	rm -f ${PACK}-*-*.s.tgz 2>/dev/null; exit 0;


cleandep: clean cleantest cleannuevos

# provisorio ver
cleannuevos:
	 rm -rf projects/*/aux projects/*/data projects/*/elements projects/*/functions projects/*/models projects/*/*.dia
	 rm -rf */aux */data */elements */functions */models;


# rmdir solo si esta vacio!, asi lo hace

cleanall: cleandep cleanwdir 
	rm -f paqlog.*.html other/paqlog.*.html  
	rmdir other 2>/dev/null; echo 0;

# no usar paqlog sino nombre del diagramao logs de acciones del paquete no del diagrama, cuando hay diagrama poner en diagrama, aunque las acciones de todos los diagramas se perderan para eldiagrama
# poner other en OUTDIR, para cada diagrama pricipalñ

# ver en que dir los crea la interfaz grafica
# muestra por si las moscas

# no muevo .graf porque debe ir al paquete, si esta calculado

#esto no funciona hay que navegar y mover
#movemake:
#	@rm -rf /tmp/mvmake 2>/dev/null;	mkdir -p /tmp/mvmake 2>/dev/null;
#	@mv  $(SCEPTRE) $(SIMUL) INSTALA_companion $(PACK).muestra $(LISTADO) *.ddia projects/*.ddia /tmp/mvmake 

#restoremake:
#	@mv  /tmp/mvmake/* . 2>/dev/null; exit 0
#	@rm -rf /tmp/mvmake 2>/dev/null; exit 0

# listado no debe ser necesario, pero ...

#borrar muestra con cuidado por logs

#hacer objetivos de clean individuales


#FALTA BORRAR DIRECTORIOS DE DIAS INEXISTENTES porque se borraron

cleanmakepackmp:  cleantmpmp
	@echo CLEANMAKEPACK==========================: $(SCEPTRE) $(SIMUL) INSTALA_companion $(LISTADO) *.ddia  projects/*.ddia
	@rm  -f $(SCEPTRE) $(SIMUL) INSTALA_dia  $(LISTADO) *.ddia  projects/*.ddia 2>/dev/null; exit 0;
	@rm -f *.sceptre projects/*.sceptre   *.simul projects/*.simul ; exit 0
	@rmdir  projects 2>/dev/null; exit 0; 
	@rm -f *.muestra

cleanmakepack:  
	@echo CLEANMAKEPACK==========================: $(SCEPTRE) $(SIMUL) INSTALA_companion $(LISTADO) *.ddia  projects/*.ddia
	@rm  -f $(SCEPTRE) $(SIMUL) INSTALA_companion  $(LISTADO) *.ddia  projects/*.ddia 2>/dev/null; exit 0;
	@rm -f *.sceptre projects/*.sceptre   *.simul projects/*.simul ; exit 0
	@rmdir  projects 2>/dev/null; exit 0; 
	@rm -f *.muestra

cleanmake: cleanmakepack
	@rm  -f $(GRAF) 2>/dev/null; exit 0;
	@rm -f *.graf projects/*.graf; exit 0

cleandiavacio:

# buscar todos dias vacios y borrarlos!!!!!!!!!!


TMPFIL= '*.gnu'  _run .dat .sim .f .for .GPI .gra .ini .ls1 .ls2 .dirac  .acs
RESFIL= .simul '_*.eps' '_*.png' .res
TESTFIL= .caj .paraplot .ls3 .d 

# creo que gnus no lo salve a tmp
cleanwdir: $(patsubst %.sceptre,%.cleanwdir,$(SCEPTRE))
cleanresults: $(patsubst %.sceptre,%.cleanresults,$(SCEPTRE)) 
cleantmp: $(patsubst %.sceptre,%.cleantmp,$(SCEPTRE)) 
cleantmpmp: $(patsubst %.sceptre,%.cleantmpmp,$(SCEPTRE)) 
cleantest: $(patsubst %.sceptre,%.cleantest,$(SCEPTRE)) 

# clean.wdir.sim
# hacer uno por uno los clenamake y otros.

%.cleanresults: 
	@echo cleanresults $@
	@OBJ=$(patsubst %.cleanresults,%,$@) ; \
	 nf=`echo $$OBJ | sed -e 's/^projects\///'`;\
	 echo "file: $@ -$$OBJ - $$nf" ;\
	 for EXT in $(RESFIL) ; do \
	  echo "Borro:  $$OBJ/results/$$nf$$EXT"  ;\
	  rm -f $$OBJ/results/$$nf$$EXT 2>/dev/null;\
	 done; \
	 rmdir  $$OBJ/results 2>/dev/null;\
	 rmdir  $$OBJ 2>/dev/null;\
	 rmdir  $$nf 2>/dev/null;\
	 rmdir  projects 2>/dev/null ; \
	 exit 0


%.cleantmp: 
	@echo cleantmp $@
	@OBJ=$(patsubst %.cleantmp,%,$@);\
	 nf=`echo $$OBJ | sed -e 's/^projects\///'`;\
	 echo "file: $@ -$$OBJ - $$nf" ;\
	 echo "Borro dir: $$OBJ/tmps/gnus" ;\
	 rm -rf  $$OBJ/tmps/gnus 2>/dev/null ; \
	 for EXT in $(TMPFIL) ; do \
	  echo "Borro:  $$OBJ/tmps/$$nf$$EXT" ;\
	  rm -f $$OBJ/tmps/$$nf$$EXT 2>/dev/null ;\
	 done; \
	 rm -f $$OBJ/tmps/gnuplot.ls1  2>/dev/null;\
	 rm -f $$OBJ/tmps/*.GPI  2>/dev/null;\
	 rmdir  $$OBJ/tmps 2>/dev/null;\
	 rmdir  $$OBJ 2>/dev/null;\
	 rmdir  $$nf 2>/dev/null;\
	 rmdir  projects 2>/dev/null ; \
	 exit 0


%.cleantmpmp: graf
	@echo cleantmpmp $@
	@OBJ=$(patsubst %.cleantmp,%,$@);\
	 nf=`echo $$OBJ | sed -e 's/^projects\///'`;\
	 echo "file: $@ -$$OBJ - $$nf" ;\
	 echo "Borro dir: $$OBJ/tmps/gnus" ;\
	 rm -rf  $$OBJ/tmps/gnus 2>/dev/null ; \
	 for EXT in $(TMPFIL) ; do \
	  echo "Borro:  $$OBJ/tmps/$$nf$$EXT" ;\
	  rm -f $$OBJ/tmps/$$nf$$EXT 2>/dev/null ;\
	 done; \
	 rm -f $$OBJ/tmps/gnuplot.ls1  2>/dev/null;\
	 rm -f $$OBJ/tmps/*.GPI  2>/dev/null;\
	 rmdir  $$OBJ/tmps 2>/dev/null;\
	 rmdir  $$OBJ 2>/dev/null;\
	 rmdir  $$nf 2>/dev/null;\
	 rmdir  projects 2>/dev/null ; \
	 exit 0

%.cleantest: 
	@echo cleantest $@
	@OBJ=$(patsubst %.cleantest,%,$@);\
	 nf=`echo $$OBJ | sed -e 's/^projects\///'`;\
	 echo "file: $@ -$$OBJ - $$nf" ;\
	 echo "Borro dir: $$OBJ/tmps/gnus" ;\
	 for EXT in $(TESTFIL) ; do \
	  echo "Borro:  $$OBJ/tests/$$nf$$EXT"  ;\
	  rm -f $$OBJ/tests/$$nf$$EXT 2>/dev/null;\
	 done ;\
	 rmdir  $$OBJ/tests 2>/dev/null;\
	 rmdir  $$OBJ 2>/dev/null;\
	 rmdir  $$nf 2>/dev/null;\
	 rmdir  projects 2>/dev/null ; \
	 exit 0


%.cleanwdir: 
	@echo Cleanwdir $@
	@OBJ=$(patsubst %.cleanwdir,%,$@);\
	 nf=`echo $$OBJ | sed -e 's/^projects\///'`;\
	 echo "file: $@ -$$OBJ - $$nf" ;\
	 echo "Borro dir: $$OBJ/tmps/gnus" ;\
	 rm -rf  $$OBJ/tmps/gnus 2>/dev/null ; \
	 for EXT in $(TMPFIL) ; do \
	  echo "Borro:  $$OBJ/tmps/$$nf$$EXT" ;\
	  rm -f $$OBJ/tmps/$$nf$$EXT 2>/dev/null ;\
	 done; \
	 rmdir  $$OBJ/tmps 2>/dev/null;\
	 for EXT in $(RESFIL) ; do \
	  echo "Borro:  $$OBJ/results/$$nf$$EXT"  ;\
	  rm -f $$OBJ/results/$$nf$$EXT 2>/dev/null;\
	 done; \
	 rmdir  $$OBJ/results 2>/dev/null;\
	 for EXT in $(TESTFIL) ; do \
	  echo "Borro:  $$OBJ/tests/$$nf$$EXT"  ;\
	  rm -f $$OBJ/tests/$$nf$$EXT 2>/dev/null;\
	 done ;\
	 rmdir  $$OBJ/tests ;\
	 rm -rf $$OBJ/tests ;\
	 rm -f $$OBJ/tmps/gnuplot.ls1  2>/dev/null;\
	 rm -f $$OBJ/tmps/*.GPI  2>/dev/null;\
	 rmdir  $$OBJ 2>/dev/null;\
	 rmdir  $$nf 2>/dev/null;\
	 rmdir  projects 2>/dev/null ; \
	 exit 0

# rm -rf $$OBJ/tests ;\ ##################################3 mal agregado urgencia

# ninguno de estos debe ser necesario, no queda nada en EJECUTASIMDIR (comprobar antes de empezar para ver error)
cleanss:  cleansstest cleanssresults cleansstmp
	@rm -rf $(EJECUTASIMDIR)

cleansstmp:
	@echo cleanss
	@rm -f $(EJECUTASIMDIR)/*.dia 2>/dev/null ; exit 0;
	@rm -rf $(EJECUTASIMDIR)/gnus 2>/dev/null ; exit 0;
	@rm -f $(EJECUTASIMDIR)/*_*.gnu $(EJECUTASIMDIR)/*_run $(EJECUTASIMDIR)/*.dat $(EJECUTASIMDIR)/*.sim $(EJECUTASIMDIR)/*.f $(EJECUTASIMDIR)/*.for $(EJECUTASIMDIR)/*.GPI $(EJECUTASIMDIR)/*.gra $(EJECUTASIMDIR)/*.ini   $(EJECUTASIMDIR)/*.ls1 $(EJECUTASIMDIR)/*.ls2  $(EJECUTASIMDIR)/*.dirac 2>/dev/null ; exit 0;

cleanssresults:
	@echo cleanssresults
	@rm -f $(EJECUTASIMDIR)/*.simul $(EJECUTASIMDIR)/*.eps $(EJECUTASIMDIR)/*.png  $(EJECUTASIMDIR)/*.res 2>/dev/null ; exit 0;

cleansstest: 
	@echo cleansstest
	@rm -f $(EJECUTASIMDIR)/*.paraplot $(EJECUTASIMDIR)/*.caj 2>/dev/null ; exit 0;
	@rm -f $(EJECUTASIMDIR)/*.ls3  $(EJECUTASIMDIR)/*.d  2>/dev/null ; exit 0;




# borra, pero deja los archivos  necesarios para comparar con otras ejecuciones
# cuidado con los .d no habra sueltos origines?
#clean: 
#	rm  -f $(proyecto).d $(proyecto).simul $(proyecto).muestra muestra.pid

# borra todo lo que se puede regenerar
#cleandep: clean
#	rm  -f $(proyecto).ls3 $(proyecto).par $(proyecto).caj $(proyecto).res 



#mv -f $(nproyecto).d  $(davirtual); exit 0;\

#simusol1.pl  en el mismo dir, lee el dia, usa elementos y modelos
# si el nombre en el dia, es relativo busca en 
#crea .d (ecuaciones y descripcion para sceptre) 
#.paraplot (info para graficos) 
#.caj (info sobre cajas)

# diagramas complementarios  directorio dia_comp

# data de dos tipos 1) .csv, .cua con texto 

### OJO ESTO PONE TODOS LOS RESULTADOS DONDE ESTAN PARADOS
# POR EJEMPLO los SIMUL de algo en proyects/ van a estar en la raiz
# definir comportamiento para test y archivos de resultados
# si no hacer cd 
# lo ideales que sceptre/simusol sepa donde esta la raiz del proyecto y ponga los resultados del
# procesar el dia en forma relativa a este segun este parado JE complicado! 



#echo "salio bien simusol" >> $(proyecto).muestra
#touch $(proyecto).simusol

#	./hace.sh $(proyecto) simusol  $(TESTERROR) 
# touch si todo salio bien

#$(proyecto).compila: $(proyecto).simusol
#	echo "salio bien compila" >> $(proyecto).muestra
#	touch $(proyecto).compila

# hacer cleans!!!!!!!!!!!!

#$(CURDIR)/$(drproyecto).simul: $(CURDIR)/$(drproyecto).d
#cd $(dproyecto) ; \

#.SECONDARY:  
#Sin esto Removing intermediate files... borraba los .simul PRECIOUS

#rm  $(patsubst %.d,%.paraplot,$<);

#si no se borra paraplot y se borro simul da error
#if test -s  $(patsubst %.d,%.dia,$<) ; then \
#  else \
#   sceptre  $(notdir $(patsubst %.d,%,$<)) ;\
# fi ;\


# el corralito-preservativo-sandbox para simusol

%.simul: %.sceptre
	echo "==> Ejecutando sceptre d->simul"  $< ;\
        nombrefile=$(notdir $(patsubst %.sceptre,%,$<)) ;\
        relapath1=$(patsubst $(EJECUTASIMDIR)/,,$(patsubst ./,,$(dir $<))) ;\
	relapath=`echo $$relapath1 | sed -e 's/\/$$//'`;\
        if test x$$relapath = x ; then \
	     dirp=$(rwdir) ;\
	     ddir=$(CURDIR) ;\
	     dirrp=$(rdirpro) ;\
	   else \
	     dirp=$(rwdir)/$$relapath ;\
	     ddir=$(CURDIR)/$$relapath ;\
	     dirrp=$(rdirpro)/$$relapath ;\
	  fi; \
	mkdir -p $(EJECUTASIMDIR)  2>/dev/null ;\
	cd $(EJECUTASIMDIR) ;  \
	if test -s $$dirp/$$nombrefile/tests/$$nombrefile.d ; then \
	    rm $$dirp/$$nombrefile/results/$$nombrefile.simul ;\
	    simusol_sceptre -o $$dirp/$$nombrefile $$nombrefile ;\
	    simusol2.pl -o $$dirp/$$nombrefile $$nombrefile ;\
	    if test -s $$dirp/$$nombrefile/results/$$nombrefile.simul ; then \
	       touch   $$ddir/$$nombrefile.simul ;\
	     else \
	       exit 1; \
	    fi;\
	elif test -s $$dirrp/$$nombrefile.d ; then \
	     rm $$dirp/$$nombrefile/results/$$nombrefile.simul ;\
	     simusol_sceptre -o $$dirp/$$nombrefile  $$dirrp/$$nombrefile.d;\
	     simusol2.pl -o $$dirp/$$nombrefile $$nombrefile ;\
	     if test -s $$dirp/$$nombrefile/results/$$nombrefile.simul ; then \
	       touch   $$ddir/$$nombrefile.simul ;\
	      else \
	       exit 1; \
	     fi;\
	else \
	     echo No puedo procesar ni  $$dirp/$$nombrefile/tests/$$nombrefile.d ni  $$dirrp/$$nombrefile.d, son vacios o no existen. ;\
	     exit 1;\
	fi;\
	echo  DIRS SIMUL $$nombrefile - $$relapath - $$dirp - $< ; 



#           cp $$dirp/$$nombrefile/tests/$$nombrefile.d  . ;\
# 	        cp $$dirrp/$$nombrefile.d  . ;\
#mkdir -p $$dirp/$$nombrefile ;\
#	  mkdir -p $$dirp/$$nombrefile/tmps ;\
#	  mkdir -p $$dirp/$$nombrefile/results ;\
#	  mkdir -p $$dirp/$$nombrefile/tests ;\
#	  cp $$dirp/$$nombrefile/tests/$$nombrefile.paraplot  . ;\
#	  simusol_sceptre $$nombrefile    ;\
#	  echo Ejecutando simusol2  $$nombrefile;\
#	  simusol2.pl $$nombrefile ;\
#	  mv $$nombrefile.dirac $$nombrefile.ls2  $$dirp/$$nombrefile/tmps ;\
#	  mv $$nombrefile.sim  $$nombrefile.ls1 $$nombrefile.acs $$nombrefile.dat $$nombrefile.ini $$nombrefile.f $$nombrefile.for $${nombrefile}_run#  $$dirp/$$nombrefile/tmps ;\
#          mv $$nombrefile.res  $$dirp/$$nombrefile/results ;\
#	  mv $$nombrefile.simul  $$dirp/$$nombrefile/results ;\
#	  mv *.GPI  $$dirp/$$nombrefile/tmps ;\

#>> $(CURDIR)/$(PACK).muestra ;\

#mv  simusol.lss1 $$dirp/$$nombrefile/tmps ;\

#quien   crea gnuplot.ls1???? parece simusol3.pl

# simusol lee archivos, si no estan no protesta!!!!!!!!!!!!

#mv -f $(davirtual)/$(nproyecto).d . ; exit 0;\
#

#mv -f $(nproyecto).simul $(nproyecto).ls3 $(nproyecto).par $(nproyecto).caj $(nproyecto).res $(nproyecto).paraplot $(nproyecto).dirac $(davirtual) ; exit 0;\

#sceptre lee solo X.d 
#produce:
#X.dirac X.sim X.ls1 X.ls2 X.acs X.dat X.ini X.f X.for X_run X.res (por el simusol_sceptre)
# bajo el simusol, en otras condiciones otros

#simusol-sceptre paarce leer praplot

#simusol2 lee .dirac
#produce 
#X.simul
# otros .GPI

#ESTADOS DE UN DIRECTORIO al empaquetar por defecto TEST, con opcion se respeta el estado
#a) VIRGEN =                  X.dia, si no hay .dia: X.d
#b) CON RESULTADOS = VIRGEN + X.simul (simusol2)   X_*.png|eps: (simusol3)
#c) TEST/DEBUG = RESULTADOS + X.paraplot:(simusol1)  X.res:(sceptre-simusol)  X.ls3 (todos suman) 
#                             X.caj (simusol1)
#d) EJECUTADO = TEST/DEBUG  + X.d:(simusol1) X.for, X.f, gnus/* X.dat X.sim X.ls1 X.ls2 X.acs 
#                             X.dat X.ini X_run X_*.GPI X.dirac:(simusol1)
#                             X.muestra:(gui) G.gnu (simusol3) Sin cartel son de simusol2

#hay un for de datos y tambien for producidos

#      simusol1: X.dia       => X.d, X.caj, X.paraplot 
#       sceptre: X.d         => X.dirac X_*.GPI  X.for, X.f, gnus/* 
#                               X.dat X.sim X.ls1 X.ls2 X.acs X.dat X.ini X_run
#simusol-scetre: X.d         => X.res  
#      simusol2: X.dirac     => X.simul   X_*.GPI
#           GUI:             => X.muestra (todas las etapas suman)
#       simusol3: X.paraplot => X_*.eps|png X_*.gnu
#            ngp: X.paraplot => GPI

# FALSO gnus lo crea simusol3.pl

# X.for borra quien empaqueta
# gnus desaparecera 
#X_run  boora quien empaqueta
#X.dat  boora quien empaqueta
#X.sim  boora quien empaqueta
#X.f  boora quien empaqueta
#X.muestra  boora quien empaqueta
# *.GPI  boora quien empaqueta
# X mmm .s.tgz borrar empaqueta !!!!!!!!!!!!!!!!!!!!!!!!!
# *.png VER ES EL RESULTADOS
# X.simul ES EL RESULTADO
# X.gra boorar el que empaqueta
# X.ls1 X.ls2 borra el que ema
# X.acs borra el que e
# X.ini intermedio del sceptre boorar el que empaqueta
# X_mmm.eps boorar intermedios
# X.dirac borrar
# X.paraplot  GUARDAR
# X_mm.gnu borrar
# X.res GUARDAR
# .lss1 (se cambiara por ls3, pero debe aceptarse)


# en el paquete van todos como subdirectorios del mismo, pero se instalan los resultados en ccada proyecto.
# FUENTES
# a) directorio raiz: *.dia o *.d para ejecutar, van a proyects una vez instalados
# b) data  *.csv y *cua
# c) functions *.for
# d) elements  *.dia
# e) objects  
# f) modules  *.dia
# g) dia_comp *.dia (otros dia llamados desde los dia principales) (solo se puede usar en uno?)

#DIA
# h) shapes sheets

#RESULTADOS estos van instalados como subdirectorio de projects con el nombre del dia
# i) simul      X.simul
# j) graphics   X.png|eps
# k) tests     .caj .paraplot .res .ls3
# l) tmp       todo otro archivo producido

#OTROS
# m) other    .
# n) contrib soft adicional contribuido para este proyecto



#echo "salio bien ejecuta" >> $(proyecto).muestra
#touch $(proyecto).ejecuta

#display: $(CURDIR)/$(drproyecto).view

#$(CURDIR)/$(proyecto).view
#mv -f $(davirtual)/$(nproyecto).simul $(davirtual)/$(nproyecto).ls3 $(davirtual)/$(nproyecto).par $(davirtual)/$(nproyecto).caj $(davirtual)/$(nproyecto).res . ; exit 0;\
#mv -f $(nproyecto).simul $(nproyecto).ls3 $(nproyecto).par $(nproyecto).caj $(nproyecto).res $(davirtual)  ; exit 0; \

#	echo  DRPROYECTO $(CURDIR)/$(drproyecto)



#display: $(patsubst %,%.simul,$(CURDIR)/$(drproyecto))


viewpack:  view pack



#	 cd $(dproyecto) ; \
# ojo el echo del shell del make no envia \n creo

# esto es muy trucho, hay que cambiar los .gnu del simusol
# tambien hay que cambiar en el .gra almacenado en el repo su referencia a los archivos simul que estan 
# en results
# view debiera depender de gra (no es necesario en realidad, quizas mostrar graficos con display.)
# cambiar nombre a simul es chocante que el make produzca algo igual en otro lugar
%.graf: %.simul
	  @echo "==> Generando graficos $@ -  $(notdir $(patsubst %.simul,%,$<))" ; \
	  nombrefile=$(notdir $(patsubst %.simul,%,$<)) ;\
	  relapath1=$(patsubst $(EJECUTASIMDIR)/,,$(patsubst ./,,$(dir $<))) ;\
	  relapath=`echo $$relapath1 | sed -e 's/\/$$//'`;\
	  if test x$$relapath = x ; then \
	     dirp=$(rwdir) ;\
	   else \
	     dirp=$(rwdir)/$$relapath ;\
	  fi; \
	  echo  DIRS VIEW $$nombrefile - $$relapath - $$dirp - $<; \
	  if test -s $$dirp/$$nombrefile/results/$$nombrefile.simul; then \
            echo Si esta $$nombrefile.simul ;\
	    echo "--> simusol3.pl -g 2 -o $$dirp/$$nombrefile $$nombrefile ";\
	    simusol3.pl -g 2 -o $$dirp/$$nombrefile $$nombrefile ;\
	    for FILE in `cd $$dirp/$$nombrefile/results; ls $${nombrefile}_*.png`; do \
	      FILEGNU=`echo "$$FILE" | sed -e 's/\.png$$//'` ;\
	      KKK=`grep "^set term X11" $$dirp/$$nombrefile/tmps/$$FILEGNU.gnu` ;\
	      echo X11 $$FILE - $$FILEGNU - $$KKK;\
	      if test x"$$KKK" != x ; then \
	         echo mv $$dirp/$$nombrefile/results/$$FILE $$dirp/$$nombrefile/results/$${FILEGNU}_f.png  ;\
	         mv $$dirp/$$nombrefile/results/$$FILE $$dirp/$$nombrefile/results/$${FILEGNU}_f.png   ;\
	      fi ;\
	     done ;\
	     echo "Termino de crear graficos $${nombrefile}" ;\
	     rm -rf gnus ;\
	else \
	  echo No puedo procesar $< ni graficar, no hay resultados ;\
	fi;
	touch $@


#	    killall gnuplot_x11 ;\


# falta que el simusol3 haga lo de _f y que de una opcion para no llamar al gnuplot

#	  mkdir -p $$dirp/$$nombrefile ;\
#	  mkdir -p $$dirp/$$nombrefile/tmps ;\
#	  mkdir -p $$dirp/$$nombrefile/results ;\
#	  mkdir -p $$dirp/$$nombrefile/tests ;\
#	  cd $(EJECUTASIMDIR) ;  \
#	  cp $$dirp/$$nombrefile/results/$$nombrefile.simul  . ;\
#	  cp $$dirp/$$nombrefile/tests/$$nombrefile.paraplot  . ;\

#	    /bin/echo -e "0 1\n" |

#	    echo se mueven graficos a   $$dirp/$$nombrefile/results ;\
#	  mkdir -p $$dirp/$$nombrefile ;\
#	  mkdir -p $$dirp/$$nombrefile/tmps ;\
#	  mkdir -p $$dirp/$$nombrefile/results ;\
#	  mkdir -p $$dirp/$$nombrefile/tests ;\
#	     mv $${nombrefile}_*.png $${nombrefile}_*.eps  $$dirp/$$nombrefile/results ;\
#	    mv $${nombrefile}_*.gnu $$nombrefile.gra  $$dirp/$$nombrefile/tmps ;\
#	    mv gnuplot.ls1 $$dirp/$$nombrefile/tmps ;\
	    rm -f $$nombrefile.simul $$nombrefile.paraplot ;\



# $$nombrefile.dia  $$nombrefile.d 

#sed -i'' -e '/ X11/ dumb/g'  $${nombrefile}_*.gnu ;\

%.view: %.simul
	  @echo "==> Graficando $@ -  $(notdir $(patsubst %.simul,%,$<))" ; \
	  nombrefile=$(notdir $(patsubst %.simul,%,$<)) ;\
	  relapath1=$(patsubst $(EJECUTASIMDIR)/,,$(patsubst ./,,$(dir $<))) ;\
	  relapath=`echo $$relapath1 | sed -e 's/\/$$//'`;\
	  if test x$$relapath = x ; then \
	     dirp=$(rwdir) ;\
	   else \
	     dirp=$(rwdir)/$$relapath ;\
	  fi; \
	echo  DIRS VIEW $$nombrefile - $$relapath - $$dirp - $<; \
	if test -s $$dirp/$$nombrefile/results/$$nombrefile.simul; then \
          echo Si esta $$nombrefile.simul ;\
	  echo "--> simusol3.pl  -o $$dirp/$$nombrefile  $$nombrefile  ";\
	  simusol3.pl  -o $$dirp/$$nombrefile  $$nombrefile  ;\
	   echo "Termino de graficar $${nombrefile} " ;\
	  rm -rf gnus ;\
	else \
	  echo No puedo procesar $< ni graficar, no hay resultados  ;\
	fi;




#	  mkdir -p $$dirp/$$nombrefile ;\
#	  mkdir -p $$dirp/$$nombrefile/tmps ;\
#	  mkdir -p $$dirp/$$nombrefile/results ;\
#	  mkdir -p $$dirp/$$nombrefile/tests ;\
#	   cd $(EJECUTASIMDIR) ;  \
#	   cp $$dirp/$$nombrefile/results/$$nombrefile.simul  . ;\
#	   cp $$dirp/$$nombrefile/tests/$$nombrefile.paraplot  . ;\
#	   echo Si esta $$nombrefile.simul ;\
#	   /bin/echo -e "0 1\n" |


#	   echo se mueven graficos a   $$dirp/$$nombrefile/results ;\
#	   mv $${nombrefile}_*.png $${nombrefile}_*.eps  $$dirp/$$nombrefile/results ;\
#	   mv $${nombrefile}_*.gnu $$nombrefile.gra   $$dirp/$$nombrefile/tmps ;\
#	   mv gnuplot.ls1 $$dirp/$$nombrefile/tmps ;\
#	   rm -f $$nombrefile.simul $$nombrefile.paraplot ;\



#	  if test -s $$nombrefile.simul ; then \
#	  else \#
#	   echo No puedo graficar, no hay resultados;\
#	  fi ;\


#rm $$nombrefile.dia  $$nombrefile.d ;\
#  setsid  nohup detach
#   echo $$INPID -display $$dirp/$$nombrefile/results/$$FILE ;\

# display esta hecho a proposito para no calcular desde resultados.
%.display: %.graf
	  @echo "==> Mostrando $@ -  $(notdir $(patsubst %.display,%,$@))" ; \
	  nombrefile=$(notdir $(patsubst %.display,%,$@)) ;\
	  relapath1=$(patsubst $(EJECUTASIMDIR)/,,$(patsubst ./,,$(dir $@))) ;\
	  relapath=`echo $$relapath1 | sed -e 's/\/$$//'`;\
	  if test x$$relapath = x ; then \
	     dirp=$(rwdir) ;\
	   else \
	     dirp=$(rwdir)/$$relapath ;\
	  fi; \
	  for FILE in `cd $$dirp/$$nombrefile/results; ls $${nombrefile}_*_f.png`; do \
                PID=`ps a |grep "display $$dirp/$$nombrefile/results/$$FILE"|cut -d' ' -f1` ;\
	        echo PID $$PID de $$dirp/$$nombrefile/results/$$FILE ;\
	        for INPID in $$PID; do \
	           kill -9 $$INPID 2>/dev/null;\
	        done ;\
	        (display $$dirp/$$nombrefile/results/$$FILE &) ;\
	  done 

display: $(DISPLAYIMAGES)

view: $(VIEW) 
	@echo VIEW: $(VIEW)

graf: $(GRAF) 
	@echo GRA: $(GRAF)

enddisplay:
	killall display; exit 0;
	killall gnuplot_x11; exit 0;

#$(patsubst %.dia,%.view,$(DIASRAIZ) $(DIASPROJ) $(DRAIZ) $(DPROJ))

#	echo "muestra gnuplot"  >> $(proyecto).muestra

#simusol3.pl requiere X.paraplot 
#procude G.eps y G.png
# intermedios G.gnu

#muestra: 
#touch $(proyecto).muestra
#fork.sh "xless -f $(proyecto).muestra" ; \
 #echo $$! > muestra.pid ;

#killmuestra: 
#	PID=`cat muestra.pid`;\
#	kill -9 $$PID; exit 0

backup:
	NUMCEROBACK=`printf "%03d" $(shell $(shellpath) $(shell $(shellpath) ls -d back-* 2>/dev/null | tail -n1 | sed -e 's/^back-0*//')+1)`;\
	echo "CREA: back-$$NUMCEROBACK" ;\
	echo "CREA: back-$$NUMCEROBACK"  >> $(proyecto).muestra ;\
	mkdir back-$$NUMCEROBACK  2>/dev/null ;\
	rm -f back; ln -s back-$$NUMCEROBACK back;\
	cp $(proyecto)*  back-$$NUMCEROBACK ;\
	cp Makefile  back-$$NUMCEROBACK 

rmbackup:
	echo $(numback);
	NUMCEROBACK=`printf "%03d" $(numback)`;\
	echo BORRA: back-$$NUMCEROBACK ;\
	echo "BORRA: back-$$NUMCEROBACK"  >> $(proyecto).muestra ;\
	rm -rf  back-$$NUMCEROBACK

listabackup:
	echo LISTA: `ls -d back-* 2>/dev/null`
	echo "Lista de backups:" >> $(proyecto).muestra
	ls -d back-* >> $(proyecto).muestra 2>/dev/null

comparabackup:
	echo "No se todavia comparar" >> $(proyecto).muestra


# no entiendo porque PREFIXSIM o PREFIXDIA DEBE EXISTIR, se hace make

ifeq (exists, $(shell $(shellpath) test -d ${PREFIXSIM}  && echo exists ))
        $(info PREFIXSIM: ${PREFIXSIM})
   else
        $(shell $(shellpath) mkdir ~/.simusol  2>/dev/null)
        PREFIXSIM = ~/.simusol
        $(info Simusol no parece estar instalado, creo PREFIXSIM: ${PREFIXSIM})
endif

ifeq (exists, $(shell $(shellpath) test -d ${PREFIXDIA}  && echo exists ))
        $(info PREFIXDIA: ${PREFIXDIA})
   else
        $(shell $(shellpath) mkdir ~/.dia  2>/dev/null)
        PREFIXDIA = ~/.dia
        $(info Dia no parece estar instalado, creo PREFIXDIA: ${PREFIXDIA})
endif

IFILSHAPES=$(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "shapes/" )
IFILDOCS=$(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep  "docs/" )
IFILSHEETS=$(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep  "sheets/" )
#IFILSIMUSOL=$(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep -v "shapes/"|grep -v "sheets/" |grep -v "docs/")
#IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "projects/")
IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "data/")
IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "soft/")
IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "elements/")
IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "models/")
IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "graphics/")
IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "other/")
IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "objects/")
IFILSIMUSOL += $(shell $(shellpath) find  -type f -not -wholename '*.svn*'| grep "functions/")
#  en todo caso a los archivos de root ponerlos en otro lado

# auxdia

FILESRAIZ = ChangeLog AUTHORS NEWS README INSTALL COPYING COPYING.WEB COPYING.DOC LICENSE THANKS TODO Makefile ${PACK.summa}

#DIARAIZ = $(shell $(shellpath) ls *.dia *.ls3 *.par *.caj *.d *.res *.simul 2>/dev/null)



# .summa

#$(info SHAPES ${IFILSHAPES})
#$(info DOCS ${IFILDOCS})
#$(info SHEETS ${IFILSHEETS})
#$(info SIMUSOL ${IFILSIMUSOL})

# directorios
IDSHAPES=$(shell $(shellpath) find  -type d -not -wholename '*.svn*'| grep "shapes/" )
IDDOCS=$(shell $(shellpath) find  -type d -not -wholename '*.svn*'| grep  "docs/" )
IDSHEETS=$(shell $(shellpath) find  -type d -not -wholename '*.svn*'| grep  "sheets/" )
IDSIMUSOL=$(shell $(shellpath) find  -type d -not -wholename '*.svn*'| grep -v "shapes/"|grep -v "sheets/" |grep -v "docs/")
#$(info D SHAPES ${IDSHAPES})
#$(info D DOCS ${IDDOCS})
#$(info D SHEETS ${IDSHEETS})
#$(info D SIMUSOL ${IDSIMUSOL})


installpack: installbase $(TOINSTALL) installfin

# ${PREFIXSIM} debe existir
%.install: 
	$(call installproject,$@,${PREFIXSIM})

# ver docs es un lio, diuf en home que en otros
installbase:
	@echo Install ${PACKC}
	@rm -f $(LISTADO)
	@install -d ${PREFIX}${SHARE}
	#caso overriden por command line
	@install -d ${PREFIXDIA}
	@install -d ${PREFIXDIA}/sheets
	@install -d ${PREFIXDOCS}
	@install -d ${PREFIXSIM}       
	# caso overrriden por command line
	$(call installdirs,${IDSIMUSOL},${PREFIXSIM},)
	$(call installdirs,${IDSHEETS} ${IDSHAPES},${PREFIXDIA},)
	$(call installdirs,${IDDOCS},${PREFIXDOCS},docs\/)
	$(call installfiles, ${DIARAIZ},${PREFIXSIM}/proyects,)
	install  -d  ${PREFIXDOCS}/${PACK}
	$(call installfiles,${FILESRAIZ},${PREFIXDOCS}/${PACK},docs\/)
	$(call installfiles,${IFILSIMUSOL},${PREFIXSIM},)
	$(call installfiles,${IFILSHEETS} ${IFILSHAPES},${PREFIXDIA},)
	$(call installfiles, ${IFILDOCS},${PREFIXDOCS},docs\/)
	$(info Proyectos a instalar $(TOINSTALL))
ifeq (Cygwin,$(shell /bin/uname -o))	
	rm -f /tmp/pfdl
	ln -s $(PREFIXDIAW) /tmp/pfdl
	$(call installdirs,${IDSHEETS} ${IDSHAPES},/tmp/pfdl,)
	$(call installfiles,${IFILSHEETS} ${IFILSHAPES},/tmp/pfdl,)
endif

installfin:
	@install -d ${PREFIXSIM}/ls
	@mv  ${PREFIXSIM}/ls/${PACKC}.ls ${PREFIXSIM}/ls/${PACKC}.ls.viejo 2>/dev/null; exit 0;
	@install $(LISTADO) ${PREFIXSIM}/ls/${PACKC}.ls
	@rm -f $(LISTADO)

# ponemos en algun lado al summa al instalar ? SI en pkgs
# hay un dir test no uso test:
# test que testea el makefile o el proyecto, es una mala idea tener un solo make

# sacar /graphics
# hacer test flexible, que informe si esta mal sin exit, agregar opcion arreglar a la rutina test
# importar dias y dirs a un paquete, esconder directorio de trabajo
# crear paquete!

test: testpack

testpack:
	echo Make test simpack
	rm -f ./${PACKC}.s.tgz 2>/dev/null; exit 0;
	simpack t $(dirpro)

# en vez de ese rm no es make clean
#### OJOOOOOOOOOOOOOOOOO No da error si no pasa el test SIGUE


# saco de aca testpack!!!!
save: pack
pack: solopack


#restoremake
# no parece hacegurar que 

solopack: cleanmakepackmp
	         @echo "Make solopack ${DESTINO}/${PACKC}.s.tgz";
		 @BASET=${BASETMP};\
		 rm -rf $${BASET}/$${PACKC}; \
		 mkdir -p $${BASET}/$${PACKC};  2>/dev/null\
		 chmod -R 777 $${BASET}; \
		 rsync -a --exclude='*.svn*' --exclude '*.gui' --exclude "${PACKC}.s.tgz" --exclude='*/.*' ./ $${BASET}/${PACKC};   \
		 tar --exclude .svn --exclude "${PACKC}.s.tgz" --exclude .gui -C$${BASET} -zcf ${DESTINO}/${PACKC}.s.tgz ${PACKC}; \
		echo  Creado ${DESTINO}/${PACKC}.s.tgz;


# export ORIGEN=/home/dsa/.simusol/pkg/examples_gui-0.1-project.s.tgz; export UNPACKDIR=ttt; make unpack 

unpack:
	         @echo "Make unpack ${ORIGEN} ${UNPACKDIR}";
		if test -e ${ORIGEN} ; then \
		if test -d ${UNPACKDIR} ; then \
                 DIRS=`tar -ztf  ${ORIGEN} | cut -d/ -f1 |sort -u`; \
		 NUM=`echo $${DIRS} | wc -l`; \
		 if test x$${NUM} != x1 ; then \
			echo "ERROR ${ORIGEN} INVALIDO, mas de un dir: $${DIRS}";\
                 else \
		   BASETMP=`mktemp -d`;\
		   echo "BT: $$BASETMP - ORI: ${ORIGEN} - DIR: $${DIRS} - UNPDIR: ${UNPACKDIR}"; \
		   chmod -R 777 $${BASETMP}; \
		   rm -rf $${BASETMP}/$${DIRS}; \
		   mkdir -p $${BASETMP}/$${DIRS};  2>/dev/null\
		   tar  -C$${BASETMP} -zxf ${ORIGEN} ; \
		   rsync -a   $${BASETMP}/$${DIRS}/*  ${UNPACKDIR}/;   \
		   echo  Abierto ${ORIGEN}  EN ${UNPACKDIR} ; \
		 fi; \
		fi; \
		fi; 

# no pongo test porque simpack lo hace
repo: pack
	simpack r ${PACK}

# ojo con la intefaz grafica pide clave con una rutina especial del perl!!!
# mejor usar para subir paquete
upload: clean repo
	if test x${ISSIMUSOLGUI} != x ; then \
	 export ISSIMUSOLGUI=$(ISSIMUSOLGUI); echo  '$(USERDATA)' |simpack u ${PACK} ;\
	else \
	 echo ${PACK} ;\
	 simpack u ${PACK} ;\
	fi

#update cpanm????
updatesimusolall:  updsimpack updsceptre  updsimusol updskeleton updsimusol-gui

installsimusolall:  insimpack  insceptre  insimusol inskeleton insimusol-gui
# hacer un inmake que funciones como los otros, por ahora updmake

updsoftware: updmake changebash updcompanion updatesimusolall  
updsoftwarenomake:  changebash updcompanion updatesimusolall  
# ojo changebash no cambia

#installcompanion
installsoftware: updmake changebash updcompanion installsimusolall

#mal cada uno de esos 3 depende del anterior


##########################################################3



# verificar que estan instalados, sino instalar. (gcc gfortran)





# ver si se puede poner make install sin sudo, segun el usuario



#################################################### Sceptre
SCEPTREBIN=$(call findfirst,bin/sceptre)

#sceptreNAME = sceptre-inenco-2009-0.5.tar.gz
sceptreNAME = sceptre-inenco-last.tar.gz
sceptreDIR = http://simusol.org.ar/downloads/${sceptreNAME}

rmsceptre:
	$(call rmbin,Sceptre,sceptre,$(SCEPTREBIN))

rmfsceptre: rmsceptre
	$(call rmfbin,Sceptre,${sceptreNAME})

updsceptre: 
	$(call download,,$(DOWN),${sceptreNAME},${sceptreDIR},sceptre-inenco,Sceptre,$(call sceptrecomp))


#rmsceptre insceptre

# como no esta terminado el paquete sceptre
setsceptremd5:
	$(call mkmd5,${DOWN},${sceptreNAME},${sceptreDIR})

#define sceptrecomp
#	   make ;\
#	   sudo -n make install ;
#endef

define sceptrecomp
	make FC=$(FC) >/dev/null 2>/dev/null;\
	sudo make FC=$(FC) install >/dev/null 
endef

insceptre:
	$(call download,$(SCEPTREBIN),$(DOWN),${sceptreNAME},${sceptreDIR},sceptre-inenco,Sceptre,$(call sceptrecomp))

#################################################### Simusol

simusolNAME=simusol-last.tar.gz
simusolDIR=http://simusol.org.ar/downloads/${simusolNAME}
SIMUSOL=$(call findfirst,bin/simusol)

rmsimusol:
	$(call rmbin,Simusol,simusol)

rmfsimusol: rmsimusol
	$(call rmfbin,Simusol,${simusolNAME})

updsimusol: 
	$(call download,,$(DOWN),${simusolNAME},${simusolDIR},simusol,Simusol,$(call simusolcomp))

#rmsimusol insimusol

define simusolcomp
	 make ; \
	 echo NO hacer caso al ejecutar simusol.usuario.instalar 
endef

#	 if test x$(SUDO) != x ; then \
#	   sudo -n make install ; \
#	  else\
#	   make install;\
#	 fi; \
# ver de eliminar simusol.usuario.instalar, que lo haga simusol si no esta hecho
# debe ejecutarse en el simusol-gui cada vez 

insimusol:
	$(call download,$(SIMUSOL),$(DOWN),${simusolNAME},${simusolDIR},simusol,Simusol,$(call simusolcomp))

#################################################### Simpack
simpackNAME=simpack-last.tar.gz
simpackDIR=http://simusol.org.ar/downloads/${simpackNAME}

SIMPACK=$(call findfirst,bin/simpack)

rmsimpack:
	$(call rmbin,Simpack,simpack)

rmfsimpack: rmsimpack
	$(call rmfbin,Simpack,${simpackNAME})

updsimpack: 
	$(call download,,$(DOWN),${simpackNAME},${simpackDIR},simpack,Simpack,$(call simpackcomp))

#rmsimpack insimpack

define simpackcomp
	 sudo make depinstall ;\
	 make install
endef

#	 if test x$(SUDO) != x ; then \
#	   sudo -n make install ; \
#	  else\
#	   make install;\
#	 fi; 

insimpack:
	$(call download,$(SIMPACK),$(DOWN),${simpackNAME},${simpackDIR},simpack,Simpack,$(call simpackcomp))

#################################################### Simusol-gui
simguiNAME=simusol_gui-last.tar.gz
simguiDIR=http://simusol.org.ar/downloads/${simguiNAME}

SIMUSOLG=$(call findfirst,bin/simusol-gui)

# seria logico llamar a este ejecutable simusol y no simusol-gui
# con cpan debes poder hacer sudo !

# PARA TODOS, no habra que borrar solo {SIMUSOLG}

rmsimusol-gui:
	$(call rmbin,Simusol-Gui,simusol-gui)

rmfsimusol-gui: rmsimusol-gui
	$(call rmfbin,Simusol-Gui,${simusol-guiNAME})

# ya no es necesario
define simusol-guicomp
	sudo make cpan; \
	make
endef

updsimusol-gui: 
	$(call download,,$(DOWN),${simguiNAME},${simguiDIR},simusol_gui,Simusol-GUI,$(call simusol-guicomp))


#rmsimusol-gui insimusol-gui

# por ahora make solo alcanza
#if test x$(SUDO) != x ; then \
#  sudo -n make install ; \
# else\
#  make install;\
#fi; 


insimusol-gui:
	$(call download,$(SIMUSOLG),$(DOWN),${simguiNAME},${simguiDIR},simusol_gui,Simusol-GUI,$(call simusol-guicomp))

#################################################### skeleton

rmskeleton:
	@if test x$(SUDO) != x ; then \
	   sudo -n rm -f /usr/local/share/simusol/pkg/skeleton*.s.tgz /usr/share/simusol/pkg/skeleton*.s.tgz ;\
	else \
	  if  test x"$(SUDOPR)" != x ; then \
	   sudo rm -f /usr/local/share/simusol/pkg/skeleton*.s.tgz /usr/share/simusol/pkg/skeleton*.s.tgz ; \
	  fi ;\
	fi; \
	rm -f ~/.simusol/pkg/skeleton*.s.tgz

##########3 OJO ESTO NO PONE LA ULTIMA VERSION DE SKELETON, ejecutar el rmskeleton, si se quiere instalar el ultimo. MEJOR: corregir simpack!

# lo llama siempre, y desempaqueta e instala, ver como evitarlo

inskeleton:
	@if test x$(SUDO) != x ; then \
	   sudo -n env PATH=${HOME}/bin:/usr/local/bin:${PATH}  simpack i skeleton; \
	 else \
	   simpack i skeleton ;\
	 fi;

# verificar si se instala con i o con k y que pasa con vacio ya que installproject
#protesta por vacio, ver que hace summa con skeleton que saca vacio, capaz que este paso es al vicio.

# ver en los make install de los paqutes si no usar simusol-make

# poner algo aca!
updskeleton: rmskeleton inskeleton

#################################################### .this

# hacer un back de lo que se borra, por si acaso

#HACER UN DEL PARA REPOS DE INTERNET
makefileNAME=Makefile
MAKEFILEG=$(call findfirst,bin/simusol-make)
makefileDIR=http://simusol.org.ar/downloads/Makefile
makefileDIRmd5=http://simusol.org.ar/downloads/Makefile.md5

# ojo si no hay simusol-make.summa la version subida estara mal
# ojo esto de la VERSION funciona de casualidad busca summa de paquete. 
#poner version especifica de makefile para esta VERSION

upmake: sedmakefile
	if ! test -e simusol-make.summa ; then \
	   wget  http://www.simusol.org.ar/downloads/simusol-make.summa;  \
	fi; \
        makeVERSION=`cat simusol-make.summa 2>/dev/null| awk -F= '/BASEVERSION/ {print $$2}'` ;\
	if test x$${makeVERSION} = x ; then \
	    makeVERSION=0.01;\
	fi; \
	md5sum -t  shortcut.pl >shortcut.pl.md5;\
	md5sum -t  Makefile >Makefile.md5;\
	md5sum -t  LiberaWin.exe >LiberaWin.exe.md5;\
	wget  -O MF.md5 http://www.simusol.org.ar/downloads/Makefile.md5; \
	wget  -O SC.md5 http://www.simusol.org.ar/downloads/shortcut.pl.md5; \
	wget  -O LW.md5 http://www.simusol.org.ar/downloads/LiberaWin.exe.md5; \
	cp Makefile Makefile-$${makeVERSION} ;\
	cp shortcut.pl shortcut-$${makeVERSION}.pl ;\
	cp LiberaWin.exe LiberaWin-$${makeVERSION}.exe ;\
	if test -e MF.md5 ; then  \
	   DIF=`diff MF.md5 Makefile.md5` ;\
          else \
           DIF=1; \
        fi ; \
	if test -e SC.md5 ; then  \
	   DIFSC=`diff SC.md5 shortcut.pl.md5` ;\
          else \
           DIFSC=1; \
        fi ;\
	if test -e LW.md5 ; then  \
	  DIFW=`diff LW.md5 LiberaWin.exe.md5` ;\
         else \
          DIFW=1; \
        fi; \
	echo DIF $$DIF $$DIFW; \
	if test x"$$DIF$$DIFW$$DIFSC" != x ; then \
	  scp LiberaWin.exe LiberaWin-$${makeVERSION}.exe LiberaWin.exe.md5 Makefile-$${makeVERSION} simusol-make.summa Makefile.md5 shortcut.pl shortcut.pl.md5 wwwrun@simusol.org.ar:/srv/www/htdocs/simusol/simusolsite/downloads ; \
	  ssh wwwrun@simusol.org.ar "cd /srv/www/htdocs/simusol/simusolsite/downloads; rm -f Makefile; ln -s Makefile-$${makeVERSION} Makefile";\
	fi; 
	# si estoy en el arbol de desarrollo de simusol (repo), actualizar otros paquetes que llevan Makefile
	# se copia el makefile en los proyectos por si alguno recibe un proyecto y no tiene simusol pueda instalarlo
	# probablemente el camino a estos repos cambie mucho, ver
	if test -e ../skeleton/Makefile ; then \
	  cp Makefile ../skeleton/Makefile;\
	  cp Makefile ../simusolnuevo/packs/base/Makefile;\
	  cp Makefile ../simusolnuevo/packs/examples_simple/Makefile;\
	  cp Makefile ../simusol-gui/examples_gui/Makefile;\
	  cp Makefile ../simusolnuevo/packs/examples_elements/Makefile;\
	  cp Makefile ../simusolnuevo/packs/examples_models/Makefile;\
	  cp Makefile ../simusolnuevo/packs/examples_functions/Makefile;\
	  cp Makefile ../simusolnuevo/packs/examples_data/Makefile;\
	fi

# cp Makefile ../ssp_test/Makefile;\ sacado

puntoinstall:
	ls -d -1 ~/.simusol/guiwork/*/  | xargs -n1 cp Makefile 


#	for D in `find . -type d`
# si root lo hago en todos los usuarios!
# SIN FOR para dirs con espacios find . -type d -print0 | xargs -0 -n 1 my_command
#	for D in ~/.simusol/guiwork/*; do \
#	   if [ -d "~/.simusol/guiwork/$$D" ]; then\
#	      echo "cp Makefile ~/.simusol/guiwork/$$D/Makefile";\
#	      cp Makefile "~/.simusol/guiwork/$$D/Makefile";\
#	    fi ;\
#	done




rmmakefile:
	@echo Borra Makefile;\
	if test x$(SUDO) != x ; then \
	   sudo -n rm -f /usr/local/share/simusol/pkg/Makefile /usr/share/simusol/pkg/Makefile /usr/bin/simusol-make /usr/local/bin/simusol-make;\
	else \
	  if  test x"$(SUDOPR)" != x ; then \
	   sudo rm -f /usr/local/share/simusol/pkg/Makefile /usr/share/simusol/pkg/Makefile  /usr/bin/simusol-make /usr/local/bin/simusol-make; \
	  fi ;\
	fi; \
	rm -f ~/.simusol/pkg/Makefile ~/bin/simusol-make

# recordar hacer "hash -r" para borrar el cache local de PATH en bash, si se cambio de lugar


#install -d bin para el home, a veces no esta
install: installsoftware 
update: updatereal

# da error si debe instalar sobre si mi, por eso puse exit 0, solo sucederia  si se usa el objetivo install sobre simusol-make 
# cuando se esta en bin, no es un escenario esperable.




#pruebacyg: inmake cyginstallcompanion


#	$(call  distro);\
#	if test x"$$DISTRO" = xCYGWIN; then \

/usr/bin/sudo:
	echo CYGWIN SUDO;  \
	echo '#!/bin/bash' >sudo.sh ;\
	echo 'if test x$$1 = x"-n" ; then ' >>sudo.sh ;\
	echo '   export NUEVOUID=0; $$2 $$3 $$4 $$5 $$6 $$7 $$8 $$9 $${10} $${11}'>>sudo.sh ;\
	echo ' else ' >>sudo.sh ;\
	echo '   export NUEVOUID=0; $$1 $$2 $$3 $$4 $$5 $$6 $$7 $$8 $$9 $${10} $${11}'>>sudo.sh ;\
	echo 'fi ' >>sudo.sh ;\
	install sudo.sh /usr/bin/sudo


#cygwin strawberry /usr/bin/shortcut.pl emacswin diawin gnuplot




cygwin:
	      echo Cygwyn;\
              if ! test -e ~/bin/setup.exe ; then \
	        mkdir ~/bin  2>/dev/null;\
	        wget -O ~/bin/setup.exe  http://cygwin.com/setup.exe  ;\
	        chmod a+x ~/bin/setup.exe ;\
	      fi; \
	      ~/bin/setup.exe -s "http://lug.mtu.edu/cygwin" -q -P zip -P unzip -P openssh -P gcc -P gcc-g77 -P make -P binmutils -P autoconf -P automake -P gettext -P libgcc1 -P libstdc++ ;\
	      ~/bin/setup.exe -s "http://lug.mtu.edu/cygwin" -q -P readline -P subversion  -P emacs -P mc -P nano -P perl -P perlwin32-gui -P perlXMLsimple -P perllibwin32 -P wget;\
	      ~/bin/setup.exe -s "http://lug.mtu.edu/cygwin" -q -P  util-linux  -P bsdtar -P md5deep -P lynx -P ncftp -P gnupg -P rsync ;


#"dia" -integrated
$(DOWN)/dia-setup-0.97.2.exe:
	 wget -O $(DOWN)/dia-setup-0.97.2.exe http://sourceforge.net/projects/dia-installer/files/dia-win32-installer/0.97.2/dia-setup-0.97.2.exe/download 

/cygdrive/c/Program\ Files/Dia/bin/dia.exe: $(DOWN)/dia-setup-0.97.2.exe
	chmod a+x $(DOWN)/dia-setup-0.97.2.exe
	$(DOWN)/dia-setup-0.97.2.exe; exit 0
	touch "/cygdrive/c/Program Files/Dia/bin/dia.exe"


diawin: /cygdrive/c/Program\ Files/Dia/bin/dia.exe
	rm -f /usr/bin/dia 
	ln -s "c:\\Program Files\\Dia\\bin\\dia.exe"  /usr/bin/dia
	./shortcut.pl dia "c:\\Program Files\\Dia\\bin\\dia.exe" 

# cpan cygwin m,al



cyggfortran:
	 if ! test -e  /usr/bin/gfortran.vie ; then \
	    mv /usr/bin/gfortran /usr/bin/gfortran.vie;\
	 fi;\
	 rm -f /usr/bin/gfortran ;\
	 ln -s /usr/bin/g77 /usr/bin/gfortran ;\


$(DOWN)/shortcut.pl: /cygdrive/c/SSstrawberry/perl/bin/perl.exe
	wget -O  $(DOWN)/shortcut.pl "http://simusol.org.ar/downloads/shortcut.pl"
	touch $(DOWN)/shortcut.pl


# por algun motivo el wget no cambia la fecha de shortcut


/usr/bin/shortcut.pl: $(DOWN)/shortcut.pl
	echo install shortcut
	install $(DOWN)/shortcut.pl /usr/bin

gnuplot: /cygdrive/c/Program\ Files/gnuplot/bin/wgnuplot.exe
	if ! test -e  /usr/bin/gnuplot.vie ; then \
	    mv /usr/bin/gnuplot /usr/bin/gnuplot.vie;\
	fi;\
	rm -f /usr/bin/gnuplot ;\
        ln -s "C:/Program Files/gnuplot/bin/wgnuplot.exe" /usr/bin/gnuplot;\

$(DOWN)/gp46rc1-win32-setup.exe:
	wget -O  $(DOWN)/gp46rc1-win32-setup.exe http://sourceforge.net/projects/gnuplot/files/gnuplot/4.6.rc1/gp46rc1-win32-setup.exe/download

/cygdrive/c/Program\ Files/gnuplot/bin/wgnuplot.exe: $(DOWN)/gp46rc1-win32-setup.exe
	chmod a+x $(DOWN)/gp46rc1-win32-setup.exe
	$(DOWN)/gp46rc1-win32-setup.exe; exit 0
	touch "/cygdrive/c/Program Files/gnuplot/bin/wgnuplot.exe"


$(DOWN)/emacs-23.4-bin-i386.zip:
	wget -O $(DOWN)/emacs-23.4-bin-i386.zip http://ftp.gnu.org/gnu/emacs/windows/emacs-23.4-bin-i386.zip

/cygdrive/c/Program\ Files/emacs-23.4/bin/runemacs.exe: $(DOWN)/emacs-23.4-bin-i386.zip /cygdrive/c/strawberry/perl/bin/perl.exe
	unzip $(DOWN)/emacs-23.4-bin-i386.zip -d "c:\\Program Files" 
	touch "/cygdrive/c/Program Files/emacs-23.4/bin/runemacs.exe"
	/cygdrive/c/strawberry/perl/bin/perl.exe shortcut.pl emacs "c:\\Program Files\\emacs-23.4\\bin\\runemacs.exe" 

# sacado porque perl del cpan del cygnois en esta maquina anda mal


$(DOWN)/cygwin-mount.el:
	wget -O $(DOWN)/cygwin-mount.el http://www.khngai.com/emacs/cygwin-mount.el



#usar perl!!!! cygwin parece no funcionar con espacios

emacswin:  $(DOWN)/cygwin-mount.el /cygdrive/c/Program\ Files/emacs-23.4/bin/runemacs.exe
	if ! test -e  /usr/bin/emacs.vie ; then \
	       mv /usr/bin/emacs /usr/bin/emacs.vie;\
	fi ;\
	rm -f /usr/bin/emacs ;\
        ln -s "/cygdrive/c/Program\ Files/emacs-23.4/bin/runemacs.exe" /usr/bin/emacs;
	/cygdrive/c/strawberry/perl/bin/perl.exe shortcut.pl emacs "c:\\Program Files\\emacs-23.4\\bin\\runemacs.exe" 



#WHOME=`perl -MWin32 -MFile::Basename -e 'print Win32::GetFolderPath(0x0000)'|sed -e's/\\\\Desktop$$//'|sed -e's/\\\\Escritorio$$//'|sed -e's/^\([A-Z]:\)/\L\1/'|sed -e's/:\\\\/\//'|sed -e's/\\\\/\//g'|sed -e's/ /\\\\ /g'`; \
	WHOMEWIN=`perl -MWin32 -MFile::Basename -e 'print Win32::GetFolderPath(0x0000)'|sed -e's/\\\\Desktop$$//'|sed -e's/\\\\Escritorio$$//'` ; \
	UWHOMEWIN=`cygpath -u $$WHOMEWIN/Application Data/Roaming | sed -e's/ /X/g'`; \
	echo UW $$UWHOMEWIN;\
	homeemacs1="/cygdrive/$$WHOME/AppData/Roaming/.emacs";\
	homeemacs="/cygdrive/$$WHOME/Application\\ Data/Roaming";\
	ls "$$UWHOMEWIN";\
	mkdir -p $$homeemacs ;\
	echo $$homeemacs ;\
	ls $$homeemacs ;\
	ls "$$homeemacs" ;\
	homeemacs="/cygdrive/$$WHOME/Application\ Data/Roaming/.emacs";\
	echo "(setenv \"PATH\" (concat \"c:/cygwin/bin;\" (getenv \"PATH\")))"   >> $$homeemacs ;\
	echo "(setq exec-path (cons \"c:/cygwin/bin/\" exec-path))"   > $$homeemacs ;\
	echo "(require 'cygwin-mount)"  >> $$homeemacs ;\
	echo "(cygwin-mount-activate)"   >> $$homeemacs ;\
	echo "(add-hook 'comint-output-filter-functions"       >> $$homeemacs ;\
	echo "  'shell-strip-ctrl-m nil t)"                    >> $$homeemacs ;\
	echo "(add-hook 'comint-output-filter-functions"       >> $$homeemacs ;\
	echo "    'comint-watch-for-password-prompt nil t)"    >> $$homeemacs ;\
	echo " (setq explicit-shell-file-name \"bash.exe\")"      >> $$homeemacs ;\
	echo ";; For subprocesses invoked via the shell"       >> $$homeemacs ;\
	echo ";; (e.g., \"shell -c command\")"                 >> $$homeemacs ;\
	echo "(setq shell-file-name explicit-shell-file-name)" >> $$homeemacs ;\
	cp  cygwin-mount.el   "c:\\Program Files\\emacs-23.4\\site-lisp" 


STRAWV=5.12.3.0
#STRAWV=5.14.2.1-32bits

#http://strawberry-perl.googlecode.com/files/strawberry-perl-5.14.2.1-32bit.msi
#http://strawberry-perl.googlecode.com/files/strawberry-perl-5.14.2.1-32bit.msi
#http://strawberry-perl.googlecode.com/files/strawberry-perl-5.12.3.0.msi

$(DOWN)/strawberry-perl-$(STRAWV).msi:
	wget -O $(DOWN)/strawberry-perl-$(STRAWV).msi http://strawberry-perl.googlecode.com/files/strawberry-perl-$(STRAWV).msi



/cygdrive/c/strawberry/perl/bin/perl.exe: $(DOWN)/strawberry-perl-$(STRAWV).msi
	CAM=`echo "C://cygwin$(DOWN)/strawberry-perl-$(STRAWV).msi"|sed -e's/\//\\\\/g'` ;\
	echo $$CAM ;\
	msiexec.exe /passive /I $$CAM 
	touch /cygdrive/c/strawberry/perl/bin/perl.exe

# ponmer para borar y listar lo bajado y retraer

#/quit no muestra nada /passive informa

strawberry:  /cygdrive/c/strawberry/perl/bin/perl.exe
	if ! test -e ppdlisto ; then \
	/cygdrive/c/strawberry/perl/bin/perl.exe c://strawberry/perl/bin/ppm.pl install \
	http://www.wxperl.co.uk/repository/Alien-wxWidgets.ppd \
	http://www.wxperl.co.uk/repository/Wx.ppd \
	http://www.wxperl.co.uk/repository/Wx-TreeListCtrl.ppd \
	http://www.wxperl.co.uk/repository/Wx-GLCanvas.ppd \
	http://www.wxperl.co.uk/repository/Wx-Perl-ListView.ppd \
	http://www.wxperl.co.uk/repository/Wx-Demo.ppd ; \
	touch ppdlisto ;\
	fi;
	export PATH=C:\strawberry\c\bin:C:\strawberry\site\bin:C:\strawberry\perl\bin  ; echo $$PATH; /cygdrive/c/strawberry/perl/bin/perl c://strawberry/perl/bin/cpan Win32::Shortcut Clipboard Capture::Tiny ExtUtils::Command Shell::Command  Win32::Process Win32::Pipe


# ojo esto ultimo no fuinciona, cree que esta en cygwin y busca un /bin/bash, en commando dos si funciona


#c://strawberry/perl/bin/

#	 echo WX 
#	 cpan install Wx



# if test x$$DISTRO != xCYGWIN  ; then   \
#fi
# ojo con la variable term en la instalacion del gnuplot

#http://www.nntp.perl.org/group/perl.wxperl.users/2010/02/msg7142.html
#www.imagemagick.org/download/binaries/ImageMagick-i686-pc-cygwin.tar.gz
#http://artfiles.org/cygwin.org/pub/cygwinports/release/perl/perl-Alien-wxWidgets/

# 
# echo 
#http://stackoverflow.com/questions/1966380/where-is-the-emacs-file-in-windows-gnu-emacs
#http://stackoverflow.com/questions/189490/where-can-i-find-my-emacs-file-for-emacs-running-on-windows
#homeemacs="c:\\ProgramData\\.emacs";\

#homebash=%HOME%/.bashrc




#ojo cambiar X11 por wxt en archivos gnuplot

# chmod a+x cpanm

# cambiar bashrc para todos

## ojo cambia el archivo, pero no ejecuta el nuevo!!!!!!!!!!!!, 
## si lo cambia, pero si baja incompleto no recupera el viejo?
updmake:
	echo update  Makefile
	$(call download,,$(DOWN),${makefileNAME},${makefileDIR},,simusol-make,make -C $(DOWN) -f $(DOWN)/Makefile sedmakefile)
	nombrefile=$(notdir $(ESTEMAKE)) ;\
	echo Nombre de ESTEMAKE: $$nombrefile - ESTEMAKE: $(ESTEMAKE) DOWN: $(DOWN)/Makefile ;\
	if test x$$nombrefile != xsimusol-make ; then \
	   if test x$(ESTEMAKE) != x$(DOWN)/Makefile ; then \
	       echo copio bajado a ESTEMAKE ;\
	       cp $(DOWN)/Makefile $(ESTEMAKE); \
	   fi; \
	fi; exit 0;

updatereal: updmake
	echo UPDATE updsoftwarenomake CON EL NUEVO MAKE
	make -C $(DOWN) -f $(DOWN)/Makefile updsoftwarenomake

#
# solo lo puedo hacer si $ESTEMAKE no es simusol-make, si no se encarga sedmakefile
# exit 0 caso son el mismo fichero

kkk:
	wget -c -P ${DOWN}  ${makefileDIRmd5} ;\
	if ! test -e ${DOWN}/Makefile ; then \
	   wget -c -P ${DOWN}  ${makefileDIR} ;\
	  else \
	   md5sum -t  ${DOWN}/Makefile > Makefile.md5;\
	fi ;\
	if  test -e ${DOWN}/Makefile ; then \
	  install ${DOWN}/Makefile ${PREFIX}/bin/simusol-make; \
	 $(call sedmake,${PREFIX},${SPREFIX}) \
	 else \
	  echo No se pudo bajar Makefile;\
	fi

 #cp ${DOWN}/Makefile Makefile ;\  para ejectuar esto es porque YA la tengo de antes





#################################################### Del sistema
# dice dia, pero es dia, gnuplot, firefox
#DISTRO=$(shell $(shellpath) ./infosis | grep  " DISTRO="|sed -e 's/export DISTRO=//');\
# 
#


fincompanion:
	touch INSTALA_companion

updcompanion: fincompanion installcompanion

#cpan> o conf prerequisites_policy follow

# Bundle::CPAN ;\ da problemas en cygwin y no es necesario

 #/bin/echo -e "\n"| 


#apt-get --reinstall install *
PACKSDEBIAN = iceweasel gnuplot dia gcc   emacs  subversion  gfortran make\
              gnome-terminal xdg-utils  imagemagick libxml-parser-perl \
              libwww-perl libyaml-perl  libcrypt-ssleay-perl libtext-asciitable-perl \
              data-dumper  libfile-homedir-perl  libgtk2.0-dev libwxbase2.8-0 \
              libwxgtk2.8-0 libwxbase2.8-dev libwxgtk2.8-dev  wx2.8-headers\
               wx-common xclip libterm-readline-perl-perl xtail

PACKSUBUNTU =  firefox gnuplot dia gcc  emacs subversion  gfortran make \
               gnome-terminal xdg-utils imagemagick libxml-parser-perl libwww-perl  \
               libyaml-perl libcrypt-ssleay-perl libtext-asciitable-perl  \
               data-dumper  libfile-homedir-perl  libgtk2.0-dev libwxbase2.8-0 \
               libwxgtk2.8-0 libwxbase2.8-dev libwxgtk2.8-dev   wx2.8-headers\
               wx-common xclip libterm-readline-perl-perl xtail



#	   sudo -n apt-get -y install $(PACKSUBUNTU)

# ver como enterarse de los errores del apt y reportar
# quizas correr de nuevo el dpkg query y si no da vacio error

#PACKSUTUTO = firefox-10.0.2 gnuplot-4.6_rc1 dia-0.97.2 gcc-4.5.3-r2 emacs-23.4-r1 subversion-1.7.2 make-3.82-r3 gnome-terminal-3.2.1 xdg-utils-1.1.0_rc1_p20111003 XML-LibXML-1.900.0 libwww-perl-6.30.0 yaml-0.71 Crypt-SSLeay-0.58 File-HomeDir-0.91 wxGTK-2.8.12.1 Term-ReadLine-Perl-1.30.300 xclip-0.12 xtail-2.1

PACKSUTUTO = firefox-10 gnuplot-4 dia-0 gcc-4 emacs-23 subversion-1 make-3 gnome-terminal-3 xdg-utils-1 XML-LibXML-1 libwww-perl-6 yaml-0 Crypt-SSLeay-0 File-HomeDir-0 wxGTK-2 Term-ReadLine-Perl-1 xclip-0 xtail-2

PACKSUTUTO = firefox gnuplot dia gcc emacs subversion make gnome-terminal xdg-utils XML-LibXML libwww-perl yaml Crypt-SSLeay File-HomeDir wxGTK Term-ReadLine-Perl xclip xtail


PACKSSUSE=  MozillaFirefox gnuplot dia gcc  emacs  subversion gcc-fortran make gnome-terminal xdg-utils  imagemagick perl-libxml-perl  perl-libwww-perl perl-YAML    perl-Crypt-SSLeay perl-Text-ASCIITable  perl-Getopt-Long perl-File-HomeDir wxWidgets-devel wxGTK-devel perl-Wx   xclip perl-Term-ReadLine-Perl xtail

#NO Term-ReadLine-Perl xtail xclip
#           LANG=''; dpkg-query -W  $(PACKSUBUNTU) 2>&1 1>/dev/null| sed -e's/^No packages found matching //'|sed -e's/\.$$//'| xargs sudo apt-get -y install ; \

#   LANG=''; dpkg-query -s  $(PACKSUBUNTU) 2>&1 1>/dev/null| sed -e's/^is not installed //'|sed -e's/\.$$//'| xargs sudo apt-get -y install ; \


# zypper    --non-interactive -n --quiet -q --auto-agree-with-licenses --gpg-auto-import-keys
lininstallcompanion: 
	echo CPANM
	if test -e  $(HOME)/.cpanm; then \
	  sudo chmod -R 777 $(HOME)/.cpanm ; \
	  echo "chmod -R 777 $(HOME)/.cpanm" ;\
	fi ;
	if ! test -e /usr/bin/cpanm ; then \
	 if ! test -e /usr/local/bin/cpanm ; then \
	   wget --no-check-certificate -O - http://cpanmin.us | sudo perl - --self-upgrade ;\
	 fi; \
	fi; 
	echo INSTALLCOMPANION
	if test -e INSTALA_companion ; then \
	 rm -f INSTALA_companion ;\
	 echo CPANM;\
	 /bin/echo -e "\n"| cpanm --sudo  CPAN YAML;\
	 $(call  distro);\
	 echo DISTRO: $$DISTRO; \
	 if  test x$$DISTRO = xUBUNTU ; then \
	   echo UBUNTU APT; \
	   sudo -n apt-get update; \
           sudo -n apt-get -y install $(PACKSUBUNTU) ;\
	 elif test x$$DISTRO = xDEBIAN ; then \
	   sudo -n apt-get update; \
	   sudo -n apt-get -y install $(PACKSDEBIAN) ;\
	 elif test x$$DISTRO = xSUSE ; then \
	   sudo -n zypper -n in $(PACKSSUSE)  ;\
	 elif test x$$DISTRO = xREDHAT ; then   \
	   sudo -n yum install      firefox gnuplot dia gcc   emacs  subversion   gfortran make gnome-terminal xdg-utils  imagemagick\
              perl-XML-LibXML   perl-libwww-perl perl-YAML    perl-Crypt-SSLeay     perl-Text-ASCIITable \
	      perl-Getopt-Long perl-File-HomeDir wxGTK-devel perl-Alien-wxWidgets xclip perl-Term-ReadLine-Perl xtail ;\
	 elif test x$$DISTRO = xMANDRIVA  ; then   \
	   sudo -n urpmi          firefox gnuplot dia gcc  emacs  subversion gcc-gfortran make gnome-terminal xdg-utils  imagemagick\
              perl-XML-parser   perl-libwww-perl perl-YAML    perl-Crypt-SSLeay     perl-Text-ASCIITable \
	      perl-Getopt-Long perl-File-HomeDir libwxgtku2.8 xclip perl-Term-ReadLine-Perl xtail;\
	 elif test x$$DISTRO = xUTUTO  ; then   \
	    for FILE in $(PACKSUTUTO)  ; do \
	       echo  "Y" | sudo -n uget $$FILE ;\
	       cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
	       rm -f /dist-upgrade.notfound 2> /dev/null;\
	    done; \
            cpanm --sudo  Text::ASCIITable File::HomeDir;\
	 elif test x$$DISTRO = xGENTOO  ; then   \
	   sudo -n emerge firefox gnuplot dia gcc  emacs   dev-util/subversion  gfortran make gnome-terminal xdg-utils  imagemagick\
              XML-LibXML        libwww-perl      yaml Crypt-SSLeay \
	      File-HomeDir  wxGTK xclip Term-ReadLine-Perl xtail;\
	   cpanm --sudo  Text::ASCIITable ;\
	 elif test x$$DISTRO = xCYGWIN  ; then   \
	     echo NUNCA;\
	 fi ;\
         echo CPAN NNNN;\
	sudo chmod -R 777 $(HOME)/.cpanm ;\
	echo "chmod -R 777 $(HOME)/.cpanm" ;\
	 cpanm --sudo  Capture::Tiny IO::Handle IO::Socket::INET  HTTP::DAV Digest::MD5 Shell::Command File::Path;\
	 cpanm --sudo   Clipboard  HTML::TagParser ;\
	 if test x$$DISTRO != xCYGWIN  ; then   \
	   cpanm -n --sudo  Wx ;\
	   cpanm -n --sudo  Wx ;\
	 fi;\
	fi ;\

#echo notest install Wx|sudo cpan
# falla si se ejecuta en una terminal sin salida grafica GTK
# Error: Unable to initialize gtk, is DISPLAY set properly


# parece en algiunos casos ser necesrio hacerlo dos veces al cpan Wx



# los otros soft los instala el instalador de windows
cyginstallcompanion:   /usr/bin/sudo   cyggfortran 
	if test -e  $(HOME)/.cpanm; then \
	  sudo chmod -R 777 $(HOME)/.cpanm ; \
	  echo "chmod -R 777 $(HOME)/.cpanm" ;\
	fi ;
	if ! test -e /bin/cpanm ; then \
           wget --no-check-certificate -O $(DOWN)/cpanm  http://cpanmin.us ;\
           sudo install $(DOWN)/cpanm /bin ;\
	fi; 
	cpanm  YAML Crypt::SSLeay Text::ASCIITable  File::Which 
	cpanm Getopt::Long File::HomeDir Term::ReadLine::Perl
	if ! test -e /tmp/LWP.si ; then \
	       cpanm GAAS/libwww-perl-5.836.tar.gz;\
	       touch /tmp/LWP.si ;\
	fi
	echo capnam 2
	cpanm Capture::Tiny IO::Handle IO::Socket::INET  HTTP::DAV  Shell::Command File::Path 
	cpanm  HTML::TagParser 
	echo cpanm4


# ver paquetes para Digest::MD5
#Sed
# sudo -n uget install xtail ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
#  sudo -n uget install xclip;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\

	   
#           sudo -n uget install  gnuplot ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
#           sudo -n uget install dia;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
#           sudo -n uget install gcc;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
#  sudo -n uget install emacs;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
 # sudo -n uget install subversion;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
 # sudo -n uget install make ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
 # sudo -n uget install gnome-terminal;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
 # sudo -n uget install xdg-utils;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
 # sudo -n uget install XML-LibXML ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
 # sudo -n uget install libwww-perl ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
 # sudo -n uget install yaml ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
 # sudo -n uget install Crypt-SSLeay;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
#  sudo -n uget install File-HomeDir ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
#  sudo -n uget install wxGTK ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\
#  sudo -n uget install Term-ReadLine-Perl ;\
#	    cat   /dist-upgrade.notfound >>  /tmp/simusolnotfound;\
#	    rm -f /dist-upgrade.notfound;\

copiadiagui:
	UHOME=`perl -MFile::HomeDir -e 'print home()'` \
	UUSER=`perl -MFile::HomeDir -e 'print home()'|sed -e's/^\/home\///'` \
	WHOME=`perl -MWin32 -MFile::Basename -e 'print Win32::GetFolderPath(0x0000)'|sed -e's/\\\\Desktop$$//'|sed -e's/\\\\Escritorio$$//'|sed -e's/^\([A-Z]:\)/\L\1/'|sed -e's/:\\\\/\//'|sed -e's/\\\\/\//g'`; \
	echo $$UHOME $$WHOME $$UUSER; \
	cp -r $$UHOME/.dia/shapes /cygdrive/$$WHOME/.dia/shapes; \
	cp -r $$UHOME/.dia/sheets /cygdrive/$$WHOME/.dia/sheets; \
	cp -r $$UHOME/share /cygdrive/$$WHOME/share; \
	shortcut.pl CygwinHome "C:\\cygwin\home\\$$UUSER"


#Wx::Perl::Packager
#http://www.wxperl.co.uk/repository/Wx-ActiveX.ppd

#XML::LibXML
#               ~/bin/setup.exe -s "http://lug.mtu.edu/cygwin" -q -P  libxml2-devel;\
#	      ~/bin/setup.exe -s "http://lug.mtu.edu/cygwin" -q -P zip zoo sharutils pbzip2 p7zip lzip liblzo2 liblzma-devel;\

#              cp C:/Users/dsa/Desktop/setup.exe .; \

###http://strawberry-perl.googlecode.com/files/strawberry-perl-5.12.3.0.msi
#https://kjkpub.s3.amazonaws.com/sumatrapdf/rel/SumatraPDF-1.9-install.exe
#http://dia-installer.de/index.html.en
#
#


#cywin esta en c:/cywin/home/USUARIO_WIN

#http://gfortran.com/download/cygwin/
#http://gfortran.com/download/cygwin/gfortran-4.7-20110424-Cygwin-i686.tar.bz2
# cd /home
#> wget gfortran-Cygwin-i686.tar.bz2
#> tar -jxvf gfortran-Cygwin-i686.tar.bz2 -C /
#> ln -s /usr/local/gfortran/bin/gfortran.exe ~/bin/gfc
#> gfc --version


#http://bytes.com/topic/perl/insights/737530-how-install-setup-strawberry-perl



#agregar para suse viejos wxGTK-devel
#para todo suse perl-Wx


#Wx::Perl::ListCtrl

# en suse cpan force WX y Wx::PerlCtrl
# suse viejo wxGTK
#http://wiki.wxwidgets.org/Installing_and_configuring_under_Gentoo
#http://en.opensuse.org/openSUSE:Packaging_wxWidgets
# no se porque sudo no funciona si no esta dentro de bash algun lio de path sera
# sudo cpan CPAN YAML
# no parece ser necesario usar cpan aqui;\

#suse libwx_baseu-2_8-0-wxcontainer libwx_gtk2u_core


# en apt --no-upgrade
# urpmi,emerge,uget, zypper , yum no puede instalar sin update solo debian
# igual no tiene sentido, solo si falta software hace eso, entonces actualiza, solo entonces o si se le da de prepo


#  perl-base de suse tiene data::dumper y cwd

#gentoo: data::dumper esta en perl http://gpo.zugaina.org/perl-core

#debian ya instalados con perl: perl-modules perl-base perl 

#emerge -uD update todos los paquetes

# gentoo asciii-tables no esta

# libgetopt-mixed-perl debian

#parece tonto poner make, pero al menos lo actualiza!

#para update
#	   sudo -n apt-get update
#	   sudo -n apt-get -y install  firefox gnuplot-x11 dia gcc gfortran make libxml-parser-perl
#pacman -S	yum install	apt-get install	rug install	zypper install zypper in	 emerge [-a]
#pacman -Syu	yum update	apt-get upgrade	rug update	zypper update zypper up	emerge -u world

#usar ssh para crear ln, ya lo hice en otro lado ver.
# no uso last para facilitar a los usuarios bajar por primera vez Makefile.

#cpan2dist  cpanspec



print-%:
	@echo '$*=$($*)'
	@echo '  origin = $(origin $*)'
	@echo '  flavor = $(flavor $*)'
	@echo '   value = $(value  $*)'

# OJO luego de instalar quedo in INSTALA_companion y me dio problemas al test



# al ultimo para que no cambie la rutina del cambio
	      #poner XXX ;\
	      #poner $(ESTEMAKE)\

fixme:
	@if test x$(notdir $(ESTEMAKE)) = xMakefile ; then \
	      echo "FIXME simusol-make ->XXX  $(ESTEMAKE)" ;\
	      $(call sedmake2,\/usr\/local\/bin\/simusol-make) \
	      $(call sedmake2,\/usr\/bin\/simusol-make) \
              $(call sedmake2,\/home\/[^\/]\+\/bin\/simusol-make) \
	   else \
	      echo "FIXME XXX -> simusol-make  $(ESTEMAKE)";\
	      sed -i'' -e "s/-fXXX\./-f$(shell $(shellpath) echo $(ESTEMAKE)|sed -e 's/\//\\\//g')/"  $(ESTEMAKE); \
	      sed -i'' -e "s/,XXX\./,$(shell $(shellpath) echo $(ESTEMAKE)|sed -e 's/\//\\\//g')/"  $(ESTEMAKE); \
	      sed -i'' -e "s/XXX\.:/$(shell $(shellpath) echo $(ESTEMAKE)|sed -e 's/\//\\\//g'):/"  $(ESTEMAKE); \
	fi 

######################3

#definir proceso para recorrer todos los usuarios


# esto es un disparate, poner archivos especificos
cleanuser:
	 rm -rf ~/.simusol
	 rm -rf ~/.dia
	 rm -rf ~/.cpanm
	 rm -rf ~/lib ~/bin
	 rm ~/.gnuplot-wxt
	 rm ~/.simusolbash 
	 rm ~/simusol_arbol_interno
	 rm ~/simusol_diagramas_instalados


# ~/.bashrc ~/.bash_profile
######################################################## Funciones
# ojo si baja mal no dejka el archivo como antes!!!!!!!!!!!!!!!!!!!!!!!!
define download
	@echo $6 esta en: $1
	@if test x"$1" = x ; then \
	 touch INSTALA_companion ;\
	 echo Instalar $6; \
	 mkdir -p $2  2>/dev/null; \
	 rm -f  $2/$3.md5.new ;\
	 wget --no-check-certificate -c -O  $2/$3.md5.new  $4.md5 ; \
	 if test ! -s  $2/$3.md5.new ; then\
	    echo Internet falla bajando $4.md5 ;\
	    rm -f $2/$3.md5.new;\
	 fi; \
	 MD5NEW=`cat $2/$3.md5.new 2>/dev/null| cut -d' ' -f1` ;\
	 MD5=`cat $2/$3.md5 2>/dev/null| cut -d' ' -f1`;\
	 echo md5 $$MD5 md5new $$MD5NEW ;\
	 if test \( -s $2/$3.md5.new -a \
                    \( ! -e $2/$3 -o  \
                       ! -e $2/$3.md5 -o \
                       x$$MD5 != x$$MD5NEW \) \
                 \) ; then \
	    echo Bajando  $4 ;\
	    mkdir -p /tmp/saved  2>/dev/null; \
	    chmod a+w /tmp/saved; \
	    mv -f $2/$3 /tmp/saved 2>/dev/null;\
	    rm -f $2/$3; \
	    wget --no-check-certificate  -P $2 $4; \
	    if test ! -s  $2/$3 ; then\
	       echo Internet falla bajando $4 ;\
	       rm -f $2/$3;\
	     else \
	       rm -f   $2/$3.md5 ;\
	       md5sum -t   $2/$3 > $2/$3.md5 ; \
	       MD5BAJ=`cat  $2/$3.md5 | cut -d' ' -f1` ;\
	       MD5OK=`cat $2/$3.md5.new 2>/dev/null| cut -d' ' -f1`;\
	       echo md5 $$MD5OK md5new $$MD5BAJ ;\
	       if test x$$MD5OK != x$$MD5BAJ ; then \
	          echo EL archivo $4 bajo mal, lo renombro;\
	          mv -f  $2/$3 $2/$3.mal 2>/dev/null ;\
	       fi;\
	       rm -f $2/$3.md5.new  2>/dev/null;\
	    fi; \
          else \
	    echo No bajo: $4 ;\
	 fi; \
	 if  test -e $2/$3 ; then \
	   echo Instalando $6;\
	   if test x"$5" != x; then \
            cd ${BASETMP} ;\
	    tar -zxvf $2/$3 >/dev/null ; \
	    cd $5* ; \
	   fi; \
	   $7 ;\
	   echo $6 fue instalado en ${PREFIX};\
	 else \
	   echo No puede bajar $6 ;\
	 fi;\
	 else \
	   echo No se instala: $6 ya esta instalado en $1;\
	fi
endef


# ojo, si se lo llama dentro de sudo hay problemas!!!!!!!!!!!!
define rmbin 
	@echo rm -f $1 - $3 ;\
	if test x$(SUDO) != x ; then \
	   sudo -n rm -f /usr/local/bin/$2 /usr/bin/$2  ;\
	else \
	  if  test x"$(SUDOPR)" != x ; then \
	   sudo rm -f /usr/local/bin/$2 /usr/bin/$2  ;\
	  else \
	    echo No se pudo ejecutar ningún sudo, si esta en algun /usr  sigue instalado;\
	  fi ;\
	fi; \
	rm -f ~/bin/$2 
endef


define rmfbin
	@echo rmf  $1 ;\
	if test x$(SUDO) != x ; then \
	   sudo -n rm -f /usr/local/share/simusol/pkg/$2 /usr/share/simusol/pkg/$2 ;\
	else \
	  if  test x"$(SUDOPR)" != x ; then \
	    sudo rm -f /usr/local/share/simusol/pkg/$2 /usr/share/simusol/pkg/$2 ; \
	   else \
	    echo No se pudo ejecutar ningún sudo, si esta en algun /usr  sigue instalado;\
	  fi ;\
	fi; \
	rm -f ~/.simusol/pkg/$2
endef



# solo borra targets
# sudo sin n fallara enla interfaz grafica

# en realidad sceptre solo se instala por ahora en /usr/local
# /usr esta reservado para paquetes buinarios del sistema, o sea este make nunca instalara asi
# por ahora no se puede instalar sin sudo

# se podria verificar la fecha o algun cheksum, para proceder (siempre) o antes de proceder (a pedido)

define findfirst
$(shell $(shellpath) test -x /usr/$1  && echo /usr/$1;\
                 test -x /usr/local/$1  && echo /usr/local/$1;\
                 test -x ~/$1  && echo ~/$1;)
endef

define mkmd5
	mkdir -p /tmp/saved  2>/dev/null; exit 0;
	chmod a+w /tmp/saved; exit 0;
	mv -f $1/$2 /tmp/saved; exit 0;
	rm -f $1/$2; exit 0;
	wget --no-check-certificate -c -P $1 $3; 
	md5sum -t   $1/$2 > $1/$2.md5 ;
	scp  $1/$2.md5 wwwrun@simusol.org.ar:/srv/www/htdocs/simusol/simusolsite/downloads/$2.md5
endef



define distro
        SISTEMA=`uname -o |sed -e's/\n//'` ;\
	echo UNAME $$SISTEMA;\
	if test x"$${SISTEMA}" != x"GNU/Linux" ; then \
	  case x$${SISTEMA} in \
           xCygwin)  echo "";   DISTRO=CYGWIN      ;;\
           xCYGWIN*)  echo "";   DISTRO=CYGWIN      ;;\
           xMINGW*)   echo "";   DISTRO=MINGW      ;;\
           xFreeBSD ) echo "";   DISTRO=FREEBSD  ;;\
           xSolaris ) echo "";   DISTRO=SOLARIS  ;;\
           xSunOS )   echo "";   DISTRO=SUNOS  ;;\
           xOpenBSD ) echo "";   DISTRO=OPENBSD       ;;\
           xNetBSD )  echo "";   DISTRO=NETBSD        ;;\
           x* )       echo "";   DISTRO=NONGNULINUX   ;;\
          esac; \
        echo DISTRO $$DISTRO;\
        else \
         UTU=`cat /etc/issue|grep ututo |sed -e's/\n//g'` ; \
	 if test -e /etc/SuSE-release; then \
	   DISTRO=SUSE; \
	 elif test -e /etc/mandriva-release; then \
	   DISTRO=MANDRIVA;\
	 elif test -e /etc/redhat-release; then \
	   DISTRO=REDHAT; \
	 elif test -e /etc/debian_version; then \
	   DISTRO=DEBIAN;\
	   if test -e /etc/issue ; then \
	      UBU=`grep 'Ubuntu' </etc/issue |sed -e's/\n//g'  `;\
              if  test x"$${UBU}" != x ; then \
               DISTRO=UBUNTU;\
              fi; \
	   fi; \
         elif test -e /etc/ututo-release ; then \
           DISTRO=UTUTO;\
         elif  -e /ututo.lastversion ; then \
           DISTRO=UTUTO;\
         elif  x$${UTU} != x ; then \
           DISTRO=UTUTO;\
         elif test -e /etc/gentoo-release; then \
           DISTRO=GENTOO;\
         elif test -e /etc/slackware-version; then \
           DISTRO=SLACKWARE;\
           if test -e /etc/slax-version; then \
             SUBDISTRO=Slax;\
           fi; \
         fi; \
	fi; \
	echo $$DISTRO 
endef


#uso XXX\. porque \. es diferente de . para que no se autoreeemplace
define sedmake
	 echo sedmake $1 
	 sed -i'' -e 's/-fXXX\./-f$2\/bin\/simusol-make/' $1/bin/simusol-make; \
	 sed -i'' -e 's/,XXX\./,$2\/bin\/simusol-make/' $1/bin/simusol-make; \
	 sed -i'' -e 's/XXX\.:/$2\/bin\/simusol-make:/' $1/bin/simusol-make; 
endef

define sedmake2
	      sed -i'' -e 's/-f$1/-fXXX\./'  $(ESTEMAKE); \
	      sed -i'' -e 's/,$1/,XXX\./'  $(ESTEMAKE); \
	      sed -i'' -e 's/$1:/XXX\.:/'  $(ESTEMAKE); 
endef




define installproject
	SOURCE=$(basename  $@) ;\
	PROJ=$(basename $(basename  $@)) ;\
	FILENAME=$(basename $(basename  $(notdir $@))) ;\
        relapath1=$(patsubst ./,,$(dir $@)) ;\
	relapath=`echo $$relapath1 | sed -e 's/\/$$//'`;\
        if test x$$relapath = x ; then \
	     dirp=$(rwdir) ;\
	     ddir=$(CURDIR) ;\
	     dirrp=$(rdirpro) ;\
	   else \
	     dirp=$(rwdir)/$$relapath ;\
	     ddir=$(CURDIR)/$$relapath ;\
	     dirrp=$(rdirpro)/$$relapath ;\
	fi; \
	echo DIRS installproject $$SOURCE - $$PROJ - $$FILENAME - $$relapath;\
	install  -d $2/projects/$$FILENAME;\
	install  -d $2/projects/$$FILENAME/tests;\
	install  -d $2/projects/$$FILENAME/results;\
	install  -d $2/projects/$$FILENAME/tmps;\
	echo "D:$2/$$FILEDIR" >> $(LISTADO) ;\
	install  $(rdirpro)/$$SOURCE  $2/projects ;\
        echo "A:$2/$$SOURCE" >> $(LISTADO) ;\
	cd  $$dirp ;\
        IFIL=`find $$FILENAME -type f -not -wholename '*.svn*'`;\
        IDFIL=`find $$FILENAME -type d -not -wholename '*.svn*'`;\
	$(call installdirs,$$IDFIL,$2/projects,) \
	$(call installfiles,$$IFIL,$2/projects,) 
endef

#	    FILEP=`echo -n $$FILE|sed -e  's/\.\/$3//' ` ;




############### ojo no se porque no hace echo en algunos casos a listado.ls, busque pero no entiendo porque no
define installdirs
	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) ;\
	    echo "D:$2/$$FILEP"  ;\
	   fi;\
	done;
endef

define installfiles
	for FILE in $1 ; do \
	   if test x"$$FILE" != x"." ; then \
	    FILEP=`echo -n $$FILE|sed -e  's/^\.\/$3//' ` ;\
	    install  $$FILE  "$2/$$FILEP";\
	    echo "A:$2/$$FILEP" >> $(LISTADO) ;\
	    echo "A:$2/$$FILEP"  ;\
	   fi;\
	done;
endef



# paquetes efectivamente bajados en un ubuntu casi virgen
# build-essential cvs debhelper dia-common dia-libs dpkg-dev g++ g++-4.4
#  gettext gfortran-4.4 gnuplot-nox gnuplot-x11 groff gsfonts-x11 html2text
#  intltool-debian libatk1.0-dev libcairo2-dev libdirectfb-dev
#  libdirectfb-extra libexpat1-dev libfontconfig1-dev libfreetype6-dev
#  libgfortran3 libglib2.0-dev libice-dev libjpeg62-dev libmail-sendmail-perl
#  libnetpbm10 libpango1.0-dev libpixman-1-dev libpng12-dev libpthread-stubs0
# libpthread-stubs0-dev libsm-dev libstdc++6-4.4-dev libsys-hostname-long-perl
#  libsysfs-dev libx11-dev libxau-dev libxcb-render-util0-dev
#  libxcb-render0-dev libxcb1-dev libxcomposite-dev libxcursor-dev
#  libxdamage-dev libxdmcp-dev libxext-dev libxfixes-dev libxft-dev libxi-dev
#  libxinerama-dev libxrandr-dev libxrender-dev libyaml-syck-perl netpbm
#  po-debconf psutils x11proto-composite-dev x11proto-core-dev
#  x11proto-damage-dev x11proto-fixes-dev x11proto-input-dev x11proto-kb-dev
#  x11proto-randr-dev x11proto-render-dev x11proto-xext-dev
#  x11proto-xinerama-dev xtrans-dev xz-utils zlib1g-dev
