# --- 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/functions
# ROCK Linux is Copyright (C) 1998 - 2006 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 ---

# This function returns a "uniqe id" as output
#
get_unique() {
	date "+%s.$$.`{ /sbin/ifconfig -a; /sbin/ip a; } 2>&1 | cksum | cut -f1 -d' '`"
}

# Hook variables
#
unset hook_functions hook_fcounter
declare -a hook_functions='()'
hook_fcounter=0

# This function adds a code fragment to a named hook with the named priority
#
# hook_add hook_name priority code
#
hook_add() {
	hook_functions[hook_fcounter]="$3" # declare -a hookidx_$1
	eval "hookidx_$1[\${#hookidx_$1[@]}]=\"$2 $hook_fcounter\""
	eval "(( hookdirty_$1++ ))"; (( hook_fcounter++ ))
}

# This function executes all code fragments from the named hook
#
# hook_eval hook_name
#
hook_eval() {
	while read pri fnr ; do
		eval "${hook_functions[fnr]}"
	done < <( IFS=$'\n' ; eval "echo \"\${hookidx_$1[*]}\"" | sort )
	eval "unset hookdirty_$1"
}

# This function prints all hooks and their current contents
#
# hook_dump
#
hook_dump() {
	for hook in ${!hookidx_*} ; do
		hook=${hook#hookidx_}
		echo ; echo "Contents of hook $hook:"
		
		while read pri fnr ; do
			echo ; echo "    $pri ($fnr)"
			echo "${hook_functions[fnr]}" | sed 's,^,	,'
		done < <( IFS=$'\n'
		          eval "echo \"\${hookidx_$hook[*]}\"" | sort )
		if eval "[ -n \"\$hookdirty_\$hook\" ]"; then
			echo ; echo -n "    Hook is marked as dirty: "
			eval "echo \"\${hookdirty_$hook}\""
		fi
	done
	echo
}

# This function register a split package
#
# splitreg prio name regex
#
splitreg() {
	var_append pkgsplits "," "$1 $2 $3"
}

# This function modifies an flist file according to the registered splits
#
# splitapply pkg-name flist-file
#
splitapply() {
	local p n r
	sed -i "s/^[^ ]+/$1:/" $2
	while read -r p n r; do
		if [ "$n" = "." ]; then
			echo "Applying package split: $p $1 $r"
			sed -ri "\,$r, s/^[^ ]+/$1:/" $2
		else
			if type "splitdesc_${n}" > /dev/null 2>&1; then
				echo "Applying package split: $p $1:$n $r"
				sed -ri "\,$r, s/^[^ ]+/$1:$n:/" $2
			else
				echo "Skipping package split: $p $1:$n $r (splitdesc_$n() undefined)"
			fi
		fi
	done < <( echo "$pkgsplits" | tr ',' '\n' | sort; )
}

# This functions append, insert or remove values in variables:
#
#	var_append PATH ":" "$HOME/bin"
#	var_insert CC_WRAPPER_INSERT " " "-O3"
#	var_remove CC_WRAPPER_INSERT " " "-O3"
#
#	var_remove_regex CC_WRAPPER_INSERT " " "-O.*"
#
#	var_insert_before_regex patchfiles " " "mypatch.diff" ".*\/foo.diff"
#
# 1st Parameter: Variable Name
# 2nd Parameter: Delimiter Text
# 3rd Parameter: Value (or regex)
# 4th Parameter: regex for insert_before
#
var_append() {
	eval "[ \"\$$1\" ] && $1=\"\${$1}$2\"" || true
	eval "$1=\"\${$1}\$3\""
}
var_insert() {
	eval "[ \"\$$1\" ] && $1=\"$2\$$1\"" || true
	eval "$1=\"\$3\$$1\""
}
var_remove() {
	local a=${2//\/\\/}
	local b=${3//\/\\/}
	eval '[ "$'$1'" = "$3" ] && '$1'="" || true'
	eval $1'="${'$1'//$a$b$a/$2}"'
	eval $1'="${'$1'%$a$b}"'
	eval $1'="${'$1'#$b$a}"'
}
var_remove_regex() {
	eval "$1=\"\`echo \"\$$1\" | awk -- ' { split(\$0, a, \"$2\"); for (c1=c2=1; c1 in a; c1++) if ( a[c1] !~ /^$3\\\$/ ) b[c2++]=a[c1]; for (c1=1; c1 in b; c1++) printf \"%s%s\", (c1 > 0 ? \"$2\" : \"\"), b[c1]; }'\`\""
}
var_insert_before_regex() {
	eval "$1=\"\`echo \"\$$1\" | awk -- '{ split(\$0, a, \"$2\"); for (d=c1=c2=1; c1 in a; c1++) { if ( d && a[c1] ~ /^$4\\\$/ ) { b[c2++]=\"$3\"; d=0; } b[c2++]=a[c1]; } if (d) b[c2++]=\"$3\"; for (c1=1; c1 in b; c1++) printf \"%s%s\", (c1 > 0 ? \"$2\" : \"\"), b[c1]; }'\`\""
}

# This function can be used to duplicate a shell-function. E.g. when
# overwriting a shell-function but the old one should stay available under
# a new name:
#
#	copy_function set_confopt set_confopt_foobar_old
#
#	set_confopt() {
#		....
#		set_confopt_foobar_old "$@"
#		....
#	}
#
copy_function() {
	eval "$( declare -f $1 | sed "1 s,$1,$2," )"
}

# | column_clean |
#
# convert tabs to spaces, transform multiple consecutive spaces to one,
# remove leading and trailing spaces
column_clean() {
	tr '\t' ' ' | tr -s ' ' | sed -e 's,^[ ]*,,; s,[ ]*$,,;'
}

# | column_clean_tab |
#
# see column_clean, but with tabs
column_clean_tab() {
	tr ' ' '\t' | tr -s '\t' | sed -e 's,^[\t]*,,; s,[\t]*$,,;'
}

# This function sets the 'confopt' and some other variables.
# Re-run it in the package .conf file if you modify $prefix
#
set_confopt() {
	confopt="--prefix=$root/$prefix"

	bindir="$root/$prefix/bin"
	confopt="$confopt --bindir=\$bindir"

	sbindir="$root/$prefix/sbin"
	confopt="$confopt --sbindir=\$sbindir"

	libdir="$root/$prefix/lib"
	confopt="$confopt --libdir=\$libdir"

	if [ -z "$prefix" ]; then
		datadir="$root/usr/share"
		includedir="$root/usr/include"

		docdir="$root/usr/share/doc/$xpkg"
		infodir="$root/usr/share/info"
		mandir="$root/usr/share/man"
	else
		datadir="$root/$prefix/share"
		includedir="$root/$prefix/include"

		docdir="$root/$prefix/share/doc/$xpkg"
		infodir="$root/$prefix/share/info"
		mandir="$root/$prefix/share/man"
	fi
	confopt="$confopt --datadir=\$datadir"
	confopt="$confopt --includedir=\$includedir"

	confopt="$confopt --infodir=\$infodir"
	confopt="$confopt --mandir=\$mandir"

	if [ "${prefix#opt/}" != "$prefix" ] ; then
		sysconfdir="$root/etc/$prefix"
		localstatedir="$root/var/$prefix"
	elif [ "${prefix#usr}" != "$prefix"  ] ; then
		sysconfdir="$root/etc"
		localstatedir="$root/var"
	else
		sysconfdir="$root/$prefix/etc"
		localstatedir="$root/$prefix/var"
	fi
	confopt="$confopt --sysconfdir=\$sysconfdir"
	confopt="$confopt --localstatedir=\$localstatedir"

	if [ "$ROCKCFG_CONFIGURE_OPTS" ] ; then
		confopt="$confopt $ROCKCFG_CONFIGURE_OPTS"
	fi

	if [ "$ROCKCFG_DEBUG" = 0 ] ; then
		confopt="$confopt --disable-debug"
	fi

	if [ "$stagelevel" -le 1 -o "$ROCKCFG_DISABLE_NLS" = 1 ] ; then
		confopt="${confopt//--enable-nls/} --disable-nls"
	fi

	confopt="$confopt \$extraconfopt"
	if [ "$stagelevel" -eq 0 ]; then
		confopt="$confopt --target=\$arch_target --host=\$arch_build"
	else
		confopt="$confopt --build=\$arch_build --host=\$arch_target"
	fi
}

#
# eval_config_command $( eval echo $confopt )
#
function eval_config_command() {
	local config_command

	for x in /usr/share/automake/*
	do
		[ -x "$x" -a -f "$x" ] || continue
		x="$( basename "$x" )"
		if [ -L $x -a ! -e $x ] ; then
			echo "Fixing dead symlink $x."
			ln -sf /usr/share/automake/$x .
		fi
	done
	if [ $autogen -eq 1 -a \( -f configure.in -o -f configure.ac \) ] ; then
		if [ -f configure.orig ] ; then
			echo "Found configure.orig. Not" \
			     "running autogen script."
		elif [ -f autogen.sh ] ; then
			echo "Running package autogen script."
			sh autogen.sh
		else
			echo "Running builtin autogen script."
			libtoolize --force --automake
			aclocal$automakever
			if grep AM_INIT_AUTOMAKE configure.[ia][nc]
				then automake$automakever ; fi
			autoconf
		fi
	fi
	if [ $stagelevel -le 1 ] ; then
		create_config_cache >> config.cache
		grep -q '.--cache-file=' $configscript &&
			set -- "$@" "--cache-file=config.cache"
		export cache_file=config.cache
	fi

	config_command="$configprefix $configexec $configscript"
	sub_scripts="$( find $( dirname $configscript ) -name configure )"

	# remove unsupported config script options
	for x ; do
		if grep -q "[[ ]${x%%=*}[]= ):]" $configscript $sub_scripts ; then
			config_command="$config_command $x"
		elif [[ $x = --*able-* ]] && egrep -q "\-\-(en|dis)able-\*" $configscript ; then
			echo "Autodetection for option impossible: " \
			     "$x passed thru."
			config_command="$config_command $x"
		else
			echo "Removing unsupported '$x' from" \
			     "configure option string."
		fi
	done

	echo Running "$config_command"
	eval "$config_command"
}

# run 'make check' if Makefile supports it.
#
function run_check() {
	if grep -q -e "^check:" ./Makefile; then
		echo "Running make check ..."
		$MAKE check
	fi
	if grep -q -e "^test:" ./Makefile; then
		echo "Running make test ..."
		$MAKE test
	fi
}

# move the static libs from lib to usr/lib and correct the libdir used
# inside the .la file
#
postflist_static_lib() {
	echo "Processing static lib corrections ..."
	egrep '^lib/.*\.(a|la)$' $builddir/flist.txt |
	while read fn ; do
		[ -e $root/$fn -o -L $root/$fn ] || continue
		if [[ $fn = *.a ]] ; then
			mv -fv $root/$fn $root/usr/$fn
		else
			sed "s,\([ =']\)/lib\(.*\),\1/usr/lib\2,g" \
				$root/$fn > $root/usr/$fn
			rm $root/$fn
		fi
		add_flist $root/usr/$fn
	done

	# this check might be removed in the future when we decide this is not
	# an issue anymore ...
	echo "Verifing the .la files ..."
	defect_la="`egrep 'lib/.*\.la$' $builddir/flist.txt |
	            xargs egrep 'dependency_libs=.*-pthread.*' |
	            cut -d : -f1 | sort -u | tr '\n' ' '`"
	if [ "$defect_la" ] ; then
		abort "-pthread in: $defect_la!"
	fi
}

# Parse the *.desc file. Use the description from PKG-DESC-FORMAT and
# save the tag data in $desc_*.
#
parse_desc() {
	tag="`grep '^\[' $base/Documentation/Developers/PKG-DESC-FORMAT | \
	      sed 's, (\*),,; s,\] \[,|,g; s,\[,,; s,\],,;'`"
	descfile="$( pkg="$pkg" xpkg="$xpkg" descparser < $1 )"
	for tag in $tag ; do
		tagdata="`echo "$descfile" | egrep "^\[($tag)\]" | \
			  cut -f2- -d']' | sed 's,^ ,,'`"
		tag="`echo $tag | cut -f1 -d'|' | tr - _`"
		if eval "[ -z \"\$desc_$tag\" ]"; then
			eval "desc_$tag=\"\$tagdata\""
		fi
	done
}

# This function is used for forcing a file to be in the flist
#
add_flist() {
	for addfile ; do
		echo "$addfile" | fl_wrparse -D -r "$xroot/" \
			>> $builddir/flist.txt
	done
}

# This function is used for forcing a package to be in the dependency list
#
add_dependency() {
	for addpackage ; do
		echo "$addpackage: add_dependency()" \
					>> $builddir/dependencies.debug
	done
}

# This function adds a wrapprer for the currently running build
#
# Usage:
#
# add_wrapper bin_name <<- 'EOT'
#	demo-demo-demo-demo
#	$orig "$@"; rc=$?
#	demo-demo-demo-demo
#	exit $rc
# EOT
#
declare -a wrapper_data='()'
add_wrapper() {
	local l data="$1"
	while read l; do
		data="$data
$l"
	done
	wrapper_data[${#wrapper_data[@]}]="$data"
}

# This function is used to subsitute some important variables
# using a D_ prefix thru m4 ...
rock_substitute() {
	sed -e s,D_prefix,$prefix,g   -e s,D_sysconfdir,$sysconfdir,g \
	    -e s,D_docdir,$docdir,g   -e s,D_localstatedir,$localstatedir,g \
	    -e s,D_datadir,$datadir,g -e s,D_infodir,$infodir,g \
	    -e s,D_bindir,$bindir,g   -e s,D_sbindir,$sbindir,g \
	    -e s,D_libdir,$libdir,g   -e s,D_mandir,$mandir,g \
	    -e s,D_version,$ver,g $1
}

# This outputs a predefined config.cache file as it needed by some
# packages to cross-build correctly in stages 0 and 1.
#
create_config_cache() {
	cat $base/scripts/config.cache

	echo -e "\n# Architecture specific stuff\n"
	echo "arch_sizeof_char=1"
	echo "ac_cv_sizeof_short=$arch_sizeof_short"
	echo "ac_cv_sizeof_int=$arch_sizeof_int"
	echo "ac_cv_sizeof_long=$arch_sizeof_long"
	echo "ac_cv_sizeof_long_long=$arch_sizeof_long_long"
	echo "ac_cv_sizeof_char_p=$arch_sizeof_char_p"
	echo "ac_cv_sizeof_void_p=$arch_sizeof_char_p"
	echo "ac_cv_c_bigendian=$arch_bigendian"

	local pt=""
	[ $arch_sizeof_char_p -eq $arch_sizeof_int       ] && pt="int"
	[ $arch_sizeof_char_p -eq $arch_sizeof_long      ] && pt="long"
	[ $arch_sizeof_char_p -eq $arch_sizeof_long_long ] && pt="long long"
	[ -n "$pt" ] && echo "db_cv_alignp_t=\"unsigned $pt\""

	echo "ac_cv_prog_CC=$CC"
}

# Abort build before actual build starts
# (is overwritten in Build-Pkg)
#
abort() {
	echo -e "The package build aborted with the following config" \
	     "error:\n$*" > $root/var/adm/logs/$stagelevel-$xpkg.err
	echo_errorquote "`cat $root/var/adm/logs/$stagelevel-$xpkg.err`"
	echo_pkg_abort $stagelevel $repository $xpkg
	exit 1
}

# Dump Environment
#
dump_env() {

	# Dump $base - only set if there is not already an older value.
	#
	echo "base=\"\${base:-$base}\""

	# Dump all variables including their flags, but skip read-only
	# variables and $base.
	#
	# Substitute base directory with ${base}.
	#
	for name in ${!a*} ${!b*} ${!c*} ${!d*} ${!e*} ${!f*} ${!g*} ${!h*} \
	            ${!i*} ${!j*} ${!k*} ${!l*} ${!m*} ${!n*} ${!o*} ${!p*} \
	            ${!q*} ${!r*} ${!s*} ${!t*} ${!u*} ${!v*} ${!w*} ${!x*} \
	            ${!y*} ${!z*}					    \
	            ${!A*} ${!B*} ${!C*} ${!D*} ${!E*} ${!F*} ${!G*} ${!H*} \
	            ${!I*} ${!J*} ${!K*} ${!L*} ${!M*} ${!N*} ${!O*} ${!P*} \
	            ${!Q*} ${!R*} ${!S*} ${!T*} ${!U*} ${!V*} ${!W*} ${!X*} \
	            ${!Y*} ${!Z*} ${!_*}
	do
		[ $name = IFS ] && continue
		[ $name = base ] && continue
		if declare -p $name | head -n 1 | grep -qv '^declare -[a-z]*r'
		then
			declare -p $name | sed "s,\\(^\\|[\"=:]\\)$base\\([\"=:/]\\|\$\\),\\1\${base}\\2,g"
		fi
	done

	# Dump functions
	#
	declare -f | sed 's/^declare -f //; s/<<(/< <(/;'

	# Dump aliases
	#
	alias
}

# Check if a package is already installed
#
# It does check the build-list if not in the rebuild stage - and
# the really installed package data for rebuilds (and so manual builds).
#
pkginstalled() {
	local pattern="$1"; pattern="${pattern//+/\\+}"
	if [ "$stagelevel" -le 8 ] ; then
		egrep -q "^X.* ($pattern) " $base/config/$config/packages
	else
		ls $root/var/adm/flists | egrep -q "^($pattern)$"
	fi
}

# Register a window-manager
#
register_wm() {
	[ -e /usr/share/rock-registry/wm ] || mkdir -p $root/usr/share/rock-registry/wm
	echo -e "name=\"$2\"\nexec=\"$3\"\n" > $root/usr/share/rock-registry/wm/$1
}

# Register a xdm - display manager
#
register_xdm() {
	[ -e /usr/share/rock-registry/xdm ] \
		|| mkdir -p /usr/share/rock-registry/xdm
	echo -e "name=\"$2\"\nexec=\"$3\"\n" > /usr/share/rock-registry/xdm/$1
}

# Create Package Database for gasgui install tool
#
create_package_db() {
	local admdir="$1"
	local outdir="$2"

	rm -f $outdir/packages.db $outdir/packages_stripped.db
	rm -f $outdir/packages.db.md5 $outdir/packages_stripped.db.md5
	rm -f $outdir/packages.db.tmp

	for file in $( ls $admdir/descs/ ) ; do
		pkg="${file##*/}"
		# only include the package if a binary file is available

		if [ "$ROCKCFG_PKGFILE_VER" = 1 ] ; then
			v=-$(grep '^Package Name and Version' \
                                $admdir/packages/$pkg | cut -f6,7 -d' ' | tr ' ' -)
		else
			v=""
		fi
		if [ "$ROCKCFG_CREATE_GEM" = 1 ] ; then
			bfile=${pkg}${v}.gem
		else
			bfile=${pkg}${v}.tar.bz2
		fi

		if [ -e $outdir/$bfile ] ; then
			[ "$pkg" = TRANS.TBL ] && continue

			( echo -e "$pkg"
			  echo -e "\027"

			  cat $admdir/descs/$pkg
			  echo -e "\027"

			  cat $admdir/dependencies/$pkg
			  echo -e "\027"

			  cat $admdir/cksums/$pkg
			  echo -e "\027"

			  echo -e "\004"
			) >> $outdir/packages.db.tmp
		fi
	done

	gawk '
		BEGIN { chunk=0; }
		$0 == "\004" { chunk=0; print; next; }
		$0 == "\027" { chunk++; print; next; }
		chunk != 3 { print; }
	' < $outdir/packages.db.tmp | gzip -9 > $outdir/packages_stripped.db

	gzip -9 < $outdir/packages.db.tmp > $outdir/packages.db
	rm -f $outdir/packages.db.tmp

	( cd $outdir; md5sum packages.db > packages.db.md5; )
	( cd $outdir; md5sum packages_stripped.db > packages_stripped.db.md5; )
}

# Add files to the 'badfiles' list
#
register_badfiles() {
	local x desc="$1"
	shift

	for x in "$@"; do
		var_append badfiles $'\n' " $x\$"
		badfiles_desc[$badfiles_nr]=" $x\$"$'\n'"$desc"
		(( badfiles_nr++ ))
	done
}

# Apply the given $patchfiles
#
apply_patchfiles() {
	for x in $patchfiles; do
		echo "Apply patch $x ..."
		if [[ $x = *.bz2 ]] ; then
			bzcat $x | patch $patchopt
		else
			patch $patchopt < $x
		fi
		eval "$@"
        done
}

# Main program for building a package
#
build_this_package() {
	if [ ".$desc_SRC" == "." ] ; then
		# Autodetect source tar and extract it
		#
		if [ $srctar = auto ] ; then
			xsourceballs=$( echo "$desc_D" | head -n 1 | tr ' ' '\t' | tr -s '\t' | \
				cut -f2 | sed 's,.\(t\?\)\(gz\|Z\)$,.\1bz2,' )
			if [ -z "$xsourceballs" ] ; then
				echo "Can't auto-detect srctar for package '$xpkg'!"
				false
			fi
		else
			xsourceballs="$srctar"
		fi
	else
		sourceballs=$( echo "$desc_D" | tr ' ' '\t' | tr -s '\t' | \
			cut -f2 | sed 's,.\(t\?\)\(gz\|Z\)$,.\1bz2,' )
		xsrcpattern=$( echo "$desc_SRC" | tr ' ' '\t' | tr -s '\t' | tr '\t' '\n' )
		xsourceballs=$( echo "$sourceballs" | grep -F "$xsrcpattern" )
	fi
	for xsrctar in $xsourceballs; do
		saved_patchfiles="$patchfiles"
		var_append patchfiles " " \
		           "`ls $confdir/*.patch.${xsrctar/-[0-9]*/} 2> /dev/null`"
		if [ $autoextract = 1 ]; then
			echo "Extracting $xsrctar ($taropt) ... "
			cd $builddir
			tar -v $taropt $archdir/$xsrctar | tee untar.txt |
				cut -f1 -d/ | sort -u > xsrcdir.txt
			#
			if [ $srcdir = auto ]; then
				xsrcdir=${xsrctar%.tar.bz2}
				xsrcdir=${xsrcdir%.tbz2}
				if [ ! -d $xsrcdir ] ; then
					for x in $pkg-$ver ${pkg}_$ver $pkg \
					         $xpkg-$ver ${xpkg}_$ver $xpkg \
					         "$( cat xsrcdir.txt )"
					do
						[ -d "$x" ] && xsrcdir="$x"
					done
				fi
			else
				xsrcdir="$srcdir"
			fi
			#
			if [ "$chownsrcdir" = 1 ]; then
				echo "Fixing ownership and permissions ..."
				chown -R 0:0 $builddir/$xsrcdir
			fi
			#
			if [ "$nocvsinsrcdir" = 1 ]; then
				echo "Removing CVS and .svn directories ..."
				egrep '(^|/)(CVS|\.svn)(/|$)' untar.txt |
				while read x; do
					echo "Removing $x ..."
					rm -rf "$x"
				done
			fi
			#
			echo "Changeing into $builddir/$xsrcdir ..."
			cd $builddir/$xsrcdir

			# Apply patches
			#		
			if [ $autopatch = 1 ]; then
				hook_eval prepatch
				apply_patchfiles	
				hook_eval postpatch
			fi

		else
			cd $builddir
		fi

		if [ "$createprefix" = 1 ]; then
			echo "Creating $root/$prefix/<..> if required ..."
			for x in $root/$prefix $bindir $sbindir $libdir $datadir $includedir \
			         $docdir $infodir $mandir $sysconfdir $localstatedir
			do
				if [ ! -e $x ]; then
					mkdir -p $x
					rmemptydir="$x $rmemptydir"
				fi
			done
			if [ ! -e $root/$prefix/man ]; then
				ln -s ${mandir#$root} $root/$prefix/man
				rmemptydir="$rmemptydir $root/$prefix/man"
			fi
			if [ ! -e $root/$prefix/info ]; then
				ln -s ${infodir#$root} $root/$prefix/info
				rmemptydir="$rmemptydir $root/$prefix/info"
			fi
		fi
		
		if [ ".$custmain" = "." ]
		then

			# Run configure scripts etc.
			#
			hook_eval preconf
			#
			if [ $runconf = 1 ]; then 
			  if [ -n "$( type -p $configscript )" -o $autogen = 1 ]
			  then
				eval_config_command $( eval echo $confopt )
			  fi
			fi

			# automated package build

			# styles without make run first:
			if [ -f setup.py -a $runpysetup = 1 ] ; then
				pyconfopt="${pyconfopt:=--prefix $root/$prefix}"
				eval python setup.py build install $pyconfopt
			else # styles that include a make run
				if [ ! -f Makefile -a ! -f makefile -a \
				     -f Makefile.PL -a $runmkpl = 1 ]; then
					sed -i 's/auto_install/# &/' Makefile.PL
					perl Makefile.PL INSTALLDIRS=perl
				fi
				#
				if [ ! -f Makefile -a ! -f makefile -a \
				     -f Imakefile -a $runxmkmf = 1 ]; then
					xmkmf -a
				fi
				#
				# Build it
				#		
				hook_eval premake
				if [ "$makeopt"     ]
				then eval "$MAKE $makeopt"; fi
				hook_eval inmake
				if [ "$makeinstopt" ]
				then eval "$MAKE $makeinstopt"; fi
				hook_eval postmake

			fi
		else
			eval "$custmain"
			for x in preconf premake inmake postmake; do
				if eval "[ -n \"\$hookdirty_$x\" ]"; then
					echo "Hook $x is still marked as dirty ..."
					hook_eval $x
				fi
			done
		fi

		if [ "$createdocs" != 0 ]; then
			if [ ! -e $docdir ]; then
				mkdir -p $docdir
				rmemptydir="$rmemptydir $docdir"
			fi
			[ -z "$createdocs" ] && createdocs="$ROCKCFG_CREATE_DOCS"
		fi
		
		[ -n "${desktopfiles}" ] && for file in ${desktopfiles} ; do
			[ -f $file ] || continue
	
			echo -n "Install desktop file '$file': "

			mkdir -p $root/usr/share/applications

			rock_substitute $file > \
			  $root/usr/share/applications/`basename $file`
		done

		if [ -f $confdir/postinstall.sh.$xpkg ] ; then
			echo "Installing postinstall file $confdir/postinstall.sh.$xpkg"
			mkdir -p $root/etc/postinstall

			rock_substitute $confdir/postinstall.sh.$xpkg > \
			  $root/etc/postinstall/$xpkg-postinstall.sh
		elif [ -f $confdir/postinstall.sh -a "$pkg" != "$xpkg" ] ; then
			echo_error "forked package $xpkg from $pkg"
			echo_error "but only found a 'postinstall.sh'"
			echo_error "please create a 'postinstall.sh.$xpkg'"
		elif [ -f $confdir/postinstall.sh ] ; then
			echo "Installing postinstall file $confdir/postinstall.sh"
			mkdir -p $root/etc/postinstall

			rock_substitute $confdir/postinstall.sh > \
			  $root/etc/postinstall/$pkg-postinstall.sh
		fi

		if [ "$createdocs" = 1 ]; then
			echo "Trying to copy the default documentation ..."
			[ -d $builddir/$xsrcdir ] && cd $builddir/$xsrcdir
			for x in `find -type d \( -name 'doc' -o -name 'docs' -o \
				       -name '[Dd]ocumentation' \) ! -empty`
			do
				if [ -d "$x" -a "`echo $x/*`" != "$x/*" ]
				then cp -rLv $x/* $docdir || true ; fi
			done
			for x in [A-Z][A-Z]* *.lsm ChangeLog*; do
				[ "${x#*.[cho0-9]}" ] || continue
				[ "${x#*.info*}"    ] || continue
				if [ -f $x ] ; then cp -v $x $docdir/$x ; fi
			done
			for x in $confdir/*.doc; do
				if [ -f $x ]; then cp -v $x $docdir/${x%.doc}; fi
			done
			find $docdir/ -name '*.[0-9]' -o -name '*.info*' \
				-o -name '[Mm]akefile*' | \
				xargs -r rm -f 2> /dev/null || true
			find $docdir/* -type d -empty 2> /dev/null | \
				xargs -r rmdir 2> /dev/null || true
		fi

		hook_eval postdoc
		patchfiles="$saved_patchfiles"
	done
  
	for x in $rmemptydir; do
		rmdir $x 2> /dev/null || true
		[ -e $x ] || rm $x 2> /dev/null || true
	done

	return 0
}

# [D] line regex:
Dre='\([^:]*\):\([^ ]*\)[ ]\([^ ]*\)[ ]\(\([^ ]\)[^ ]*\)[ ]\([^ ]*\)'
# \1: package-desc-path                 \2: '[D]'
# \3: cksum                             \4: archive-file
# \5: first-letter-of-archive-file      \6: download-url
D2re='\([^ ]*\)[ ]\([^ ]*\)[ ]\(\([^ ]\)[^ ]*\)[ ]\([^ ]*\)'
# \1: '[D]'                             \2: cksum 
# \3: archive-file                      \4: first-letter-of-archive-file
# \5: download-url

# NODIST flag regex:
NODISTre='[nN][oO][dD][iI][sS][tT]'

# source_file cksum file url flags...
#
# Create the file path from 'file' and 'flags'.
# cksum and url are ignored
# ([D] tag compatible format)
source_file() {
	local pre="" file="$2"
	shift; shift; shift
	
	# inside Build-Pkg $archdir is set
	if [ -n "$archdir" ]; then
		pre=$base/; file="$( echo $file | sed 's,.\(t\?\)\(gz\|Z\)$,.\1bz2,' )"
	fi
    
	if echo $* | egrep -q "($NODISTre)"; then 
		echo ${pre}download/nodist/${file:0:1}/$file
	else
		echo ${pre}download/mirror/${file:0:1}/$file
	fi
}