#!/bin/sh
##############################################################################
#         $Id: checkinstall,v 1.4.1.6 2001/06/26 06:52:41 izto Exp $ 
#                           ########################                         
#                                                                            
#
#                             CheckInstall v1.4.1
#
#  Installs a compiled program from the program's source directory using     
#  "make install" or any other command supplied on checkinstall's command  
#  line. checkinstall will create a Slackware or RPM compatible package named
#  after the source directory's name and install it using your standard package 
#  administration utilities.                                                 
#                                                                            
#  This version of checkinstall needs enough free space on the partition     
#  holding the temp dir (see BASE_TEMP_DIR below) to write there a temporary 
#  copy of the package.              
#                                                                            
#  Copyright (C) 2001 Felipe Eduardo Sanchez Diaz Duran                         
#  <fsanchez@uagunix.gdl.uag.mx>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
############################################################################


# Trap the INT signal (ctrl-c, for example)
trap trapint 2

CHECKINSTALL_VERSION=1.4.1


#############################################################################
                           # Function definitions #
                           ########################


function ckversion {
   echo
   echo "checkinstall $CHECKINSTALL_VERSION, Copyright 2001 Felipe Eduardo Sanchez Diaz Duran"
   echo "           This software is released under the GNU GPL."
}



function usage() {

   ckversion
   echo
   echo "Usage: checkinstall [options] <command> <command arguments>"
   echo "Options:"
   echo "-d,-D <0|1|2>			Set debug level"
   echo "-A, --arch=<arch>		Set architecture"
   echo "-t, --type=<slackware|rpm>	Choose packaging system"
   echo "-S				Build a Slackware package"
   echo "-R				Build a RPM package"
   echo "-si				Run an interactive install command"
   echo "--showinstall=<yes|no>		Toggle interactive install command"
   echo "-ss				Run an interactive Slackware"	
   echo	"				installation script"
   echo "--showslack=<yes|no>		Toggle interactive Slackware"
   echo	"				installation script"
   echo "--exclude=<name[,...]>		Exclude files/dirs from the package"
   echo "--autodoinst=<yes|no>		Toggle the creation of a doinst.sh script"
   echo "--deldoc=<yes|no>		Delete doc-pak upon termination"
   echo "--delspec=<yes|no>		Delete spec file upon termination"
   echo "--strip=<yes|no>		Strip any ELF binaries found inside the package"
   echo "--bk				Backup any overwritten files"
   echo "--backup=<yes|no>		Toggle Backup"
   echo "--default, -y			Accept defaults for all questions"
   echo "--spec=<path>			.spec file location"
   echo "--help, -h			Show this message"
   echo "--copyright			Show Copyright information"
   echo "--version			Show version information"
   echo
   exit 1
}

function help_notice() {
 
echo
echo "Use --help or -h to get more information"
echo
exit 1 

}

function boolean_usage() {
   echo
   echo "$2 is an invalid value for $1" 
   help_notice
   exit 1
}


# 001117-BaP: Define a function or two

function yorn {


   if [ "$1" ]; then     # If there is no default value specified
       DEFAULTYN="$1"     # then the default is "Y"
    else
       DEFAULTYN="Y"
    fi
    DEFAULTYN=`echo $DEFAULTYN | tr 'a-z' 'A-Z'`

    if [ "$DEFAULTYN" = "Y" ]; then  
       echo -n " [y]: "              # Print the default option
    else
       echo -n " [n]: "
    fi
    
if [ $ACCEPT_DEFAULT -eq 0 ]; then     # Shall we accept all the defaults?

    read YN
    YN=`echo $YN | tr 'a-z' 'A-Z'`
    ! [ "$YN" ] && YN=$DEFAULTYN          # If the user pressed ENTER then 

else
   YN=$DEFAULTYN
fi

    if [ "$YN" = "Y" ] ;then    # We return something useful for a 
       return 0                 # simpler sintax ahead (12/dic/2000-Izto)
    else
       return 1
    fi


}



# dec/10/2000-Izto
# Prints OK or FAILED! depending on previous command return value

function okfail () {
 if [ $? -gt 0 ]; then
    echo ' FAILED!'
    return 1
 else
    echo 'OK'
    return 0
 fi
}

