#http://www.linuxparatodos.net/portal/staticpages/index.php?page=como-rpmbuild

#Here are the definitions for some common specfile macros as they are defined on Fedora 13 (rpm-4.8.0-14.fc13). For definitions of more macros, examine the output of "rpm --showrc". To see the expanded definition of a macro use the command rpm --eval "%{macro}". Note that neither command will take into account macros defined inside specfiles, but both will take into account macros defined in your ~/.rpmmacros file and macros defined on the command line. 

#http://fedoraproject.org/wiki/Packaging/RPMMacros
#http://lists.rpm.org/pipermail/rpm-list/2009-March/000221.html
#echo "">~/.rpmmacros
#%{_tmppath}           %{_var}/tmp
#%{_lib}               lib (lib64 on 64bit multilib systems)

cat <<EOF
$RPM_BUILD_ROOT       %{buildroot}
%{__global_cflags}   -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4
%{optflags}          %{__global_cflags} -m32 -march=i686 -mtune=atom -fasynchronous-unwind-tables
$RPM_OPT_FLAGS       %{optflags}

EOF
cat <<EOF >~/.rpmmacros
%_topdir %(echo "$HOME")/rpmbuild
%_tmppath %(echo "$HOME")/rpmbuild/TMP
%_builddir          %{_topdir}/BUILD
%_rpmdir            %{_topdir}/RPMS
%_sourcedir         %{_topdir}/SOURCES
%_specdir           %{_topdir}/SPECS
%_srcrpmdir         %{_topdir}/SRPMS
%_buildrootdir      %{_topdir}/BUILDROOT 
%buildroot          %{_buildrootdir}/%{name}-%{version}-%{release}.%{_arch}
%_var               /var
%_usr               /usr
%_usrsrc            %{_usr}/src
%_lib               lib 
%_docdir            %{_datadir}/doc
%_sysconfdir        /etc
%_prefix            /usr
%_exec_prefix       %{_prefix}
%_bindir            %{_exec_prefix}/bin
%_libdir            %{_exec_prefix}/%{_lib}
%_libexecdir        %{_exec_prefix}/libexec
%_sbindir           %{_exec_prefix}/sbin
%_sharedstatedir    /var/lib
%_datarootdir       %{_prefix}/share
%_datadir           %{_datarootdir}
%_includedir        %{_prefix}/include
%_infodir           /usr/share/info
%_mandir            /usr/share/man
%_localstatedir     /var
%_initddir          %{_sysconfdir}/rc.d/init.d
%debug_package %{nil}
%_unpackaged_files_terminate_build 1
%_signature gpg
%_gpg_path %(echo "$HOME")/.gnupg
%_gpg_name Fulano de Perengano (Una empresa ficticia) <fulano@algún-dominio.com>
%_gpgbin /usr/bin/gpg
%packager Fulano de Perengano <su cuenta de correo o bien http://su-sitio-de-red.com>
%distribution nombre de su producto aquí
%vendor su nombre o nombre de su empresa aquí
%desktop_vendor nombre-de-su-empresa-sin-espacios
EOF
#Creación de la estructura de la jaula para rpmbuild.


## toma de Changelog y prepara info para paquetes

cl2pkgf.pl "$DIRSUMA/ChangeLog" rpm "$TMP_DIR/changelog" "$PACKAGE" "$VERSION" "$RELEASE" 




####################   CONSTRUCCION DE MANIFIESTO ###################
#Son archivos agregados despues, si nolos pongo ahora da error pues no estaran en manifiesto

# estas cosas no deben ir en paquetes que no sean de slack o debian
#touch $UPACKDROOT/$INSTALL/slack-desc
#touch $UPACKDROOT/$DEBIAN/control
#touch $UPACKDROOT/$DEBIAN/rules


find $UPACKDROOT | sed "s+^$UPACKDROOT++" | grep [\/] >$TMP_DIR/newfiles

