#!/bin/bash
##############################################################################
# install-tarball
# Compile source tarball in the current directory, then
# Install it and also produce Vector Linux (slackware) package
# In the current directoryscript will produce:
#   package-version-ARCH-RELEASE.tgz
#   package-version-ARCH-RELEASE.txt
#   package-version-ARCH-RELEASE.tgz.md5
#
# (c) 2003, Eko M. Budi
# License: GNU GPL
#
# Parts of this script were taken from 
# - SlackBuild, commonly available in various Slackware's source packages
# - makepkg, Copyright 1994, 1998  Patrick Volkerding, Moorhead, Minnesota USA 
# - checkinstall 1.5.3, Copyright 2001 Felipe Eduardo Sanchez Diaz Duran
#
#    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.
#
############################################################################

usage()
{
echo "install-tarball
Build and install tarball in the current directory

Usage: install-tarball 
"
exit 0
}

pause()
{
if [ "$PAUSE" = "yes" ]; then
   echo  $*
   echoc "Press Enter to continue" cyan
   read
fi 
}

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  usage
fi

# determine the values
VERSION=0.1
CONFIGURE_CMD="./configure"
MAKE_CMD="make"
INSTALL_CMD="make install"
INSTALLPKG="pkg -i"
UPGRADEPKG="pkg -u"
CHMOD="chmod"
CHOWN="chown"

# Transfer global variables
# Sorry, not the same, since the were evolve :)
[ -z "$MAKE_DIR" ] && MAKE_DIR=$HOME/make
[ -z "$DEST_DIR" ] && DEST_DIR=$HOME/dest
[ -z "$PKG_DIR" ] && PKG_DIR=$HOME/pkg

mkdir -p $MAKE_DIR || exit 1
mkdir -p $DEST_DIR || exit 1
mkdir -p $PKG_DIR  || exit 1

# Empty the variables we expect from settings.sh
PNAME=""
PVERSION=""
PVERSION_EXTRA=""
PARCH=""
TNAME=""
# but not this one, PRELEASE=""

# Source the settings
if [ -f settings.sh ]; then
   . settings.sh
fi

CWD=`pwd`

# compilation settings
MARCH=${MARCH:-`uname -m`}
PREFIX=${PREFIX:-/usr/local}
CONFIGURE=${CONFIGURE:---prefix=$PREFIX}

# set package name & tarball name
PNAME=${PNAME:-`basename $CWD`}
TNAME=${TNAME:-$PNAME}