function restore_backup {
 ls ${TMP_DIR}/backup/*  &> /dev/null
 if [ $? -eq 0 ]; then
    echo -n "Restoring overwritten files from backup..."
    cd ${TMP_DIR}/backup
    tar -cpf - * | tar -f - -xvpC / &> /dev/null
    okfail
    echo
 fi
} 


function trapint {
 echo
 echo
 echo "*** SIGINT received ***"
 cleanup
}

function cleanup {
 echo
 restore_backup
 echo -n "Cleaning up..."
 cd $DIRECTORIO_FUENTE
 rm -rf ${TMP_DIR}
 rm -f $BUILDROOT
 rm -f checkinstall-debug*
 true; okfail
 echo
 echo "Bye."
 echo
 exit 1
}

                      #################################
                      # Function definition ends here #
#############################################################################

# Show the version information
ckversion
echo

if ! [ -f /usr/local/lib/checkinstall/checkinstallrc ]; then
   echo "The checkinstallrc file was not found at:"
   echo "/usr/local/lib/checkinstall/checkinstallrc"
   echo
   echo "Assuming default values."
else
# Get our default settings from the rc file
source /usr/local/lib/checkinstall/checkinstallrc
fi


# Arguments parsing

CKNAME=`basename $0`
PARAMS=`getopt -a -n $CKNAME -o +d:D:A:t:RShHy -l arch:,type:,si,showinstall::,ss,showslack::,deldoc::,delspec::,deldesc::,strip::,bk,backup::,autodoinst::,spec:,exclude:,help,version,copyright,default -- $*`

[ $? -gt 0 ] && help_notice

eval set -- $PARAMS

while [ "$1" != "--" ]; do
   case $1 in
      -h|-H|--help)
         usage;;
      -d|-D)
         shift
         case `eval echo $1` in
            0) DEBUG=0;;
            1|'') DEBUG=1;;
            2) DEBUG=2;;
            *)
               boolean_usage "-D" $1
         esac
         ;;
      -A|--arch)
         shift
         ARCHITECTURE=`eval echo $1`
         ;;
      -t|--type)
         shift
         INSTYPE=`echo $1 | tr 'a-z' 'A-Z'`
         case `eval echo $INSTYPE` in
            RPM|R)
               INSTYPE=R;;
            SLACKWARE|S)
               INSTYPE=S;;
            *)
               echo
               echo $1 is not a valid packaging system. Please use \'rpm\' or \'slackware\'
               echo 
               echo
               exit 1
          esac
          ;;
       -R)
          INSTYPE=R;;
       -S)
          INSTYPE=S;;
       -y)
          ACCEPT_DEFAULT=1;;
       --si)
          SHOW_INSTALL=1;;
       --showinstall)
          shift
          case `eval echo $1` in
             1|yes|'')
                SHOW_INSTALL=1;;
             0|no)
                SHOW_INSTALL=0;;
             *)
                boolean_usage "--showinstall" $1
          esac
          ;;
       --ss)
          SHOW_SLACK_INSTALL=1;;
       --showslack)
          shift
          case `eval echo $1` in
             1|yes|'')
                SHOW_SLACK_INSTALL=1;;
             0|no)
                SHOW_SLACK_INSTALL=0;;
             *)
                boolean_usage "--showslack" $1
          esac
          ;;
       --deldoc)
          shift
          case `eval echo $1` in
             1|yes|'')
                DEL_DOCPAK=1;;
             0|no)
                DEL_DOCPAK=0;;
             *)
                boolean_usage "--deldoc" $1
          esac
          ;;
       --delspec)
          shift
          case `eval echo $1` in
             1|yes|'')
                DEL_SPEC=1;;
             0|no)
                DEL_SPEC=0;;
             *)
                boolean_usage "--delspec" $1
          esac
          ;;
       --deldesc)
          shift
          case `eval echo $1` in
             1|yes|'')
                DEL_DESC=1;;
             0|no)
                DEL_DESC=0;;
             *)
                boolean_usage "--deldesc" $1
          esac
          ;;
       --strip)
          shift
          case `eval echo $1` in
             1|yes|'')
                STRIP_ELF=1;;
             0|no)
                STRIP_ELF=0;;
             *)
                boolean_usage "--strip" $1
          esac
          ;;
       --bk)
          BACKUP=1;;
       --backup)
          shift
          case `eval echo $1` in
             1|yes|'')
                BACKUP=1;;
             0|no)
                BACKUP=0;;
             *)
                boolean_usage "--backup" $1
          esac
          ;;
       --default)
          ACCEPT_DEFAULT=1;;
       --spec)
	  shift
	  SPEC_PATH=`eval echo $1`
          ;;
       --copyright|--version)
          cat << EOF

Copyright (C) 2001 Felipe Eduardo Sanchez Diaz Duran <izto@mayams.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

EOF
         exit 0;;
       --autodoinst)
          shift
          case `eval echo $1` in
             1|yes|'')
                AUTODOINST=1;;
             0|no)
                AUTODOINST=0;;
             *)
                boolean_usage "--autodoinst" $1
          esac
          ;;
      --exclude)
         shift
         EXCLUDE=`eval echo $1`
         ;;
   esac
   shift
done

# See if we have and install command
shift

[ "$1" = "" ] && set -- "make install"

# End of argument parsing

#############################################################################
                   # We initialize some useful variables #
                   #######################################

################################################################
# User-configurable variables were moved to the checkinstallrc #
# file which is probably found at /usr/local/lib/checkinstall  #          
#                                                              #
#                  DO NOT modify them here!!                   #
################################################################


# Debug level
! [ "$DEBUG" ] && DEBUG=0

INSTALLWATCH_PREFIX="/usr/local"
INSTALLWATCH=${INSTALLWATCH_PREFIX}/bin/installwatch

# Default architecture type
! [ "$ARCHITECTURE" ] && ARCHITECTURE=""

# Default package type
! [ "$INSTYPE" ] &&INSTYPE=""

# Interactively show the results of the install command
# This is useful for interactive installation commands
! [ "$SHOW_INSTALL" ] && SHOW_INSTALL=1

# Show Slackware package installation script while it runs? Again, useful if
# it's an interactive script
! [ "$SHOW_SLACK_INSTALL" ] && SHOW_SLACK_INSTALL=0

# Automatic deletion of "doc-pak" upon termination
! [ "$DEL_DOCPAK" ] && DEL_DOCPAK=1

# Automatic deletion of the spec file
! [ "$DEL_SPEC" ] && DEL_SPEC=1

# Automatic deletion of "description-pak"
! [ "$DEL_DESC" ] && DEL_DESC=1

# Automatically strip all ELF binaries
! [ "$STRIP_ELF" ] && STRIP_ELF=1

# Backup all files modified by the install command supplied by the user
! [ "$BACKUP" ] && BACKUP=1 

# Write description installing code to doinst.sh
! [ "$AUTODOINST" ] && AUTODOINST=1 

# We won't include anything under this directories
! [ "$EXCLUDE" ] && EXCLUDE=""

# Accept the default answer for all the questions
! [ "$ACCEPT_DEFAULT" ] && ACCEPT_DEFAULT=0

####################
# Non-configurable #
####################

DIRECTORIO_FUENTE=`pwd`
PKG_BASENAME=`basename $DIRECTORIO_FUENTE`
NOMBRE_DEL_PAQUETE=${PKG_BASENAME}-pak.tgz


MAKEPKG=/usr/local/sbin/makepak
INSTALLCMD="$@"
: ${INSTALLCMD:='make install'}


                      #################################
                      # Variable definition ends here #
#############################################################################



if [ ! -x $INSTALLWATCH ]; then
   echo
   echo "I can't find $INSTALLWATCH."
   echo
   echo "I can't continue. Either install installwatch or"
   echo "modify the INSTALLWATCH variable in this script,"
   echo "then run checkinstall again."
   echo
   exit 1
fi

echo


# Find a safe TMP_DIR

TMP_DIR=${BASE_TMP_DIR}/`awk 'BEGIN { srand(); for (i=1;i<21;i++) { a=95; while (a > 90 && a < 97) { a=65+int(50*rand())}; printf("%c", a) } }'`
[ -e "$TMP_DIR" ] && rm -rf $TMP_DIR
if [ -e "$TMP_DIR" ]; then 
   echo
   echo "My temp dir exists already."
   echo "This looks like a symlink attack!"
   echo 
   echo "*** Aborting"
   echo
   exit 1
fi

if [ "$TMP_DIR" = "$BASE_TMP_DIR" -o "$TMP_DIR" = "/" ]; then
  echo 
  echo "\"$TMP_DIR\" is an unacceptable value for the temp dir. Please"
  echo "edit the variable definition for $TMP_DIR and try again."
  echo
  echo "*** Aborting"
  echo
  exit 1
fi


mkdir $TMP_DIR
chmod 700 $TMP_DIR
RETURN=$?

if [ $RETURN -gt 0 ]; then
   echo
   echo "**** Failed to create temp dir!"
   echo "**** Do you have write permission for ${BASE_TMP_DIR}?"
   echo
   echo '**** Aborting installation.'
   echo
   exit  $RETURN
fi

BUILD_DIR=${TMP_DIR}/package
mkdir $BUILD_DIR

if [ $DEBUG -gt 0 ] ;then 
   echo "The temporary directory is: [ $TMP_DIR ]"
   echo
fi


# 001117-BaP: We can create a default set of docs on the fly . . .
#   The list I've included should cover most packages adequately. If not,
#   then you should really create the package doc set *manually*


if  ! [ -d $DIRECTORIO_FUENTE/doc-pak ]; then
    echo "The package documentation directory ./doc-pak does not exist."
    echo -n "Should I create a default set of package docs? "
    if  yorn ; then
        echo
        echo -n "Preparing package documentation..."
        mkdir doc-pak
         for f in ABOUT ABOUT-NLS ANNOUNCE AUTHORS *BUGS* CHANGES CONFIGURATION *COPYING* *COPYRIGHT* CREDITS ChangeLog Changelog CHANGELOG CONTRIBUTORS *FAQ* FEATURES FILES HACKING History HISTORY INSTALL* LICENSE LSM MANIFEST NEWS *README* *Readme* SITES *RELEASE* RELNOTES THANKS TIPS TODO VERSION CONFIGURATION* GPL License ; do
            if [ -f $f ]; then                                                 
                cp -a $f doc-pak
            fi
        done
        okfail
        DOCS=`ls doc-pak`
        if ! [ "$DOCS" ]; then
           echo
           echo "*** No known documentation files were found. The new package"
           echo "*** won't include a documentation directory."
           rm -rf doc-pak                 # If doc-pak is empty then we
        fi                                # don't need it
    fi                                    
    
fi



#
# We run the program installation from the source directory       
#

# Write a small script to run the install command. This way the LD_PRELOAD
# environment variable will be available to it, wich among other things
# will allow proper detection of new symbolic links and files created by
# subshells.

TMP_SCRIPT=${TMP_DIR}/installscript.sh

cat << EOF > $TMP_SCRIPT
#!/bin/sh

# Copy the documentation files           

if [ -d $DIRECTORIO_FUENTE/doc-pak ]; then             # Are there any files? 
   echo
   echo "Copying documentation directory..."
   mkdir -p /usr/doc/`basename $DIRECTORIO_FUENTE`
   cd $DIRECTORIO_FUENTE/doc-pak
   tar -cpf - * | tar -f - -xvpC /usr/doc/`basename $DIRECTORIO_FUENTE` &> /dev/null
   [ \$? -gt 0 ] && exit 1
   chown -R root.root /usr/doc/`basename $DIRECTORIO_FUENTE`
fi

cd $DIRECTORIO_FUENTE
$INSTALLCMD

# Report success or failure
if [ \$? -eq 0 ]; then
   exit 0
else
   exit 1
fi

EOF

# No one needs to see what we are doing. It's safer this way.
chmod 700 $TMP_SCRIPT


echo
echo -n "Installing with \"$INSTALLCMD\"..."


# Are we going to do the backup?

if [ "$BACKUP" = "1" ]; then 
    export INSTALLWATCH_BACKUP_PATH=${TMP_DIR}/backup
else
    unset INSTALLWATCH_BACKUP_PATH
fi

export LD_PRELOAD=${INSTALLWATCH_PREFIX}/lib/installwatch.so

# Run the install command, showing the results interactively if we were asked
# to do so in the configuration section (see the SHOW_INSTALL switch above)
if [ $SHOW_INSTALL -eq 0 ]; then
   $INSTALLWATCH -o /${TMP_DIR}/newfiles.tmp $TMP_SCRIPT &> /${TMP_DIR}/install.log
   okfail
   unset INSTALLWATCH_BACKUP_PATH
else
   echo
   echo
   echo ========================= Installation results ===========================
   $INSTALLWATCH -o /${TMP_DIR}/newfiles.tmp $TMP_SCRIPT 2>&1 
   if [ $? -eq 0 ]; then 
      echo
      echo ======================== Installation succesful ==========================
      true     #
   else        # This is ugly, but it works  ;-)
      false    #
   fi
fi

INSTALL_FAILED=$?
unset INSTALLWATCH_BACKUP_PATH

unset LD_PRELOAD


VIEWLOG="n"
if [ $INSTALL_FAILED -gt 0 ]; then 
   echo
   echo "****  Installation failed. Aborting package creation."
   VIEWLOG="y"
fi

if [ $SHOW_INSTALL -eq 0 ]; then
   echo
   echo -n "Do you want to view the installation log file? "

   if  yorn $VIEWLOG ; then

      (echo
       echo ' ***************************************************************'
       echo '         Installation results. You can find them in'
       echo "       ${TMP_DIR}/install.log"
       echo ' ***************************************************************'
       echo
       cat /${TMP_DIR}/install.log)  | less
   fi
fi

if [ $INSTALL_FAILED -gt 0 ]; then 
   cleanup
   exit $INSTALL_FAILED
fi


#
# Extract the relevant files from the modified files list
#

# Find regular files first
cat /${TMP_DIR}/newfiles.tmp | cut -f 3 | egrep -v "/dev|$BASE_TMP_DIR|/tmp" | sort -u > /${TMP_DIR}/newfiles

# symlinks are next
cat /${TMP_DIR}/newfiles.tmp | cut -f 4 | egrep -v "/dev|$BASE_TMP_DIR|/tmp" | grep -v "#success" | sort -u  >> /${TMP_DIR}/newfiles

# OK, now we clean it up a bit
mv /${TMP_DIR}/newfiles.tmp /${TMP_DIR}/newfiles.installwatch
sort -u <  /${TMP_DIR}/newfiles | uniq  | while read file; do
   ! [ -d "$file" ] && [ -e "$file" ] && echo $file >> /${TMP_DIR}/newfiles.tmp
done

cp /${TMP_DIR}/newfiles.tmp /${TMP_DIR}/newfiles

# Don't include anything under the directories specified with "--exclude"

[ $DEBUG -gt 0 ] && echo EXCLUDE=$EXCLUDE

for exclude in `echo $EXCLUDE | awk '{ split ($0, files,","); for(i=1; files[i] != ""; i++) print files[i];}'`; do
   if [ -d $exclude ]; then  # If it's a directory, ignore everything below it
      egrep -v "^$exclude" < /${TMP_DIR}/newfiles > /${TMP_DIR}/newfiles.tmp
   else
      if [ -f $exclude ]; then  # If it's a file, ignore just this one
         egrep -v "^$exclude$" < /${TMP_DIR}/newfiles > /${TMP_DIR}/newfiles.tmp
      fi
   fi
   cp /${TMP_DIR}/newfiles.tmp /${TMP_DIR}/newfiles
done


## Find any files created in `pwd`. We probably don't want them here

grep `pwd` ${TMP_DIR}/newfiles > /${TMP_DIR}/unwanted 
if [ $? = 0 ]; then 
   echo
   echo "Some of the files created by the installation are inside the build"
   echo "directory: `pwd`"
   echo
   echo "You probably don't want them to be included in the package,"
   echo "especially if they are inside your home directory."
   echo -n "Do you want me to list them? "
   if  yorn "n"; then
      less ${TMP_DIR}/unwanted
   fi
   echo -n "Should I exclude them from the package? (Saying yes is a good idea) "
   if  yorn ; then
      grep -v `pwd` ${TMP_DIR}/newfiles > /${TMP_DIR}/newfiles.tmp
      mv /${TMP_DIR}/newfiles.tmp /${TMP_DIR}/newfiles
   fi
fi
   
#
# Copy the files to the temporary directory
#

echo
echo -n "Copying files to the temporary directory..."

cd /

cat /${TMP_DIR}/newfiles | while read i; do 
   if ! [ -d "$i" -a -e "$i" ]; then 
      (tar -cpf - "$i"| tar -f - -xvpC ${BUILD_DIR}) &> /${TMP_DIR}/checkinstall.log
   fi
done
okfail


# Strip ELF binaries (Taken from the rpm's brp-strip script) 

if [ $STRIP_ELF -eq 1 ]; then
   echo
   echo -n "Striping ELF binaries..."
   for f in `find ${BUILD_DIR} -type f \( -perm -0100 -or -perm -0010 -or -perm -0001 \) -exec file {} \; | \
        grep -v ' shared object,' | \
        sed -n -e 's/^\(.*\):[  ]*ELF.*, not stripped/\1/p'`; do
        strip $f || :
   done
   okfail
fi


## Do we have a package description file? If we don't then 
## we should write one

cd $DIRECTORIO_FUENTE


if [ $ACCEPT_DEFAULT -eq 0 ]; then  # If --default is given, we skip this 
 if ! [ -r description-pak ]; then
   DESCRIPTION="Package created with checkinstall $CHECKINSTALL_VERSION"
   echo
   echo "Please write a description for the package. Remember that pkgtool shows"
   echo "only the first one when listing packages so make that one descriptive."
   echo "End your description with an empty line or EOF."
   while [ "$DESCRIPTION" ]; do
      echo -n ">> " 
      read DESCRIPTION
      [ "$DESCRIPTION" ] && echo "$DESCRIPTION" >> description-pak
   done
 fi
fi

# We still don't have it??
! [ -r description-pak ] && echo "Package created with checkinstall $CHECKINSTALL_VERSION" > description-pak


if ! [ "$INSTYPE" ]; then
   echo
   echo "Please choose the packaging method you want to use."
   echo -n "Slackware [S] or RPM [R]? "
   read INSTYPE
fi
echo


FAILED=0

case $INSTYPE in

#####################################
# Create Slackware compatible tarball
#

s|S)  


echo
echo "********************************************"
echo "**** Slackware package creation selected ***"
echo "********************************************"
echo

FAILED=0

# Create the Slackware installation script

echo -n "Preparing Slackware install directory..."
mkdir -p ${BUILD_DIR}/install
touch ${BUILD_DIR}/install/doinst.sh
okfail

#
# Generate the description-installing doinst.sh
#

if [ $AUTODOINST -eq 1 ]; then
   echo "PACKAGE DESCRIPTION:" > ${BUILD_DIR}/install/description
   cat description-pak | while read line; do
      echo $line >> ${BUILD_DIR}/install/description
   done
   
   echo
   echo -n "Writing Slackware install script..."
   cat << EOF >> ${BUILD_DIR}/install/doinst.sh
   echo 
   cat /install/description
   
   sed '/PACKAGE LOCATION/r /install/description' < /var/log/packages/$PKG_BASENAME-pak > description.tmp
   mv description.tmp /var/log/packages/$PKG_BASENAME-pak
   rm /install/description
   
EOF
   okfail
fi


# If we have a Slackware install script already, add it to this one
if [ -f install-pak ]; then
   echo -n "Appending your script to the main install script..."
   cat install-pak >> ${BUILD_DIR}/install/doinst.sh
   okfail
fi

   

echo
echo -n "Creating package $NOMBRE_DEL_PAQUETE..."

cd $BUILD_DIR
chmod 755 $BUILD_DIR


$MAKEPKG $NOMBRE_DEL_PAQUETE &> /dev/null
okfail
mv $NOMBRE_DEL_PAQUETE $DIRECTORIO_FUENTE

#
# Install the package to register it in Slackware's installed packages list    
# so we can list it's contents with pkgtool o remove it with removepkg
#

# Go back to where we started
cd $DIRECTORIO_FUENTE

echo
if [ $SHOW_SLACK_INSTALL -eq 0 ]; then
   echo -n "Installing package..."
   installpkg $DIRECTORIO_FUENTE/$NOMBRE_DEL_PAQUETE &> ${TMP_DIR}/slackinstall.log
   okfail
   [ $? -gt 0 ] && FAILED=1

else
   echo ========================= Installation results ===========================
   echo
   installpkg $DIRECTORIO_FUENTE/$NOMBRE_DEL_PAQUETE
   if [ $? -gt 0 ]; then
      FAILED=1
   else
      echo
      echo ======================== Installation succesful ==========================
   fi
fi

if [ $FAILED -eq 1 ]; then
   echo
   echo "*** Failed to install the package"
   echo
   echo -n "Do you want to see the log file? " 
   if yorn ; then
      less ${TMP_DIR}/slackinstall.log
      cleanup
      exit 1
   fi
fi
 

PKG_LOCATION=${DIRECTORIO_FUENTE}/${NOMBRE_DEL_PAQUETE}
REMOVESTRING="removepkg ${PKG_BASENAME}-pak"
;;
########## End Slackware package section ##########


##########################
# RPM package installation
#

r|R)

echo
echo "**************************************"
echo "**** RPM package creation selected ***"
echo "**************************************"


# Figure out what kind of machine are we running on

if ! [ "$ARCHITECTURE" ]; then
   ARCHITECTURE=`uname -m`
   echo $ARCHITECTURE | grep i[3456]86 &> /dev/null
   [ $? -eq 0 ] && ARCHITECTURE=i386  # Arch will be "i386" for any of
fi                                    # i386, i486, i586 or i686.
                                      # You can change this with "--arch"



# Find out the RPM source directory path

if ! [ "$RPMSOURCEDIR" ]; then
   RPMSOURCEDIR="NOT-FOUND"
   for directory in packages redhat RedHat rpm RPM "" ; do
    [ -d /usr/src/${directory}/SOURCES ] && RPMSOURCEDIR="/usr/src/${directory}"
   done
fi

[ $DEBUG -gt 0 ] && echo RPMSOURCEDIR=$RPMSOURCEDIR


while ! [ -d "$RPMSOURCEDIR/SOURCES" ]; do
   echo
   echo "$RPMSOURCEDIR has no SOURCES directory. Please write the path to"
   echo -n "the RPM source directory tree: "
   read RPMSOURCEDIR
   ! [ "$RPMSOURCEDIR" ] && RPMSOURCEDIR="NOT-FOUND"
done

   
# We'll write a basic spec file

if ! [ -f $PKG_BASENAME.spec ]; then


SUMMARY=`head -1 description-pak`
NAME=`echo $PKG_BASENAME | rev | cut -f2- -d"-" | rev`
VERSION=`echo $PKG_BASENAME | rev | cut -f1 -d"-" | rev`
RELEASE=1
LICENSE="GPL"
GROUP="Applications/System"

   OPTION=junk
   while [ "$OPTION" ]; do

      # Some sanity checks
      ! [ "$SUMMARY" ] && SUMMARY="No summary"
      ! [ "$NAME" ] && NAME="NOT-FOUND"
      ! [ "$VERSION" ] && VERSION="NOT-FOUND"
      ! [ "$RELEASE" ] && RELEASE="1"
      ! [ "$LICENSE" ] && LICENSE="GPL"
      ! [ "$GROUP" ] && GROUP="Applications/System"
      ! [ "$ARCHITECTURE" ] && ARCHITECTURE="i386"
      
      
      echo
      echo "The spec file for this package will include these values: "
      echo
      echo "1 - Summary: [ $SUMMARY ]"
      echo "2 - Name:    [ $NAME ]"
      echo "3 - Version: [ $VERSION ]"
      echo "4 - Release: [ $RELEASE ]"
      echo "5 - License: [ $LICENSE ]"
      echo "6 - Group:   [ $GROUP ]"
      echo "7 - Architecture: [ $ARCHITECTURE ]"
      echo
      echo -n "Enter a number to change any of them or press ENTER to continue: "
      read OPTION

      case $OPTION in
         1)
            echo "Enter new summary: "
            echo -n ">> "
            read SUMMARY
            ;;
         2)
            echo "Enter new name: "
            echo -n ">> "
            read NAME
            ;;
         3)
            echo "Enter new version: "
            echo -n ">> "
            read VERSION
            ;;
         4)
            echo "Enter new release number: "
            echo -n ">> "
            read RELEASE
            ;;
         5)
            echo "Enter license type: "
            echo -n ">> "
            read LICENSE
            ;;
         6)
            echo "Enter new software group: "
            echo -n ">> "
            read GROUP
            ;;
         7)
            echo "Enter the architecture type: "
            echo -n ">> "
            read ARCHITECTURE
            ;;
      esac
   done
   
   # The PKG_BASENAME is adjusted to reflect any changes
   # in the NAME and VERSION of the package

   PKG_BASENAME=$NAME-$VERSION  


   cat > $PKG_BASENAME.spec << EOF
Summary:   $SUMMARY
Name:      $NAME
Version:   $VERSION
Release:   $RELEASE
Copyright: $LICENSE
Packager:  checkinstall-$CHECKINSTALL_VERSION
Group:     $GROUP          
BuildRoot: $DIRECTORIO_FUENTE/buildroot          

%description
EOF
   cat description-pak >> $PKG_BASENAME.spec  

   cat >> $PKG_BASENAME.spec << EOF

%files
EOF

# Append the file list to the .spec file
cat ${TMP_DIR}/newfiles | while read line; do 
                             echo "\"${line}\""  >> $PKG_BASENAME.spec
                          done
fi

BUILDROOT=`egrep '^[Bb]uild[Rr]oot' < $PKG_BASENAME.spec | cut -f2 -d:`

# We make sure that we have a valid RELEASE number

! [ "$RELEASE" ] && RELEASE=`egrep '^Release:' < $PKG_BASENAME.spec|cut -f2 -d: | awk '{ for (i=1;substr ($0,i,1) ~ /[[:blank:]]/ ;i++); print substr ($0,i); }'`

[ $DEBUG -gt 0 ] && echo BUILDROOT=$BUILDROOT

! [ -d "$BUILDROOT" ] &&  ln -s $BUILD_DIR $BUILDROOT

# We make sure that the architecture directory exists

! [ -d ${RPMSOURCEDIR}/RPMS/${ARCHITECTURE} ] && mkdir -p ${RPMSOURCEDIR}/RPMS/${ARCHITECTURE}


mkdir ${TMP_DIR}/$PKG_BASENAME
cd $TMP_DIR
tar -cz $PKG_BASENAME -f ${RPMSOURCEDIR}/SOURCES/${PKG_BASENAME}.tgz
rm -rf ${TMP_DIR}/$PKG_BASENAME
cd $DIRECTORIO_FUENTE

echo
echo -n "Building RPM package..."
rpm -bb --target=$ARCHITECTURE $PKG_BASENAME.spec &> ${TMP_DIR}/rpmbuild.log
okfail

if [ $? -gt 0 ]; then
   echo
   echo "*** Failed to build the package"
   echo
   echo -n "Do you want to see the log file? " 
   if yorn ; then
      less ${TMP_DIR}/rpmbuild.log
   fi
   FAILED=1
fi
 
RPMPKG=${RPMSOURCEDIR}/RPMS/${ARCHITECTURE}/${PKG_BASENAME}-${RELEASE}.${ARCHITECTURE}.rpm


if ! [ $FAILED -gt 0 ]; then 
   echo
   echo -n "Installing RPM package..."
   rpm -U $RPMFLAGS ${RPMPKG} &>  ${TMP_DIR}/rpminstall.log
   okfail
   if [ $? -gt 0 ]; then
      echo
      echo "*** Failed to install the package"
      echo
      echo -n "Do you want to see the log file? " 
      if yorn ; then
         less ${TMP_DIR}/rpminstall.log
      fi
      FAILED=1
   fi
fi
   
if ! [ $FAILED -gt 0 ]; then
   PKG_LOCATION=$RPMPKG
   REMOVESTRING="rpm -e ${PKG_BASENAME}-${RELEASE}"
else
   cleanup
fi

;;
########## End RPM package section ##########

*)
   echo
   echo "*** No method was selected, I won't build any package."
   echo "*** The installation command \"$INSTALLCMD\""
   echo "*** has already been executed."
   restore_backup
   FAILED=1
;;

esac

#
# Remove trash from TMP_DIR
#

echo 
echo -n "Erasing temporary files..."

[ $DEBUG -lt 2 ] && rm -rf ${BUILD_DIR}
rm -f checkinstall-debug*
rm -f $BUILDROOT
okfail


# Delete doc-pak directory
if [ $DEL_DOCPAK -gt 0 ]; then
   echo
   echo -n "Deleting doc-pak directory..."
   rm -rf doc-pak
   okfail
fi


# Preserve the spec file if debugging is on
[ $DEBUG -gt 0 ] && [ -f ${PKG_BASENAME}.spec ] && cp ${PKG_BASENAME}.spec $TMP_DIR

# Delete spec file
 [ $DEL_SPEC -gt 0 ] && rm -f $PKG_BASENAME.spec

# Delete the package description file
 [ $DEL_DESC -gt 0 ] && rm -f description-pak

# If we have a backup, pack it up

ls ${TMP_DIR}/backup/* &> /dev/null
if [ $? -eq 0 ]; then              
   cd ${TMP_DIR}/backup
   echo
   echo -n "Writing backup package..."
   tar -cpf - * | gzip -9 > ${DIRECTORIO_FUENTE}/backup-`date +%m%d%Y%H%M`-pre-${PKG_BASENAME}.tgz
   okfail
fi


if [ $DEBUG -eq 0 ]; then
   echo
   echo -n "Deleting temp dir..."
   rm -rf ${TMP_DIR}
   okfail
else
   echo
   echo -n "Building debug information package..."
   cd ${TMP_DIR}
   echo `uname -a` > sysinfo
   echo `rpm --version` >> sysinfo
   tar -cpzvf ${DIRECTORIO_FUENTE}/checkinstall-debug.$$.tgz * &> /dev/null
   okfail
fi


if ! [ $FAILED -gt 0 ]; then
   echo
   echo '**********************************************************************'
   echo
   echo " Done. The new package has been installed and saved to"
   echo " $PKG_LOCATION"
   echo
   echo " You can remove it from your system anytime using: "
   echo
   echo "      $REMOVESTRING"
   echo
   echo '**********************************************************************'
   echo
fi