#reemplazar estas dos lineas anteriores con makeinstall

rm  -f ${TMP_DIR}/newfiles.spec

#. pkgac.dat # ver directorio

# Prepare directories to be included in the .spec file
#sudo mv  ${TMP_DIR}/newfiles ${TMP_DIR}/newfiles.tmp

cat ${TMP_DIR}/newfiles | while read line; do 
# TODOS ESTOS COMANDOS PONERLOS EN EL MAKEFILE EN EL COMANDO INSTALL   ver attr

# sacar echos LINEA pero antes sacar svn
   lineaes=NADA
   linez=$line
   linem=$line
   linem=`echo $line | sed "s|^$BINDIR|%bindir|"`
   if test ! $linem = $line; then
       lineaes=BIN
       linez=$linem
     else
   linem=`echo $line | sed "s|^$INCLUDEDIR|%includedir|"`
   if test ! $linem = $line; then
       lineaes=INCLUDE
       linez=$linem
     else
      linem=`echo $line | sed "s|^$SYSCONFDIR|%sysconfdir|"`
      if test $lineaes = NADA -a ! $linem = $line; then
          linez=$linem
          lineaes=SYSCONF
         else
          linem=`echo $line | sed "s|^$docdir|%docdir|"`  #primeto DOC QUE ES   MAS LARGo, revisar todo esto
          if test $lineaes = NADA -a ! $linem = $line; then
            linez=$linem
            lineaes=DOC
           else
             linem=`echo $line | sed "s|^$MANDIR|%mandir|"`
             if test $lineaes = NADA -a ! $linem = $line; then
               linez=$linem
               lineaes=MAN
             else
             linem=`echo $line | sed "s|^$INFODIR|%infodir|"`
             if test $lineaes = NADA -a ! $linem = $line; then
               linez=$linem
               lineaes=INFO
             else
             linem=`echo $line | sed "s|^$WEBDOCSDIR|%webdocsdir|"`
             if test $lineaes = NADA -a ! $linem = $line; then
               linez=$linem
               lineaes=WEBDOCS
             else
             linem=`echo $line | sed "s|^$LIBDIR|%libdir|"`
             if test $lineaes = NADA -a ! $linem = $line; then
               linez=$linem
               lineaes=LIB
              else
               linem=`echo $line | sed "s|^$DATADIR|%datadir|"`
               if test $lineaes = NADA -a ! $linem = $line; then
                linez=$linem
                lineaes=DATA
             fi
           fi
          fi
           fi
          fi  
       fi
      fi
     fi
    fi
#    echo LINEA ES $lineaes : $linez - $line 
   #echo LINEA ES $lineaes : $linem -$line
   if test -d "$UPACKDROOT/${line}" -o -L "$UPACKDROOT/${line}"; then 
          if test $lineaes = DOC ; then
            echo  "%docdir $linez " >> ${TMP_DIR}/newfiles.spec
           else
            echo  "%dir $linez " >> ${TMP_DIR}/newfiles.spec
           fi
         else
          if test $lineaes = SYSCONF ; then
            echo "%config ${linez}" >> ${TMP_DIR}/newfiles.spec
           else
          if test $lineaes = DOC -o $lineaes = MAN  -o $lineaes = INFO ; then
            echo "%doc %attr(0444,root,root) ${linez}" >> ${TMP_DIR}/newfiles.spec
           else  
            echo "${linez}" >> ${TMP_DIR}/newfiles.spec
          fi
         fi
    fi
done

#\" rodeando las files0.3dcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc


INSTALLEDSIZE=`du -s $UPACKDROOT | awk '{print $1}'`

#spec ver tar.gz


######################### cosntruye spec


#FILESPEC=$UPACKDROOT/$PACKAGE.spec
#FILESPEC=$TMP_DIR/$PACKAGE.spec
FILESPEC=$UPACKDINFO/$PACKAGE.spec