# Do we have a TGZ ?
if [ -f $PNAME*.tgz ]; then
    TGZBALL=`ls -1r $PNAME*.tgz` 
    echo "Found prepack package $TGZBALL"
    TNAME_VER_ARCH_REL=${TGZBALL%.tgz} # remove suffix
    TREL=${TNAME_VER_ARCH_REL##*-}          # Everthing after the last '-'
    TNAME_VER_ARCH=${TNAME_VER_ARCH_REL%-*} # remove REL
    TARCH=${TNAME_VER_ARCH##*-}         # Everything after the last -
    TNAME_VER=${TNAME_VER_ARCH%-*}      # remove ARCH
    TVER=${TNAME_VER#$PNAME-}           # get the version
    echo "Old package=$TGZBALL"
fi

# Do we have a tarball ?
TARBALL=`ls -1r $TNAME*.tar.bz2 2>/dev/null | head -n1`
if [ "$TARBALL" ]; then
    echo "Found tarball $TARBALL"
    TNAME_VER=${TARBALL%.tar.bz2}
    TVER=${TNAME_VER#${TNAME}-}
    echo "Tarball= $TARBALL"
else
    TARBALL=`ls -1r $TNAME*.tar.gz 2>/dev/null | head -n1`
    if [ "$TARBALL" ]; then
	echo "Found tarball $TARBALL"
	TNAME_VER=${TARBALL%.tar.gz}
	TVER=${TNAME_VER#${TNAME}-}
	echo "Tarball= $TARBALL"
    fi
fi
if [ -d "custom*" ]; then
  echo -n "Custom= "
  for F in custom*; do
    echo -n "$F "
  done
  echo
fi
if [ -f "*-pak" ]; then
  echo -n "Package scripts= "
  for F in *-pak; do
    echo -n "$F "
  done
  echo
fi
if [ -f "*.sh" ]; then
  echo -n "Build scripts= "
  for F in *.sh; do
    echo -n "$F "
  done
  echo
fi

# determine package version
PVERSION=${PVERSION:-$TVER}
if [ -z "$PVERSION" ]; then
    echoc "ERROR: Cannot determine version" red
    exit 1
fi
PVERSION=${PVERSION}${PVERSION_EXTRA}

# determine package arch from TARCH then MARCH
PARCH=${PARCH:-$TARCH}
PARCH=${PARCH:-$MARCH}

# package release
PRELEASE=${PRELEASE:-$TREL}
PRELEASE=${PRELEASE:-1}

# package format
PEXT=${PKGFORMAT:-tgz}

# the proposed name + version
PNAME_VER="$PNAME-$PVERSION"
PNAME_VER_ARCH_REL="$PNAME_VER-$PARCH-$PRELEASE"

echo "Package to be build= $PNAME_VER_ARCH_REL.$PEXT"

############################################################################
# here we go now

# installing the package
install_pkg()
{
   PARAM=$1
   if [ "$TARGET" ]; then
      if [ "$INSTALL_HOST" = "yes" ]; then
         pkg $PARAM $PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT && ldconfig && \
         echoc "Package $PNAME is installed on the HOST" green
      fi
      if [ "$INSTALL_PKG" = "yes" ]; then
         ROOT=$TARGET pkg $PARAM $PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT && \
         echoc "Package $PNAME is installed on the TARGET" green
      fi
   elif [ "$INSTALL_HOST" = "yes" ] || [ "$INSTALL_PKG" = "yes" ]; then
      pkg $PARAM $PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT && ldconfig && \
      echoc "Package $PNAME has been installed" green
   else
      echoc "Package $PNAME_VER_ARCH_REL.$PEXT is not installed" cyan
      return 0
   fi
   if [ ! $? = 0 ]; then
      echoc "ERROR: Cannot install package $PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT" red
      exit 1
   fi
}

# If not overwite mode and nothing is newer, outa here asap. BASH is slow you know :)
if [ ! "$OVERWRITE_PKG" = "yes" ]; then
  if [ -f "$PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT" ]; then
     NEWER=`find . -newer $PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT`
     if [ -z "$NEWER" ]; then
       echoc "Package $PNAME_VER_ARCH_REL.$PEXT is up to date." blue
       if [ "$REINSTALL_PKG" = "yes" ]; then
         install_pkg -o
       else
         install_pkg -u
       fi
       exit 0
     fi
     echo "Newer files $NEWER found" 
  fi
fi

echo "Configure=$CONFIGURE"
pause "Ready to start building the package. Press Ctrl-C to abort"

###########################################################################
### Ok, need to build a new package then
### A lot of functions needed ...

# Just explode the package
function explode_tgz() {
  echoc "Exploding package $PNAME_VER ..." blue
  cd $DEST_DIR/$PNAME_VER
  explodepkg $CWD/$TGZBALL
}

# Extract tarball from $CWD to $MAKE_DIR
function extract_tarball() {
  cd $MAKE_DIR
  echoc "Extracting tarbal $TARBALL ..." blue
  if [ "CLEAN_SRC" = "yes" ]; then
     echo "Cleaning source"
     rm -rf $TNAME_VER
  fi
  if [ $CWD/$TARBALL -nt $TNAME_VER ]; then
    if [ -f $CWD/$TNAME_VER.tar.bz2 ]; then
      tar -xjf $CWD/$TNAME_VER.tar.bz2
    elif [ -f $CWD/$TNAME_VER.tar.gz ]; then
      tar -xzf $CWD/$TNAME_VER.tar.gz
    fi
    if [ ! $? = 0 ]; then
      echoc "ERROR: Cannot extract the tarbal. Aborting .." red
      exit 1
    fi
    echo "Tarball $TARBALL has been extracted"
  else
    echo "Tarball $TARBALL is not extracted" 
  fi
  if [ ! -d $TNAME_VER ]; then
    echoc "ERROR: Missing the extracted source code. Aborting ..." red
    echo "Check the tarball. It should contain $TNAME_VER directory"
    echo "Also take a look for possibly garbage at $MAKE_DIR"
    exit 1 
  fi
}

function compile_src() {
  
  cd $MAKE_DIR/$TNAME_VER

  if [ -x $CWD/compile.sh ]; then
    echoc "Compiling with custom compilation script ... " blue
    DESTDIR=$DEST_DIR/$PNAME_VER
    source $CWD/compile.sh $PREFIX $DESTDIR
    if [ ! $? = 0 ]; then
       echoc "ERROR: Compile $PNAME failed, aborting ..." red
       echo "PWD=`pwd`"
       echo "Command: compile.sh $PREFIX $DESTDIR"
       cat $CWD/compile.sh
       exit 1;
    fi
  elif [ -x ./configure ]; then
    echoc "Compiling with standard automake procedure ..." blue
    ./configure $CONFIGURE 
    if [ ! $? = 0 ]; then
      echoc "ERROR: Configure $PNAME failed, aborting ..." red
      echo "PWD = `pwd`"
      echo "CONFIGURE = $CONFIGURE"
      exit 1;
    fi
    echoc "Compiling ... " blue
    make 
    if [ ! $? = 0 ]; then
       echoc "ERROR: Make $PNAME failed, aborting ..." red
       echo "PWD=`pwd`"
       echo "CONFIGURE = $CONFIGURE"
       exit 1;
    fi
  else
    echoc "Compiling with bare make ..." blue
    make 
    if [ ! $? = 0 ]; then
      echoc "ERROR: Make $PNAME failed, aborting ..." red
      echo "PWD=`pwd`"
      exit 1;
    fi
  fi
}

## Install using checkinstall
function checkinstall_pkg() {
  cd $MAKE_DIR/$TNAME_VER
  cp $CWD/description-pak .
  if [ -x $CWD/install.sh ]; then
    echoc "Check-installing with custom install script ... " blue

    #DESTDIR=$DEST_DIR/$PNAME_VER
    #echo $DESTDIR
    #source $CWD/install.sh
    
    export PREFIX=$PREFIX
    export DESTDIR=$DESTDIR
    
    cp $CWD/install.sh .
    checkinstall -y --newslack \
      --pkgname=$PNAME \
      --pkgversion=$PVERSION \
      --pkgarch=$PARCH \
      --pkgrelease=$PRELEASE  \
      --nodoc ./install.sh
  else
    echoc "Check-installing with standard make install ... " blue
    checkinstall -y --newslack \
      --pkgname=$PNAME \
      --pkgversion=$PVERSION \
      --pkgarch=$PARCH \
      --pkgrelease=$PRELEASE \
      --nodoc
  fi
  if [ ! $? = 0 ]; then
     echoc "ERROR: Checkinstall $PNAME failed, aborting ..." red
     exit 1;
  fi
  echoc "Exploding package $PNAME_VER ..." blue
  mkdir $DEST_DIR/$PNAME_VER
  cd $DEST_DIR/$PNAME_VER
  explodepkg $MAKE_DIR/$TNAME_VER/$PNAME_VER_ARCH_REL.tgz
}

function install_src()
{
    cd $MAKE_DIR/$TNAME_VER

    # use checkinstall if asked
    if [ "$CHECKINSTALL_PKG" = "yes" ]; then
	checkinstall_pkg
        return $?
    fi
    
    # create standard directories, since some packages do not create them
    export DESTDIR=$DEST_DIR/$PNAME_VER

    mkdir -p $DESTDIR/usr/lib
    mkdir -p $DESTDIR/usr/doc
    mkdir -p $DESTDIR/usr/man/man1
    mkdir -p $DESTDIR/usr/lib
    mkdir -p ${DESTDIR}${PREFIX}/bin
    mkdir -p ${DESTDIR}${PREFIX}/sbin
    mkdir -p ${DESTDIR}${PREFIX}/lib
    mkdir -p ${DESTDIR}${PREFIX}/etc
    mkdir -p ${DESTDIR}${PREFIX}/share
    mkdir -p ${DESTDIR}${PREFIX}/man/man1
    	
    if [ -x $CWD/install.sh ]; then
	echoc "Installing with custom install script ... " blue
	cp $CWD/install.sh .
	./install.sh
    elif grep -q "DESTDIR" Makefile; then
	echoc "Installing with DESTDIR=$DESTDIR ... " blue
	# This is cheating, sometimes direct install first give the better result :)
	if [ "$INSTALL_PKG" = "yes" ] && [ "$INSTALL_HOST" = "yes" ]; then
	    make install
	fi
    	make install DESTDIR=$DESTDIR
    else
	echoc "Sorry, this package does not know DESTDIR method" red
	echo "You must provide custom install.sh, probably with"
	echo 'make prefix=${DESTDIR}${PREFIX}'
    	exit 1
    fi
    if [ $? != 0 ]; then
       echoc "ERROR: Install $PNAME failed, aborting ..." red
       exit 1
    fi

    # remove the empty directories
    rmdir $DESTDIR/usr/lib 2>/dev/null
    rmdir $DESTDIR/usr/doc 2>/dev/null
    rmdir $DESTDIR/usr/lib 2>/dev/null
    rmdir -p $DESTDIR/usr/man/man1 2>/dev/null
    rmdir ${DESTDIR}${PREFIX}/bin 2>/dev/null
    rmdir ${DESTDIR}${PREFIX}/sbin 2>/dev/null
    rmdir ${DESTDIR}${PREFIX}/etc 2>/dev/null
    rmdir ${DESTDIR}${PREFIX}/lib 2>/dev/null
    rmdir ${DESTDIR}${PREFIX}/share 2>/dev/null
    rmdir -p ${DESTDIR}${PREFIX}/man/man1 2>/dev/null
}

# Add documentations from the tarball
function add_docs() {
    echoc "Adding documentations ..." blue
  
    mkdir -p ${DESTDIR}${PREFIX}/doc/$PNAME_VER
    cd ${DESTDIR}${PREFIX}/doc/$PNAME_VER

    if [ -d "$CWD/doc" ]; then
        echo "Add predefined doc"
        cp -a $CWD/doc/* .
    else
	echo -n "Original doc: "
	for f in AUTHORS COPYING* COPYRIGHT* LICENSE *FAQ* README* ; do
    	    if [ -f "$MAKE_DIR/$PNAME_VER/$f" ]; then
    		echo -n "$f "
    	        cp $MAKE_DIR/$PNAME_VER/$f .
            fi
    	    if [ -f "$MAKE_DIR/$PNAME_VER/doc/$f" ]; then
    		echo -n "$f "
    	        cp $MAKE_DIR/$PNAME_VER/doc/$f .
            fi
	done
	echo
	#if [ -d "$MAKE_DIR/$PNAME_VER/doc" ]; then
    	#    echo "Add additional doc"
    	#    cp -a $MAKE_DIR/$PNAME_VER/doc/* .
	#fi
    fi
    # fix permission
    chmod -R 644 *
    chown -R root.users *
}

# add custom directory, custom.tar.gz or custom.tar.bz2
function add_custom() {
  echo
  echoc "Adding customization to $DEST_DIR/$PNAME_VER ..." blue

  cd $DEST_DIR/$PNAME_VER
  if [ -f $CWD/custom.tar.gz ]; then
     echo "Adding custom.tar.gz"
     tar -xzvf $CWD/custom.tar.gz
  fi
  if [ -f $CWD/custom.tar.bz2 ]; then
     echo "Adding custom.tar.bz2"
     tar -xjvf $CWD/custom.tar.bz2
  fi
  if [ -d $CWD/custom ]; then
     echo "Adding custom directory"
     cp -a $CWD/custom/* .
  fi
  
  mkdir -p .$PREFIX
  cd .$PREFIX
  if [ -f $CWD/custom-prefix.tar.gz ]; then
     echo "Adding custom-prefix.tar.gz"
     tar -xzf $CWD/custom-prefix.tar.gz
  fi
  if [ -f $CWD/custom-prefix.tar.bz2 ]; then
     echo "Adding custom-prefix.tar.bz2"
     tar -xjf $CWD/custom-prefix.tar.bz2
  fi
  if [ -d $CWD/custom-prefix ]; then
     echo "Adding custom-prefix directory"
     cp -a $CWD/custom-prefix/* .
  fi
}

# add slackware's description
# 80% of this code was taken from checkinstall
function add_desc() {

  echoc "Creating description to $DEST_DIR/$PNAME_VER ..." blue
  cd $DEST_DIR/$PNAME_VER
  mkdir -p install
  TXTNAME="install/slack-desc"
  cat << EOF > $TXTNAME
# HOW TO EDIT THIS FILE:
# The "handy ruler" below makes it easier to edit a package description.  
# Line up the first '|' above the ':' following the base package name, and 
# the '|' on the right side marks the last column you can put a character in. 
# You must make exactly 11 lines for the formatting to be correct.  
# It's also customary to leave one space after the ':'.

EOF

  # Calculate the spaces before the "handy-ruler"
  HR_SPACES=`echo $PNAME | wc -c| awk '{ for (i=1;substr ($0,i,1) ~ /[[:blank:]]/ ;i++); print substr ($0,i);}'`
  awk -v S=$HR_SPACES 'BEGIN {ORS=""; for (i=1; i < S; i++) print " ";}' >> $TXTNAME
  echo "|-----handy-ruler------------------------------------------------------|" >> $TXTNAME

  # add the contents
  if [ -f $CWD/description-pak ]; then
    echo Adding description-pak ...
    cat $CWD/description-pak | while read line; do
      echo "$PNAME: $line" >> $TXTNAME
    done
  else
    echo Adding default description ...
    echo "$PNAME: $PNAME package" >> $TXTNAME
  fi
  ## Add other information
  echo "" >> $TXTNAME
  echo "-------------------------------------" >> $TXTNAME
  echo "BUILDDATE: " `date` >> $TXTNAME
  echo "HOST     : " `uname -mrs` >> $TXTNAME
  echo "DISTRO   : " `distrorelease` >> $TXTNAME
  echo "CFLAGS   : $CFLAGS" >> $TXTNAME 
  for op in $CONFIGURE ; do
     echo "CONFIGURE: $op" >> $TXTNAME
  done
  echo >> $TXTNAME

  # copy changelog
  #if [ -f $CWD/changelog-pak ]; then 
  #    cp -a $CWD/changelog-pak install/changelog
  #fi

}

# Create symlink for doinst.sh
# it was from makepkg, but I changed a lot since coreutil 5.0
function add_doinstall () {
  cd $DEST_DIR/$PNAME_VER
  mkdir -p install
  echoc "Creating do install ..." blue
  
  if [ ! -f install/doinst.sh ]; then
    echo "#!/bin/sh" > install/doinst.sh
  fi
  echo "# doinstall added by install-tarball $VERSION" >> install/doinst.sh
  echo "PREFIX=$PREFIX" >> install/doinst.sh

  # find if we have object file
  echo "Adding ldconfig path ..."
  find . -name '*.so' -print | while read LINE; do
      DIRNAME="`dirname $LINE`"
      DIRNAME=`echo $DIRNAME | sed -e 's!^.!!'`
      if ! echo $LDPATH | grep -w $DIRNAME; then
	 echo "if ! grep -qx $DIRNAME ./etc/ld.so.conf; then echo $DIRNAME >> ./etc/ld.so.conf; fi" >> install/doinst.sh
	 LDPATH="$LDPATH $DIRNAME"
      fi
  done

  # make symlinks creation
  echo "Adding symlinks creation into script ..."
  find . -type l -print | while read LINE; do
      DIRNAME="`dirname $LINE`" 
      LINKNAME="`basename $LINE`"
      LINKTO="`readlink $LINE`"
      echo "( cd $DIRNAME ; rm -rf $LINKNAME; ln -sf $LINKTO $LINKNAME )" >> install/doinst.sh
      rm -f $LINE
  done

  ## add ldconfig if we have shared object
  if [ "$LDPATH" ]; then
    echo "ldconfig" >> install/doinst.sh
  fi
  
  # Add predefined doinst.sh
  if [ -f $CWD/install-pak ]; then
    echo Adding install-pak
    cat $CWD/install-pak >> install/doinst.sh
  fi
  echo ----------------
  cat install/doinst.sh
  
  pause  
}

find_dependency()
{
    for DDNAME in $*; do
	for DD in /var/log/packages/$DDNAME-*; do
	    DDBASE=`basename $DD`
	    if [ "$DDNAME" = "`pkgname $DDBASE`" ]; then
		if ! grep -qx "$DDBASE" install/dependency; then
	    	    echo $DDBASE >> install/dependency
	    	    echo "$DDBASE"
        	fi
	    fi
	done
    done
}

# The ldd idea is from swaret
function add_dependency()
{
  cd $DEST_DIR/$PNAME_VER
  mkdir -p install
  echoc "Creating dependency ..." blue
  echo "# dependency list added by install-tarball $VERSION" > install/dependency
  if [ -f "$CWD/dependency-pak" ]; then
    grep -ve "^#" $CWD/dependency-pak | while read LINE; do
	DNAME=`pkgname $LINE`
	if [ "$DNAME" = "$LINE" ]; then
	    find_dependency $DNAME
	else
	    echo $LINE	>> install/dependency
	fi
    done
  fi

  # find the executables and track the required packages
  find . -perm +1 -print | while read LINE; do
     [ ! -f $LINE ] && continue
     echo "$LINE:"
     if ! ldd $LINE &>/dev/null; then
        # not a dynamic, possibly script
	FTYPE=`file $LINE`
	if echo $FTYPE | grep -q "Bourne shell" ; then
	    find_dependency bash
	elif echo $FTYPE | grep -q "C shell" ; then
	    find_dependency tcsh
	elif echo $FTYPE | grep -qw "perl" ; then
	    find_dependency perl
	elif echo $FTYPE | grep -qw "expect"; then
	    find_dependency expect tclx tcl
	elif echo $FTYPE | grep -qw "tcl"; then
	    find_dependency tcl
	else
	    echoc "WARNING: unknown dependency for $LINE" yellow
	fi
     else 
	ldd $LINE | while read LINE1; do
    	    LIB=`echo $LINE1 | cut -f1 -d ' '`
	    SELF=$(find -name `basename $LIB`)
	    if [ "$SELF" ]; then
		continue
	    fi
	    grep $LIB /var/log/packages/* | while read LINE2; do
		DNAME=`echo $LINE2 | cut -f1 -d:`
		DBASE=`basename $DNAME`
		case "`pkgname $DBASE`" in
		    aaa_elflibs|$PNAME)
		    continue
		    ;;
		esac
		if ! grep -qx "$DBASE" install/dependency; then
	    	    echo $DBASE >> install/dependency
	    	    echo "$DBASE"
        	fi
	    done
	    if [ $? != 0 ]; then
		echoc "WARNING : Missing dependency" red
		echoc "WARNING : Cannot find the package of $LIB" red
	    fi
	done
     fi
  done
}

# Create the slackware package
# 90% taken from makepkg

function make_pkg () {

  cd $DEST_DIR/$PNAME_VER
  echoc "Creating the package at `pwd` ..." blue
#  pause 
   
  # Strip the ELFs
  echo "Stripping ELF files"
  ( find . | xargs file | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded &> /dev/null )

  # fixing permission
  #echo Fixing permission
  #$CHOWN -R root.root .
  #if [ -d .$PREFIX/bin ]; then 
  #    $CHOWN -R root.bin .$PREFIX/bin
  #fi
  #if [ -d .$PREFIX/sbin ]; then
  #   $CHOWN -R root.bin .$PREFIX/sbin
  #fi
  # find . -type d -exec $CHMOD 755 {} \;
  # find . -type d -exec $CHOWN -v root.root {} \;
 
  # Warn of zero-length files:
  find . -type f -size 0c | while read file ; do
     echo "WARNING: zero length file $file"
  done
  find . -type f -name '*.gz' -size 20c | while read file ; do
     echo "WARNING: possible empty gzipped file $file"
  done
  
  echo "Packing and compressing ..."

  case $PEXT in
    tbz|tbz2|bz2)
	tar -cjf $PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT .
	;;
    *)
	tar -czf $PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT .
	;;
  esac

  if [ ! -f "$PKG_DIR/$PNAME_VER_ARCH_REL.$PEXT" ]; then
    echo "ERROR: Could not build $PNAME_VER_ARCH_REL.$PEXT. Aborting ..."
    exit 1 
  fi 
  echoc "Package $PNAME_VER_ARCH_REL.$PEXT has been built" green
}

function make_md5() {
  cd $PKG_DIR
  md5sum $PNAME_VER_ARCH_REL.$PEXT > $PNAME_VER_ARCH_REL.$PEXT.md5
  echoc "Checksum $PNAME_VER_ARCH_REL.$PEXT.md5 has been created" green
}

# Create Text description
function make_txt() {

  cd $PKG_DIR
  TXTNAME="$PNAME_VER_ARCH_REL.txt"

  ## Add description
  echo -n > $TXTNAME
  if [ -f "$CWD/description-pak" ]; then
    cat $CWD/description-pak | while read line; do 
       echo $PNAME: $line >> $TXTNAME
    done
  else
    echo "WARNING: description-pak is not exist"
    echo "$PNAME: $PNAME" >> $TXTNAME
  fi
     
  ## Add other information
  echo "" >> $TXTNAME
  echo "-------------------------------------" >> $TXTNAME
  echo "BUILDDATE:" `date` >> $TXTNAME
  echo "HOST     :" `uname -mrs` >> $TXTNAME
  echo "DISTRO   :" `distrorelease` >> $TXTNAME
  echo "CFLAGS   : $CFLAGS" >> $TXTNAME 

  for op in $CONFIGURE ; do
     echo "CONFIGURE: $op" >> $TXTNAME
  done

  ## Add dependency
  if [ -f $DEST_DIR/$PNAME_VER/install/dependency ]; then
    grep -ve "^#" $DEST_DIR/$PNAME_VER/install/dependency | while read line; do 
       echo "DEPENDENCY: $line" >> $TXTNAME
    done
  else
    echo "WARNING: $DEST_DIR/$PNAME_VER/install/dependency is not exist"
  fi

  echoc "Description $TXTNAME has been created" green
}

################################################################################
# Main 

## Prepare the directories
mkdir -p $MAKE_DIR
mkdir -p $PKG_DIR
mkdir -p $DEST_DIR

if [ -d "$DEST_DIR/$PNAME_VER" ]; then
   rm -rf $IMG/$PNAME_VER
fi
mkdir -p $DEST_DIR/$PNAME_VER

# explode the tgz first
if [ "$TGZBALL" ]; then
  explode_tgz
fi

# Compile the tarball
if [ "$TARBALL" ]; then
  extract_tarball
  compile_src
  install_src
fi
# Add custom and other script
add_custom
add_doinstall
add_desc
add_dependency
add_docs

# wrap it
make_pkg
make_md5
make_txt
echo "You may find them at directory $PKG_DIR"

# Delete temporary image
# echo Cleaning temporary files ...
cd $CWD
rm -rf $DEST_DIR/$PNAME_VER

# Clean the source
if [ "$DELETE_SRC" = "yes" ]; then
    #echo Cleaning the source ...
    rm -rf $MAKE_DIR/$PNAME_VER
fi

# Update the RELEASE on settings.sh
if [ "$UPDATE_RELEASE" = "yes" ]; then
    cd $CWD
    let NRELEASE=$PRELEASE+1
    grep -e "^PRELEASE=.*" settings.sh &> /dev/null
    if [ $? = 0 ]; then
	cat settings.sh | sed "s!PRELEASE=.*!PRELEASE=$NRELEASE!" > settings.sh 
    else
	echo "PRELEASE=$NRELEASE" >> settings.sh
    fi
    unset NRELEASE
fi

echo
install_pkg -o
