#!/bin/bash
#
# --- ROCK-COPYRIGHT-NOTE-BEGIN ---
# 
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
# Please add additional copyright information _after_ the line containing
# the ROCK-COPYRIGHT-NOTE-END tag. Otherwise it might get removed by
# the ./scripts/Create-CopyPatch script. Do not edit this copyright text!
# 
# ROCK Linux: rock-src/scripts/Build-Pkg
# ROCK Linux is Copyright (C) 1998 - 2003 Clifford Wolf
# 
# 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. A copy of the GNU General Public
# License can be found at Documentation/COPYING.
# 
# Many people helped and are helping developing ROCK Linux. Please
# have a look at http://www.rocklinux.org/ and the Documentation/TEAM
# file for details.
# 
# --- ROCK-COPYRIGHT-NOTE-END ---

exec 2>&1

buildstart="`date "+%m/%d/%Y from %T"`"

options=''
config=default

clear_src=1
norebuild=0
update=0

make_tar=''
prefix="usr"
prefix_auto=1
pkgdir=""
verbose=0
xtrace=0
debug=0
chroot=0
root=""
id=''

stagelevel=9
this_is_the_2nd_run=0

#
# ----  Functions
#


help_msg() {
	spacer="                          "
	echo
	echo "Usage: ./scripts/Build-Pkg" \
	             "[ -0 | -1 | -2  ... | -8 | -9 ]           \\"
	echo "$spacer [ -v ]  [ -xtrace ]  [ -chroot ]          \\"
	echo "$spacer [ -root { <rootdir> | auto } ]            \\"
	echo "$spacer [ -cfg <config> ]  [ -update ]            \\"
	echo "$spacer [ -prefix <prefix-dir> ]  [ -norebuild ]  \\"
	echo "$spacer [ -noclearsrc ]  [ -pkgdir <pkgdir> ]     \\"
	echo "$spacer [ -id <id> ]  [ -debug ]  pkg-name(s)"
	echo
	echo "Type './scripts/Help Build-Pkg' for details."
	echo
}


#
# ---- Parse options + config and make Build-Pkg sub-calls
#

while [ "$1" ] ; do
	case "$1" in
		-this_is_the_2nd_run) this_is_the_2nd_run=1 ;;
		-[0-9])   options="$options $1"    ; stagelevel=${1#-} ;;
		-v)       options="$options $1"    ; verbose=1     ;;
		-xtrace)  options="$options $1"    ; xtrace=1      ;;
		-debug)   options="$options $1"    ; debug=1 ; clear_src=0 ;;
		-update)  options="$options $1"    ; update=1      ;;
		-chroot)  options="$options $1"    ; chroot=1      ;;
		-chr-sub) options="$options $1"    ; chroot=0      ;;
		-cfg)     options="$options $1 $2" ; config="$2"   ; shift ;;
		-root)    options="$options $1 $2" ; root="$2"     ; shift ;;
		-prefix)  options="$options $1 $2" ;
				prefix_auto=0      ; prefix="$2"   ; shift ;;
		-id)      options="$options $1 $2" ; id="$2"       ; shift ;;
		-pkgdir)  options="$options $1 $2" ; pkgdir="$2"   ; shift ;;
		-noclearsrc) options="$options $1" ; clear_src=0   ;;
		-norebuild)  options="$options $1" ; norebuild=1   ;;
		-*) help_msg ; exit 1 ;;
		*)  break ;;
	esac
	shift
done