##### ojo poner si no hay redhat o suse, probar con todas otras
brand=redhat

if test x$brand = "xredhat"; then 
    PKG_GROUP=$PKG_GROUP_REDHAT
#    PKGTYPE="rpm"
elif test x$brand = "xsuse"; then 
    PKG_GROUP=$PKG_GROUP_SUSE
#    PKGTYPE="rpm"
fi
if test "x$PKG_GROUP" = "x"; then 
    PKG_GROUP=$PKG_GROUP_SUSE
fi
if test "x$PKG_GROUP" = "x"; then 
    PKG_GROUP=$PKG_GROUP_REDHAT
fi
if test "x$PKG_GROUP" = "x"; then 
     PKG_GROUP="nose"        
         
fi
echo PKGTYPE $PKGTYPE
echo PKG_GROUP $PKG_GROUP

#This is, obviously, a late addendum to this thread, but there is an easy way to get "rpmbuild" to look for tarballs in a directory other than /usr/src/redhat/SOURCES. That is, you need to use the "--define" option to redefine the _usr macro to a "usr" directory of your choosing. For instance:

#rpmbuild --define="_usr /home/hnine/RedHat/usr" ...

#Will cause rpmbuild to look in "/home/hnine/RedHat/usr/src/redhat/SOURCES" for tarballs.

SPECCOL=80


FILE=$FILESPEC.pre
FILEF=$FILESPEC

echo "%define docdir   $docdir">$FILE
echo "%define sysconfdir  $SYSCONFDIR">>$FILE
echo "%define bindir  $BINDIR">>$FILE
echo "%define libdir  $LIBDIR">>$FILE
echo "%define includedir  $INCLUDEDIR">>$FILE
echo "%define infodir  $INFODIR">>$FILE
echo "%define mandir  $MANDIR">>$FILE
echo "%define htmldir  $HTMLDIR">>$FILE
echo "%define datadir  $DATADIR">>$FILE
if test "x$WEBDOCSDIR" != "x"; then
echo "%define webdocsdir   $WEBDOCSDIR">>$FILE
else
echo "%define webdocsdir   /tmp">>$FILE
fi
if test "x$HTTPDCI" != "x"; then
echo "%define cgidir   $HTTPDCGI">>$FILE
else
echo "%define cgidir   /tmp">>$FILE
fi
echo Summary:    $SUMMARY >>$FILE
echo Vendor:     $VENDOR>>$FILE
echo Name:       $PACKAGE>>$FILE
echo Version:    $VERSION>>$FILE
echo Release:    $RELEASE>>$FILE
echo License:    $LICENSE>>$FILE
echo Group:      $PKG_GROUP    >>$FILE      
echo Packager:   $MAINTAINER>>$FILE
echo URL:        $PRIMARYSITE >>$FILE
echo BuildArch:  $ARCH >>$FILE
#$PACKAGE-$VERSION.$RELEASE.tar.gz

if test x"$TYPE" = xsrc.rpm ; then
  #echo "%define _sourcedir $DIRECTORIO_FUENTE" >>$FILE
  #echo Source: $SRC_URI    >>$FILE
  #echo "Source:    http://www.sumapack.org/download/sumapack-ini.tar.gz">>$FILE
  echo "Source:    $SRC_URI/$PKGNAMESE.tar.gz">>$FILE
  #REVISAR, poner source en binarios hace mal
fi

# de aqui toma las fuentes para srpm
#echo "%define _rpmdir $DIRECTORIO_FUENTE" >>$FILE
#echo "%define _rpmdir $UPACKDROOT" >>$FILE
# aqui escribe el resultado (archivo.rpm)
#echo "%define _srpmdir $DIRECTORIO_FUENTE" >>$FILE
#echo "%define _builddir $DIRECTORIO_FUENTE" >>$FILE

