#! /bin/bash1
#############################################################################   
# Copyright (C) 1998, 1999, M. Gerrits (etmmger@etm.ericsson.se)                
# Copyright (C) 1999, A. Verhoeven (pe1icq@amsat.org)                           
#                                                                               
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.   
#############################################################################   
#
# This SlackBuild script is derived from Marcel Gerrits' mger-pkgtools-2.3a
# mger-pkgtools can be found in ftp://sharon.esrac.ele.tue.nl/pub/linux/slackware/
#
# script version 1.1
#
# ChangeLog:
# 1.0:	Derived from mger-pkgtools-2.3a
# 1.1:  Added GPL, and minor cosmetic updates after deskcheck MGER.

# Files:
#   Package			Package File
#   PackageFiles		List of files in the package
#   SymbolicLinks		List of symbolic links in the system
#   SystemList.After		System list after program installation
#   SystemList.Before		System list before program installation
#   SystemList.Diff		Differences between system lists
#   make.log			Logging of stdout/stderr of make install
#   reply			Result of various checks

# Set initial variables:
if [ "$TMP" = "" ]; then
  TMP=/tmp
fi

TarBall=z8530drv-utils_3.0-2.tar.gz	# Change as needed
PackageName=z8530drv-utils-3.0		# Change as needed

BuildDir=$TMP/$PackageName
SourceDir=`pwd`
KeepTmpFiles=0
SkipScan=0
SearchPath="/bin /etc /install /lib /sbin /usr /var"
#SearchPath="/bin /boot /dev /etc /lib /opt /sbin /usr /var"
#SearchPath="/tmp/try"



TempDir=/tmp/SlackBuild.$$


if [ $# -gt 0 ]
 then
  case $1 in
   --help) echo "Syntax: `basename $0` [<options>] [retry_PID]"
           echo "Options: --keep     keep temp files in /tmp/SlackBuild.<pid>"
 	  echo "if retry_PID is specified, SlackBuild will try to use the"
 	  echo "data in /tmp/SlackBuild.<retry_PID> instead of scanning the"
 	  echo "system again."
	  echo "If ./doinst.sh exists, it will be run as default installation"
	  echo "script. If you don't want to use that script, rename it first."
	  exit 0;;
   --keep) KeepTmpFiles=1;;
   *) if [ ! -d /tmp/SlackBuild.$1 ]
      then
        echo "Cannot find directory /tmp/SlackBuild.$1"
	exit 1
     fi
     TempDir=/tmp/SlackBuild.$1
     SkipScan=1
 esac
fi

##########################################################################
# Cleanup()
# Clean up all temporary filed (if cmd-line option --keep not specified)
##########################################################################
Cleanup(){
 if [ ! ${KeepTmpFiles} -eq 1 ]
  then
   rm -rf ${TempDir}
   rm -rf ${BuildDir}
   removepkg $PackageName
  else
   echo "Leaving temporary files in ${TempDir}"
   echo "Leaving source tree in ${BuildDir}"
 fi
}

trap Cleanup 0 1 2 3		# Cleanup on exit of program automatically
# Cleanup				# Cleanup before we start
mkdir -p ${TempDir}
mkdir -p ${BuildDir}

##########################################################################
# Exit()
# Exit program with code $2, cleanup temporary files, print message $1
##########################################################################
Exit(){
 clear					# Clear screen
 Cleanup				# Cleanup temp files
 echo -e "$1"				# Print message on screen
 exit $2				# Exit program
}


##########################################################################
# FindChanges()
# Finding changes...
# Find differences between the list files, sort on filename
# > = added files,
# < = removed files,
# if a file is listed twice, once with > and once with <, then it is changed
# Sort differences on filename
##########################################################################
FindChanges(){
 echo "Analyzing file lists..." 
 diff ${TempDir}/SystemList.Before ${TempDir}/SystemList.After | egrep "^(>|<)" | sort +5 -o ${TempDir}/tmp

 gawk 'BEGIN{
 	LState = LFile = LLine = "";
       	}
 	# Line = (>|<) CD CT TD TT mode size name
	#         $1   $2 $3 $4 $5 $6   $7   $8
	function ShowFile()
	{
	  if (LState != "")
	    if (LState == "<") printf("Deleted: %s\n", LLine);
	    else               printf("Added: %s\n", LLine);
	}

	{
	  State = $1;					# State is < or >
	  File = $8;					# File = filename
	  Line = $8 " " $2 " " $3 " " $4 " " $5 " " $6 " " $7;
	  if (File == LFile)
	  {
	    printf("Changed: %s\n", Line);
	    LFile = LState = LLine = "";
	  }
	  else
	  {
	    ShowFile();
	    LFile = File;
	    LState = State;
	    LLine = Line;
	  }
	}
	END { ShowFile(); }
 ' ${TempDir}/tmp > ${TempDir}/SystemList.Diff
}