# check if arguments are left as package names
if [ $# = 0 ] ; then 
	help_msg ; exit 1
fi

. ./scripts/functions
. ./scripts/parse-config

if [ -z "$root" -a $stagelevel -le 1 ] || \
   [ -z "$root" -a $chroot -eq 1 ] || \
   [ "$root" = auto ]; then
		if [ $stagelevel -gt 0 ]; then root="build/$ROCKCFG_ID/root"
		else root="build/$ROCKCFG_ID/$toolsdir"; fi
fi

[ "$pkgdir" -a "${pkgdir#/}" = "$pkgdir" ] && pkgdir="$base/$pkgdir"
[ "$root" -a "${root#/}" = "$root" ] && root="$base/$root"
prefix=${prefix%/} ; prefix=${prefix#/} ; root=${root%/}
xroot="$root" ; [ $stagelevel -gt 1 ] && root=""

if [ -z "$id" ] ; then
	id=`get_unique`
	options="$options -id $id"
fi

./scripts/Build-Tools -$stagelevel -cfg $config || exit 1

# more than one package are passed
if [ $# -gt 1 ] ; then 
    for x ; do
	if ! ./scripts/Build-Pkg $options $x && \
	   [ "$ROCKCFG_ABORT_ON_ERROR" = 1 ] ; then
		exit 1
	fi
    done
    exit 0
fi
pkg="${1%=*}" ; xpkg="${1#*=}"
builddir="$base/src.$pkg.$id"

if [ "$chroot" = 1 ] ; then

	mkdir -p $builddir
	cd $builddir || exit 1

	mkdir -p R.orig R.build R.work R.src
	ln -s ../R.src   R.work/src.$pkg.$id
	ln -s ../R.build R.work/build

	mkdir -p dev proc tmp mnt
	[ -f proc/mounts ] || mount -t proc  none $builddir/proc
	mknod $builddir/dev/null c 1 3
	mknod $builddir/dev/zero c 1 5
	mknod $builddir/dev/random c 1 8
	mknod $builddir/dev/uramdom c 1 9
	# mknod $builddir/dev/tty c 5 0
	ln -s /proc/self/fd $builddir/dev/fd

	realbase=$(dirname $(cd $base/scripts ; pwd -P))
	mount --bind $realbase  $builddir/R.orig
	
	# handle mounted download dirs
	if [ -L $realbase/download ]; then
		abort "download dir can't be a symlink, use mount instead."
	fi
	mount --bind $realbase/download $builddir/R.orig/download

	realbuild=$(cd $base/build ; pwd -P)
	mount --bind $realbuild $builddir/R.build
	ln -sf R.build/$ROCKCFG_ID/root/* . 2> /dev/null

	cat > R_chroot.sh <<- EOT
		cd /R.orig ; ./scripts/Create-Links /R.work > /dev/null
		cd /R.work ; ./scripts/Build-Pkg $options -chr-sub -root "/R.build/$ROCKCFG_ID/root" "$1"
	EOT

	cat <<- EOT > $builddir/R_mount.sh
		mount -t proc  none $builddir/proc
		mount --bind $realbase $builddir/R.orig
		mount --bind $realbase/download $builddir/R.orig/download
		mount --bind $realbuild $builddir/R.build
	EOT
	cat <<- EOT > $builddir/R_umount.sh
		umount dev proc R.orig/download R.orig R.build
	EOT
	cat <<- 'EOT' > $builddir/debug.sh
		sh R_mount.sh
		chroot . bin/bash -c 'cd R.src ; exec ./debug.sh'
		[ -z "`fuser R.src/build.pid`" ] && sh R_umount.sh
	EOT
	chmod +x $builddir/debug.sh

	mkdir -p R.work/config/
	cp -rp $base/config/$config R.work/config/

	if [ "$TZ" ] ; then
		if [ "${TZ#/}" != "$TZ" ] ; then
			cp $TZ R.localtime
		else
			cp /usr/share/zoneinfo/$TZ R.localtime
		fi
	else
		if [ -f /etc/localtime ] ; then
			cp /etc/localtime R.localtime
		else
			ln -s /usr/share/zoneinfo/Factory R.localtime
		fi
	fi

	TZ="/R.localtime" chroot . bin/bash R_chroot.sh ; returncode=$?

	{
		umount -d -f $builddir/R.orig/download
		umount -d -f $builddir/R.orig $builddir/R.build
		umount -d -f $builddir/dev $builddir/proc
		umount -l -d -f $builddir/R.orig/download
		umount -l -d -f $builddir/R.orig $builddir/R.build
		umount -l -d -f $builddir/dev $builddir/proc
	} > /dev/null 2>&1

	delbuilddir=1
	for x in R.src R.orig R.build dev proc	; do
		if [ $delbuilddir = 1 ] ; then
			rmdir $x 2>/dev/null
			[ -e "$x" ] && delbuilddir=0
		fi
	done
	cd $base

	if [ $delbuilddir = 1 ] ; then
		rm -rf $builddir/
	fi
	
	exit $returncode
fi

if [ "$ROCKCFG_FLIST" = "flwrapper" -a -z "$FLWRAPPER" ] ; then
	export FLWRAPPER_WLOG="$builddir/fl_wrapper.wlog"
	export FLWRAPPER_RLOG="$builddir/fl_wrapper.rlog"
	[ "$LD_PRELOAD" ] && LD_PRELOAD="${LD_PRELOAD}:"
	export FLWRAPPER="$base/build/$ROCKCFG_ID/$toolsdir/lib/fl_wrapper.so"
	export LD_PRELOAD="${LD_PRELOAD}$FLWRAPPER"
fi
export INSTALL_WRAPPER_LOGFILE="$builddir/install_wrapper.log"
export CMD_WRAPPER_LOGFILE="$builddir/cmd_wrapper.log"

if [ $norebuild = 1 -a -f $root/var/adm/logs/$stagelevel-$xpkg.log ] ; then
	echo_pkg_deny $stagelevel $pkg "already built"
	exit 0
fi

if [ "$ROCKCFG_RETRY_BROKEN" = 0 -a $norebuild = 1 -a \
     -f $root/var/adm/logs/$stagelevel-$xpkg.err ] ; then
	echo_pkg_deny $stagelevel $pkg "already failed"
	exit 1
fi

confdir="" ; archdir=""

if [ -z "$pkgdir" ] ; then
  for x in package/* ; do
    x=${x#package/}
    if [ -f "package/$x/$pkg/$pkg.desc" ] ; then
	if [ "$confdir" ] ; then
	    echo_pkg_deny $stagelevel $pkg "in multiple trees"
	    echo "Package in multiple trees: $pkg !" \
		> $root/var/adm/logs/$stagelevel-$xpkg.err
	    exit 1
	fi
	confdir="$base/package/$x/$pkg"
	archdir="$base/download/$x/$pkg"
	repository=$x
    fi
  done
else
  if [ -f "$pkgdir/$pkg.desc" ] ; then
	confdir="$pkgdir"
	archdir="$pkgdir"
	repository=extern
  fi
fi

if [ -z "$confdir" ] ; then
	echo_pkg_deny $stagelevel $pkg "does not exist" ; exit 1
fi

mkdir -p $root/var/adm/logs
mkdir -p $root/var/adm/flists
mkdir -p $root/var/adm/cksums
mkdir -p $root/var/adm/md5sums
mkdir -p $root/var/adm/packages
mkdir -p $root/var/adm/dependencies
mkdir -p $root/var/adm/dep-debug
mkdir -p $root/var/adm/parse-config
mkdir -p $root/var/adm/cache
mkdir -p $root/var/adm/descs
[ "$root" ] && chmod 700 $root

rm -f $root/var/adm/logs/$stagelevel-$xpkg.out
rm -f $root/var/adm/logs/$stagelevel-$xpkg.log
rm -f $root/var/adm/logs/$stagelevel-$xpkg.err

if [ $this_is_the_2nd_run = 0 ] ; then
	[ $stagelevel -gt 1 ] && . /etc/profile
	options="-this_is_the_2nd_run $options $pkg=$xpkg"
	if [ "$ROCKCFG_CREATE_CACHE" = 1 -a $stagelevel -gt 1 ] ; then

		mkdir -p $root/var/adm/cache
		rm -f $root/var/adm/cache/$xpkg
		rm -f $root/var/adm/cache/$xpkg.tm

		/usr/bin/time -o "$root/var/adm/cache/$xpkg.tm" \
		              -f 'buildtime=$(qcalc %U + %S)' $0 $options
		returncode=$?

		qcalc() { gawk "BEGIN { printf(\"%d\n\", ($*)*100); }"; }
		eval "`grep -v '^Command ' < $root/var/adm/cache/$xpkg.tm`"
		rm -f $root/var/adm/cache/$xpkg.tm

		{
			if [ -f $confdir/$pkg.desc ] ; then
				grep '^\[COPY\] ' $confdir/$pkg.desc | \
					sed "s,/$pkg.desc\$,/$pkg.cache,"
			fi

			date '+%n[TIMESTAMP] %s %c'
			echo "[CONFIG-ID] ${ROCKCFG_ID#*-}"
			echo -e "[ROCKVER] $rockver\n"

			echo "[LOGS]" $( cd $root/var/adm/logs ; \
					 ls ?-$xpkg.* 2> /dev/null )
			echo

			unset stagelevel
			for x in 0 1 2 3 4 5 6 7 8 9 ; do
				[ -f "$root/var/adm/logs/$x-$xpkg.log" ] && \
					stagelevel=$x
			done

			if [ "$stagelevel" ] ; then
				echo "[BUILDTIME] $buildtime ($stagelevel)"

				x="$root/var/adm/packages/$xpkg"
				if [ -f $x ]; then
					echo "[SIZE] `grep "^Package Size: " \
							$x | cut -f3- -d' '`"
				fi
				echo

				x="$root/var/adm/dependencies/$xpkg"
				if [ "$pkg" != "rock-debug" -a -f $x ]; then
					cut -f2- -d' ' "$x" | \
						fmt -70 | sed 's,^,[DEP] ,'
					echo
				fi
			fi

			for stagelevel in 0 1 2 3 4 5 6 7 8 9 ; do
				x="$root/var/adm/logs/$stagelevel-$xpkg.err"
				if [ -f "$x" ] ; then
					tail -50 "$x" | \
						sed "s,^,[$stagelevel-ERROR] ,"
					echo
				fi
			done
		} > $root/var/adm/cache/$xpkg

		exit $returncode
	else
		exec $0 $options
	fi
fi


#
# ----  Setting Build Variables
#

flistroot="bin boot etc lib sbin usr var opt"
flistrfilter="ldconfig\..*:	.*|.*:	/var/adm/.*|.*/pkgconfig/.*\.pc"
flistdel="etc/ld.so.cache|var/tmp/.*|usr/tmp/.*|var/adm/logs/.*|.*\\.old"

if [ $stagelevel -le 1 ]
then
	makeopt='CC="$CC" CXX="$CXX" CC_FOR_BUILD="$BUILDCC"'
	makeopt="$makeopt"' BUILDCC="$BUILDCC" BUILD_CC="$BUILD_CC"'
	makeopt="$makeopt"' HOSTCC="$HOSTCC"   HOST_CC="$HOST_CC"'

	makeinstopt="$makeopt"' prefix=$root/$prefix install'

	for x in prefix bindir sbindir libdir datadir \
	         infodir mandir sysconfdir localstatedir \
	         includedir
	do
		makeopt="$makeopt $x=\${$x/${root//\//\\/}/}"
	done
else
	makeopt='prefix=/$prefix CC="$CC" CXX="$CXX"'
	makeinstopt='prefix=/$prefix CC="$CC" CXX="$CXX" install'
	flistdel="$flistdel|`echo $base | sed s,^/,,`/.*"
fi

prepare=""	; hook_add prepare	5 'eval "$prepare"'
prepatch=""	; hook_add prepatch	5 'eval "$prepatch"'
postpatch=""	; hook_add postpatch	5 'eval "$postpatch"'
postdoc=""	; hook_add postdoc	5 'eval "$postdoc"'
preconf=""	; hook_add preconf	5 'eval "$preconf"'
premake=""	; hook_add premake	5 'eval "$premake"'
inmake=""	; hook_add inmake	5 'eval "$inmake"'
postmake=""	; hook_add postmake	5 'eval "$postmake"'
postinstall=""	; hook_add postinstall	5 'eval "$postinstall"'
postflist=""    ; hook_add postflist    5 'eval "$postflist"'
finish=""	; hook_add finish	5 'eval "$finish"'

[ "$ROCKCFG_DO_CHECK" = 1 ] && hook_add inmake 6 'run_check'
hook_add postflist 3 'postflist_static_lib'

configprefix=""	; autogen=0
configscript="./configure" ; extraconfopt=""

srcdir=auto ; srctar=auto
taropt="--use-compress-program=bzip2 -xf"

mainfunction="build_this_package"
runconf=1 ; runxmkmf=1 ; runmkpl=1 ; runpysetup=1 ; autopatch=1
autoextract=1 ; chownsrcdir=1 ; nocvsinsrcdir=1; patchopt="-bfp1 -z .orig"
createprefix=1 ; createdocs="" ; rmemptydir=""

check_shared=1
check_usrlocal=1
check_badfiles=1

badfiles="" badfiles_nr=0
declare -a badfiles_desc

#
# ---- Read various config files
#

parse_desc $pkg

ver="`echo $desc_V | cut -f1 -d' '`"
extraver="`echo $desc_V | cut -s -f2- -d' '`"
[ -z "$extraver" ] && extraver="${rockver//DEV-*/DEV}"

echo_pkg_start $stagelevel $repository $xpkg $ver $extraver

if [ "$ROCKCFG_PARANOIA_CHECK" = 1 -a -z "$pkgdir" ] ; then
        x="`./scripts/Check-PkgFormat $pkg`"
	[ "$x" ] && abort "$x\nDisable the 'Paranoia Check' config `
	                  `option to ignore such errors."
fi

targetdir="$base/target/$target"
patchfiles="`ls $confdir/*.patch $confdir/*.patch.$arch \
             $targetdir/pkg_$pkg.patch $targetdir/pkg_$pkg.patch.$arch \
             2>/dev/null | tr '\n' ' '`"

if [ $stagelevel -eq 0 ]; then
	patchfiles="`ls $patchfiles $confdir/*.patch.cross \
	             $confdir/*.patch.cross.$arch 2>/dev/null | tr '\n' ' '`"
	flistroot="$flistroot include share"
fi

if [ $stagelevel -gt 1 ]; then
	for pc_file in $xroot/var/adm/parse-config/* ; do
		if [ -s "$pc_file" -a "${pc_file##*/}" != "$xpkg" ]
		then . "$pc_file" ; fi
	done
	unset pc_file
fi
. $base/build/$ROCKCFG_ID/$toolsdir/lib/parse-config

set_confopt

eval "$desc_O"

# include package pre config - if any
if [ -f $base/build/$ROCKCFG_ID/$toolsdir/lib/pkg_${pkg}_pre.conf ] ; then
	echo_status "Reading tools/pkg_${pkg}_pre.conf"
	. $base/build/$ROCKCFG_ID/$toolsdir/lib/pkg_${pkg}_pre.conf
fi

if [ -f $targetdir/pkg_$pkg.conf ] ; then
	echo_status "Reading package configuration from target directory."
	. $targetdir/pkg_$pkg.conf

elif [ -f $confdir/$pkg.conf ] ; then
	echo_status "Reading package configuration from package directory."
	. $confdir/$pkg.conf
fi
# include package post config - if any
if [ -f $base/build/$ROCKCFG_ID/$toolsdir/lib/pkg_${pkg}_post.conf ] ; then
	echo_status "Reading tools/pkg_${pkg}_post.conf"
	. $base/build/$ROCKCFG_ID/$toolsdir/lib/pkg_${pkg}_post.conf
fi

if [ -f $base/architecture/$arch/pkg-header ] ; then
	echo_status "Reading overwrites from architecture/$arch/pkg-header."
	. $base/architecture/$arch/pkg-header
fi

if [ -f $base/target/$target/pkg-header ] ; then
	echo_status "Reading overwrites from target/$target/pkg-header."
	. $base/target/$target/pkg-header
fi

#
# ---- Variable updates based on the configuration files read
#

if [ -z "$prefix" -o "${prefix#usr}" != "$prefix" ] ; then
	flistdel="$flistdel|usr/share/info/(dir|standards.info)"
	if [ "$ROCKCFG_DISABLE_NLS" = 1 ] ; then
		flistdel="$flistdel|usr/share/locale/..[/_].*"
		flistdel="$flistdel|usr/share/man/..[/_].*"
	fi
else
	flistdel="$flistdel|$prefix/info/(dir|standards.info)"
	if [ "$ROCKCFG_DISABLE_NLS" = 1 ] ; then
		flistdel="$flistdel|$prefix/share/locale/..[/_].*"
		flistdel="$flistdel|$prefix/man/..[/_].*"
	fi
fi

#
# ----  Build Package
#

echo_status "Preparing build in src.$pkg.$id"

umount -r -d -f    $builddir/* 2> /dev/null
umount -r -d -f -l $builddir/* 2> /dev/null
umount -r -d -f    $builddir   2> /dev/null
umount -r -d -f -l $builddir   2> /dev/null

if [ $clear_src = 1 ] ; then
	rm -rf $builddir/* ; mkdir -p $builddir ; chmod 700 $builddir
	if [ "$ROCKCFG_SRC_TMPFS" = 1 ] ; then
		mount -t tmpfs -o $ROCKCFG_SRC_TMPFS_OPT none $builddir
	fi
else
	mkdir -p $builddir ; chmod 700 $builddir
fi

if [ "$xroot" != "$root" ] ; then
	for x in $flistroot ; do
		[ -d $xroot/$x ] || mkdir -p $xroot/$x
		[ -d $root/$x  ] || ln -sf $xroot/$x $root/
	done
fi

if [ $update = 1 -a ! -f $xroot/var/adm/md5sums/$xpkg ] ; then
	echo_status "Ignoring update mode since package isn't installed already."
	update=0
fi

if [ $update = 1 ] ; then
	echo_status "Creating backup of old package data."
	(
		cd $xroot/
		md5sum --check var/adm/md5sums/$xpkg 2>&1 < /dev/null |
			grep ': FAILED$' | cut -f1 -d:
	) > $builddir/backup_files.txt
	if [ -s $builddir/backup_files.txt ] ; then
		mkdir -p "$xroot/var/adm/backup"
		chmod 700 "$xroot/var/adm/backup"
		backup_tar="$xroot/var/adm/backup/$(
			date '+%Y%m%d%H%M%S')_$xpkg.tar.bz2"
		( cd $xroot/; tar --no-recursion -cf - -T $builddir/`
			`backup_files.txt || true; ) | bzip2 > $backup_tar
	else
		update=0
	fi
fi

if [ "$ROCKCFG_FLIST" = "flwrapper" ] ; then
	rm -f $builddir/fl_wrapper.wlog $builddir/fl_wrapper.rlog
	touch $builddir/fl_wrapper.wlog $builddir/fl_wrapper.rlog
elif [ "$ROCKCFG_FLIST" = "find" ] ; then
	touch $builddir/temp.time_stamp
	sleep 2
fi

hook_eval prepare

# define new abort function for errors while building
#
abort() {
	[ "$*" ] && echo "$*"; echo "--- BUILD ERROR ---"
	rm -vf $root/var/adm/logs/$stagelevel-$xpkg.log
	false
}

{
	trap 'echo "Got SIGINT (Crtl-C). Aborting build." ; exit 1' INT
	exec < /dev/null

	# Makes debugging build problems easier
	#
	hook_dump > $builddir/debug.hooks
	#
	{	dump_env
		echo "PS1='\\[\\e[00m\\e[01;31m\\]debug-`
					`$xpkg\\[\\e[00m\\]:[\\W]\\\$ '"
		echo 'alias cp="cp -i" ; alias mv="mv -i"'
		echo 'alias rm="rm -i" ; alias ls="ls --color=auto -a"'
		echo 'alias ..="cd .." ; alias ...="cd ../.."'
		echo "alias xdiff='sh $base/misc/archive/xdiff.sh'"
		echo "alias bked='sh $base/misc/archive/bked.sh'"
	} > $builddir/debug.buildenv
	#
	{	echo "#!/bin/bash"
		echo "export PROMPT_COMMAND='. debug.buildenv ; cd . ;" \
		     "unset PROMPT_COMMAND'" ; echo "exec bash 200>> build.pid"
	} > $builddir/debug.sh
	chmod +x $builddir/debug.sh

	# Create PID file
	#
	# The builtin-variable '$$' is not this pid because this proc
	# is just a sub-proc of $$. That's why the $builddir/strace.tmp
	# hack is required to get the right pid to trace.
	#
	# We also conntect filedescriptor 3 with the pid file. So the command
	# 'fuser' can be used to create a list of all processes which are part
	# of this build process.
	#
	sh -c 'echo $PPID' > $builddir/build.pid
	exec 200>> $builddir/build.pid

	echo "Command Wrapper Debug: running '${CC} --version' .."
	type ${CC}; CMD_WRAPPER_DEBUG=1 ${CC} --version
	echo "[ writing debug log to $builddir/cmd_wrapper.log ]"

	if [ "$debug" = 1 ] ; then
		echo "Everything is set up." \
		     "We are in debug mode - so exit now."
		exit
	fi

	if [ "$ROCKCFG_FLIST" = "strace" ] ; then
		strace -o $builddir/strace.out -F -f -q -e open,creat,mkdir,`
		       `mknod,link,symlink,rename,utime,chdir,execve,fork,`
                       `vfork,_exit,exit_group -p `cat $builddir/build.pid` &
                 strace_pid=$! ; sleep 1 ; cd $base
	fi

	(
		set -e
		for xsrctar in $( echo "$desc_D" | tr ' ' '\t' | \
			tr -s '\t' | cut -f2 | sed 's,.\(t\?\)\(gz\|Z\)$,.\1bz2,' )
		do
			if [ ! -f $archdir/$xsrctar ]; then
				echo "File not found: ${archdir#$base/}/$xsrctar"
				echo "Did you run ./scripts/Download for this package?"
				false
			fi
		done
		echo "Running main build function '$mainfunction' ..."
		if [ $xtrace -eq 1 -o $ROCKCFG_XTRACE -eq 1 ] ;	then
			PS4=$'=[$FUNCNAME:$LINENO> ' ; set -o xtrace
			cd $builddir ; eval "$mainfunction"
			set +o xtrace
		else
			cd $builddir ; eval "$mainfunction"
		fi
		touch $root/var/adm/logs/$stagelevel-$xpkg.log
	)
	[ ! -f $root/var/adm/logs/$stagelevel-$xpkg.log ] && abort

	hook_eval postinstall

	echo "Creating file list and doing final adaptions ... "
	#
	cd $xroot/
	[ -s "var/adm/parse-config/$xpkg" ] && \
		echo "var/adm/parse-config/$xpkg" >> $builddir/flist.txt
	for x in var/adm/flists/$xpkg var/adm/md5sums/$xpkg \
	         var/adm/cksums/$xpkg var/adm/packages/$xpkg \
	         var/adm/descs/$xpkg var/adm/dependencies/$xpkg ; do
			touch $x ; echo "$x" >> $builddir/flist.txt
	done
	#
	if [ "$ROCKCFG_FLIST" = "strace" ] ; then
		sleep 1 ; kill -INT $strace_pid ; sleep 1
		fl_stparse -w $builddir/fl_wrapper.wlog \
			   -r $builddir/fl_wrapper.rlog < $builddir/strace.out
		
	fi
	if [ "$ROCKCFG_FLIST" = "flwrapper" -o \
	     "$ROCKCFG_FLIST" = "strace" ] ; then
		if [ "$stagelevel" -le 1 ]
		then
			xbase="$( cd $xroot/ 2> /dev/null ; pwd -P )"
			if egrep -qv "($base|$xbase|/tmp|/proc|/dev)/" \
						$builddir/fl_wrapper.wlog
			then
				x="Created file outside basedir: "
				egrep -v "($base|$xbase|/tmp|/proc|/dev)/" \
					$builddir/fl_wrapper.wlog | \
					cut -f2- | sort -u | sed "s,^,$x,"
				echo "base #1: $base"
				echo "base #2: $xbase"
				false
			fi
		fi
		if fl_wrparse -s -r "$xroot/" < $builddir/fl_wrapper.wlog | \
			egrep "^(${flistroot// /|})(/|$)" >> \
			$builddir/flist.txt
		then : ; fi
	elif [ "$ROCKCFG_FLIST" = "find" ] ; then
		if find $flistroot \
			\( -not -type d -or -type d -empty \) \
			-and \( -newer $builddir/temp.time_stamp -or \
			-cnewer $builddir/temp.time_stamp \) -printf "%p\n" >> \
			$builddir/flist.txt
		then : ; fi
	fi

	# merge flist of previous build
	[ -f var/adm/flists/$xpkg ] &&
		cut -f2- -d' ' var/adm/flists/$xpkg >> $builddir/flist.txt

	# evaluate flistdel
	egrep -v "^($flistdel)\$" $builddir/flist.txt > $builddir/flist.txt.new
	mv $builddir/flist.txt.new $builddir/flist.txt

	hook_eval postflist

	fl_wrparse -D -p "$xpkg" -r "$xroot/" < $builddir/flist.txt | \
			sort -u > var/adm/flists/$xpkg
	echo Found `wc -l < var/adm/flists/$xpkg` "files for this package."

	echo "Clear (old) md5sums and cksums ..."
	cat /dev/null > var/adm/md5sums/$xpkg
	cat /dev/null > var/adm/cksums/$xpkg

	if [ "$ROCKCFG_FLIST" = "flwrapper" -o \
	     "$ROCKCFG_FLIST" = "strace" ] && [ $stagelevel -gt 1 ] ; then
		echo "Calculating package dependencies ..."

		! egrep -v "^($flistrfilter)\$" $builddir/fl_wrapper.rlog |
		sort -u | fl_wrparse -s -r "$xroot/" -p '' | \
		sort -k2 var/adm/flists/* - | grep -v ' var/adm/' | awk '
			BEGIN { FS=": "; current="."; }
			$2 == current && $1 != "" && $2 != "'$xpkg'" { print; }
			$1 == "" { current=$2; }' \
					>> $builddir/dependencies.debug

		awk 'BEGIN { FS=": "; } { print "'$xpkg': " $1; }' \
			<  $builddir/dependencies.debug \
			>> $builddir/dependencies.txt

		if [ -f var/adm/dep-debug/$xpkg ] ; then
			cat var/adm/dep-debug/$xpkg \
					>> $builddir/dependencies.debug
		fi
		sort -u $builddir/dependencies.debug > var/adm/dep-debug/$xpkg

		# merge the dependencies defined by the package
		for x in `echo "$desc_E" | egrep '^add ' | sed 's/^add //' ` ; do
			echo "Adding dependency: $x ..."
			echo "$xpkg: $x" >> $builddir/dependencies.txt
		done

		# remove dependencies as requested by the package
		# TODO: goups are not used yet (and it is not easy here)
		del_pattern=""
		for x in `echo "$desc_E" | egrep '^del ' | sed 's/^del //' ` ; do
			del_pattern="$del_pattern -e \".*: $x\$\""  
		done
		if [ -n "$del_pattern" ] ; then
			echo "Deleting dependencies, pattern: $del_pattern ..."
			eval egrep -v $del_pattern \
			  $builddir/dependencies.txt > \
			  $builddir/dependencies.txt.new
			mv $builddir/dependencies.txt{.new,}
		fi

		if [ -f var/adm/dependencies/$xpkg ] ; then
			cat var/adm/dependencies/$xpkg \
					>> $builddir/dependencies.txt
		fi
		sort -u $builddir/dependencies.txt > var/adm/dependencies/$xpkg
	fi

	echo -n "Creating md5sum and cksum files ..."
	getfiles < var/adm/flists/$xpkg > $builddir/files.lst
	if [ -s $builddir/files.lst ] ; then
		cat $builddir/files.lst | \
			grep -v '^var/adm/' | sed -e 's/ /\\ /g' | \
			xargs -r md5sum > var/adm/md5sums/$xpkg
		cat $builddir/files.lst | \
			grep -v '^var/adm/' | sed -e 's/ /\\ /g' | \
			xargs -r cksum > var/adm/cksums/$xpkg
	fi
	echo ' done.'

	echo "Creating package description ..."
	#
	rocksrcck=$(cd $base; md5sum package/*/$pkg/* 2> /dev/null | \
				grep -v '\.cache$' | md5sum | cut -f1 -d' ')
	buildlist="$( grep "^Build \[.\] at " var/adm/packages/$xpkg || true
		echo "Build [$stagelevel] at $buildstart to `date "+%T %Z"`")"
	#
	cat > var/adm/packages/$xpkg << EOT
Package Name and Version: $xpkg $ver $extraver
Package Size: `getdu $root/ < var/adm/flists/$xpkg`, `
				wc -l < var/adm/flists/$xpkg | tr -d ' '` files
ROCK Linux Package Source Checksum: $rocksrcck
ROCK Linux Version and Architecture: $rockver $arch
Build on `uname -m -n -r -s -p`
$buildlist
Status: ${desc_S:-ALPHA},  License: ${desc_L:-Unknown}

  ${desc_I:-$xpkg}

$( echo "${desc_T:-No description available.}" | sed 's,^,  ,' )

URL(s):
$( echo "${desc_U:-http://www.rocklinux.org/packages/$pkg.html}" | sed 's,^,  ,' )

Original Author(s):
$( echo "${desc_A:-Unknown}" | sed 's,^,  ,' )

ROCK Package Maintainer(s):
$( echo "${desc_M:-Unknown}" | sed 's,^,  ,' )

Download URL(s):
$( echo "${desc_D:-None}" | awk '{ print "  " $3 $2; }' )
EOT
	{
	    echo "[CONFIG] ${ROCKCFG_ID#*-}"
	    descfile=$base/package/*/$pkg/$pkg.desc
	    while read x ; do
		if [ "${x#\[}" != "$x" ] ; then
		    x="`echo ${x// /|} | tr -d '[]'`"
		    y="${x%%|*}" ; x="(${x%|(*)})"
		    egrep "^\[$x\]" $descfile | expand | sed "s,^[^ ]*,[$y],"
		fi
	    done < $base/Documentation/Developers/PKG-DESC-FORMAT
	} > var/adm/descs/$xpkg

	echo "Making post-install adaptions."
	if [ $stagelevel -ge 2 -a -f /sbin/ldconfig ] ; then ldconfig ; fi

	if [ "$ROCKCFG_PARANOIA_CHECK" = 1 ] ; then
		found_errors=0
		found_dups=0

		# check for files which are 'shared' with other packages
		if [ "$check_shared" != "0" ]; then
			while read dummy file; do
				if [ $found_dups = 0 ] ; then
					echo "Found shared files with other packages:"
					found_errors=1; found_dups=1
				fi
				echo "$file:" $( cd $root/var/adm/flists
						 grep -l " $file\$" * )
			done < <( cat $root/var/adm/flists/* | sed "s,^$xpkg:,.," | \
				  sort +1 | uniq -d -f1 | grep '^\. ' )
		fi

		found_local=0

		# check for files in /usr/local
		if [ "$check_usrlocal" != "0" ]; then
			while read file ; do
				if [ $found_local = 0 ] ; then
					echo "Found files in /usr/local:"
					found_errors=1; found_local=1
				fi
				echo $file
			done < <( sed "s,^$xpkg: ,/," $root/var/adm/flists/$xpkg | \
				    egrep "^/usr/local" )
		fi

		found_bad=0

		# check for registered 'bad files'
		if [ "$check_badfiles" != "0"  -a -n "$badfiles" ]; then
			echo "$badfiles" > $builddir/badfiles.txt
			while read x file; do
				if [ $found_bad = 0 ]; then
					echo "Found registered 'bad files' in package:"
					found_errors=1; found_bad=1
				fi
				desc="No description found!"
				for ((x=0; x<badfiles_nr; x++)); do
					if echo " $file" | grep -q "${badfiles_desc[x]%%$'\n'*}" 
					then desc="${badfiles_desc[x]#*$'\n'}"; fi
				done
				echo "$file: $desc"
			done < <( grep -f $builddir/badfiles.txt $root/var/adm/flists/$xpkg )
		fi

		[ $found_errors != 0 ] && abort
	fi

} 2>&1 | {

	trap '' INT

	echo_status "Building. Writing output to" \
	            "\$root/var/adm/logs/$stagelevel-$xpkg.out"

	if [ "$ROCKCFG_VERBOSE" = 1 -o "$verbose" = 1 ] ; then
		tee $root/var/adm/logs/$stagelevel-$xpkg.out
	else
		cat > $root/var/adm/logs/$stagelevel-$xpkg.out
	fi
}

hook_eval finish

if [ $update = 1 ] ; then
	echo_status "Restoring backup of old package data."

	while read fn ; do
		[ -f $xroot/$fn ] && mv $xroot/$fn $xroot/$fn.new
	done < $builddir/backup_files.txt

	tar --use-compress-program=bzip2 -C $xroot/ -xpf $backup_tar

	while read fn ; do
		cmp -s $fn $fn.new && rm -f $fn.new
	done < $builddir/backup_files.txt
fi

cd $base

umount -r -d -f    $builddir/* 2> /dev/null
umount -r -d -f -l $builddir/* 2> /dev/null

if [ "$ROCKCFG_SRC_TMPFS_LOG" = 1 -a -n "$( type -p df )" ]; then
	mkdir -p $root/var/adm/rock-debug
	if [ ! -f $root/var/adm/rock-debug/tmpfslog.txt ] ; then
		echo -e "# Config\tPackage\tInodes\tKB" | \
			expand -20 > $root/var/adm/rock-debug/tmpfslog.txt
	fi
	echo -e "$config\t$stagelevel-$xpkg\t$(
		df 2> /dev/null -Pi $builddir | tail -1 | tr -s ' ' | cut -f3 -d' '
	)\t$(
		df 2> /dev/null -Pk $builddir | tail -1 | tr -s ' ' | cut -f3 -d' ')" | \
	expand -20 >> $root/var/adm/rock-debug/tmpfslog.txt
fi

umount -r -d -f    $builddir   2> /dev/null
umount -r -d -f -l $builddir   2> /dev/null

if [ -f $root/var/adm/logs/$stagelevel-$xpkg.log ] ; then
	if [ $clear_src = 1 ] ; then
		rm -rf $builddir/* $builddir
	else
		cp $root/var/adm/logs/$stagelevel-$xpkg.out $builddir/BUILD-LOG
	fi
	echo_status "\$root/var/adm/logs/$stagelevel-$xpkg.out" \
	            "-> $stagelevel-$xpkg.log"
	mv $root/var/adm/logs/$stagelevel-$xpkg.out \
		$root/var/adm/logs/$stagelevel-$xpkg.log
	echo_pkg_finish $stagelevel $repository $xpkg
	exit 0
else
	if [ $clear_src = 1 -a "$ROCKCFG_ALWAYS_CLEAN" = 1 ] ; then
		rm -rf $builddir/* $builddir
	else
		cp $root/var/adm/logs/$stagelevel-$xpkg.out $builddir/ERROR-LOG
	fi
	if [ "$ROCKCFG_VERBOSE" != 1 -a "$verbose" != 1 ] ; then
		echo_errorquote "$( grep -B7 -- '--- BUILD ERROR ---' \
			$root/var/adm/logs/$stagelevel-$xpkg.out | \
			sed '$ s,--- BUILD ERROR ---,,' | \
			grep . | grep -vx -- -- )"
	fi
	echo_status "\$root/var/adm/logs/$stagelevel-$xpkg.out" \
	            "-> $stagelevel-$xpkg.err"
	mv $root/var/adm/logs/$stagelevel-$xpkg.out \
		$root/var/adm/logs/$stagelevel-$xpkg.err
	echo_pkg_abort $stagelevel $repository $xpkg
	exit 1
fi

# ----  EOF