#echo BuildRoot: $UPACKDROOT>>$FILE
if test ! -z $ICON; then
echo Icon: $ICON>>$FILE
fi 
echo Prefix: $SYSCONFDIR>>$FILE
echo Prefix: $prefix>>$FILE
if test "x$HTTPDROOT" != "x"; then
echo Prefix: $HTTPDROOT>>$FILE
fi
echo Distribution: $DISTRIBUTION
echo %description >>$FILE
echo -e          $DESCRIPTION |fmt -w $SPECCOL >>$FILE
echo Provides:   "$PACKAGE $PROVIDES">>$FILE
echo Requires:   "/bin/sh $REQUIRES">>$FILE
#echo %prep>>$FILE
#echo >>$FILE
#echo %setup >>$FILE
#-q
#echo >>$FILE
#echo %build>>$FILE
#echo >>$FILE
#echo ./configure
#echo make
#echo %install>>$FILE
#echo>>$FILE
#echo 'rm -rf $RPM_UPACKDROOT'
#echo 'make DESTDIR=$RPM_UPACKDROOT install'
echo %clean>>$FILE
# igual hace un par de cosas, pero no borra el buldroot
#echo>>$FILE
echo "%files">>$FILE
echo "%defattr(-,root,root)">>$FILE

#echo 'rm -rf $RPM_UPACKDROOT'


cat $FILE  /tmp/newfiles.spec $TMP_DIR/changelog > $FILEF

echo FILE $FILEF
rm $FILE

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


#	mkdir -p ${rpmworkdir}
#	mkdir -p $(rpmdir)/SRPMS
#cp ${PACKAGE}-${VERSION}.tar.gz ${rpmworkdir}
#	SALIDAS=`rpmbuild -bs ${PACKAGE}.spec  | awk -F' ' '/\/SRPMS\// {print $2}'`  ;
#	if test "x$$SALIDAS" = "x" ; then 
#	       echo Debe instalar sumapack para poder hacer rpm asi, http://www.sumapack.org       ;
#		rm $(PACKAGE).spec;\
 #              exit 1;\
#	fi; \
#        host=i386

##########################################3 MAL
ABSS=`cd $UPACKDINFO; pwd`
FILE=$ABSS/$PACKAGE.speccomoestamallodejoasi
#if test ! -e $FILE; then
echo Summary:    $PACKAGE >$FILE
#echo Vendor:     $VENDOR>>$FILE
echo Name:       $PACKAGE>>$FILE
echo Version:    $VERSION>>$FILE
echo "Release:    0">>$FILE
echo BuildArch:  $ARCH >>$FILE
if test x"$TYPE" = xsrc.rpm ; then
  echo "Source:    http:/www.sumapack.org/download/$PKGNAMESE.tar.gz">>$FILE
  # asegurar que esta version sea subida en makefile
fi
# toma el nombre para construirla fuente

echo "License:    AGPLv3+">>$FILE
#echo Group:      none    >>$FILE      
#echo Packager:   upack>>$FILE
echo %description >>$FILE
echo -e         $PACKAGE |fmt -w 80 >>$FILE
#echo "%clean" >>$FILE


cat <<EOF  >>$FILE
%prep
%setup -q

%build
#######%configure
./configure --prefix=/usr/local
%__make
%install
%__make DESTDIR=%{buildroot} install
%clean
%__rm -fr %{buildroot}
%preun
%post
/sbin/ldconfig
%postun
EOF

echo "%files" >>$FILE
$(cd ${UPACKDROOT}; find . -type f | sed 's/^\.//' >>$FILE) 
#####################################################################3


#Desde una terminal, genere la estructura de directorios necesaria utilizando lo siguiente:
#mkdir -p ~/rpmbuild/{BUILD,RPMS,SOURCES,SRPMS,SPECS,TMP}
#mkdir -p ~/rpmbuild/RPMS/{athlon,i386,i586,i686,noarch}

#echo "/usr/local/bin/upack" >>$FILE
#echo URL:        $PRIMARYSITE >>$FILE

#fi