##########################################################################
# PackageIt()
# Ask for Package Name and Package Description, Verify package,...
##########################################################################
PackageIt(){
 echo ${PackageName}$1 > ${TempDir}/PackageName
 PackageDescription="Package ${PackageName}$1 (`date '+%Y,%b %d'`)"

	# Create package header in ${TempDir}/Package
	echo "" | gawk -v PKGName="${PackageName}$1" -v PKGDesc="${PackageDescription}" -v PKGDate="`date '+%Y, %b %d'`" '
	BEGIN {
	  printf("PACKAGE NAME: %s\n", PKGName);
	  printf("COMPRESSED PACKAGE SIZE: 0 K\n");
	  printf("UNCOMPRESSED PACKAGE SIZE: 0 K\n");
	  printf("PACKAGE LOCATION: source\n");
	  printf("PACKAGE DESCRIPTION:\n");
	  printf("%-9.9s %s\n", PKGName ":", PKGDesc);
	  printf("%-9.9s\n", PKGName ":");
	  printf("%-9.9s Package created %s with makeinstall\n", PKGName ":", PKGDate);
	  printf("%-9.9s makeinstall created by M. Gerrits (etmmger@etm.ericsson.se)\n", PKGName ":")
	  printf("FILE LIST:\n");
	}
	{
	}
	' > ${TempDir}/Package

	# Create list of added/changed files to package file list
	egrep "^(Added|Changed) *: " ${TempDir}/SystemList.Diff | cut -f2 -d' ' | sort > ${TempDir}/PackageFiles

	# Check if symbolic links point to files in the package
	echo "Checking symbolic links..." 

	# Create List of symbolic links
	gawk -v ReplyFile="${TempDir}/reply" 'BEGIN { LinkNr=0; }

		function CheckLink(LinkName) {
			Scanned="";
			while ( Link[LinkName] in Link)
			{
		 	   if (match(Scanned, " " LinkName)) return "Cyclic";
			   Scanned=Scanned " " LinkName;
			   LinkName=Link[LinkName];
			}
			return Link[LinkName];
		}


		{
			if ($8 != "")
			{	# This is a relative symlink
				if (substr($8,1,1)!="/")
				{
					LinkName=$7
					gsub("/[^/]*$","", LinkName);
					$8=LinkName "/" $8
					while (gsub("/[^/]*/\\.\\.","",$8));
					while (gsub("/\\./","/",$8));
					# $8 = full path of symlink
				}
				Link[$7] = $8;
				LinkNr++;
			}
		}

		END {
		  Depth=0;
		  for (i in Link)
		      printf("%s %s\n", i, CheckLink(i));
		  printf("%d", LinkNr) > ReplyFile;
	}' ${TempDir}/SystemList.After > ${TempDir}/SymbolicLinks
	NumLinks="`cat ${TempDir}/reply`"
	echo "Checking symbolic links... (${NumLinks} found)"
	
	# Check which symlinks point to files in the package
	gawk 'BEGIN { }
		{
		   if (match(FILENAME, "SymbolicLinks")) { Link[$1] = $2; next; }
		   for (i in Link)
		     if (Link[i] == $1) printf("%s\n", i);
		}
		END { }
	' ${TempDir}/SymbolicLinks ${TempDir}/PackageFiles >> ${TempDir}/Package

	# Merge filelist and package header
	egrep -v "/var/(log|run|spool/mail/)" ${TempDir}/PackageFiles >> ${TempDir}/Package

	echo "Edit this package list"
	    if [ "${DISPLAY}" = "" ]
	      then
	        vim -f ${TempDir}/Package
	      else
	        gvim -f ${TempDir}/Package
	    fi
	
	echo "Installing this package list"
	if [ ! `whoami` = root ]
	  then
	    cp ${TempDir}/Package ${HOME}/${PackageName}$1.package
	    echo -e "You (`whoami`) must be root to install the\npackage list in /var/adm/packages.\nCopy left in \$HOME/${PackageName}$1.package"
	    Exit "Not root" 1
	fi

	cp ${TempDir}/Package /var/adm/packages/${PackageName}$1
	echo "Package list ${PackageName}$1 installed in /var/adm/packages/${PackageName}$1"


 ##########################################################################
 # strip files and create .tgz file
 ##########################################################################
 cd $SourceDir
 ./strippkg ${PackageName}$1
 ./pkg2tgz ${PackageName}$1
}



##########################################################################
# Untar source and make program
##########################################################################
cd $BuildDir
tar zxvf $SourceDir/$TarBall
cd $PackageName
echo "############## make ###################"  
make dep ; make

touch /etc/ax25/z8530drv.conf # make sure that this file exists, otherwise
                         # 'make install' will won't create z8530drv.conf.ex
			 

if [ ${SkipScan} -eq 0 ]
 then

##########################################################################
# Making list of files on system (before install)...
# Store last status date&time, last modification date&time, mode, size, name
##########################################################################
echo "Creating system file list (1)..."
find ${SearchPath} -fprintf ${TempDir}/tmp "%CD %CT %TD %TT %04m %10s %p %l\n" 2>/dev/null
sort +6 ${TempDir}/tmp -o ${TempDir}/SystemList.Before

##########################################################################
# Install the program
##########################################################################
echo "############## make install ###################" 
make install
mkdir -p /usr/doc/$PackageName
cp doc/* /usr/doc/$PackageName
mkdir /install
cat << EOF >> /install/doinst.sh 
if [ ! -f /etc/ax25/z8530drv.conf ]
  then
    cp /etc/ax25/z8530drv.conf.ex /etc/ax25/z8530drv.conf
fi

EOF

##########################################################################
# Making list of files on system (after install)...
##########################################################################
echo "Creating system file list (2)..."
find ${SearchPath} -fprintf ${TempDir}/tmp "%CD %CT %TD %TT %04m %10s %p %l\n"  2>/dev/null
sort +6 ${TempDir}/tmp -o ${TempDir}/SystemList.After


fi	# End of skip scanning...

FindChanges

PackageIt

Exit done 0
