# --- 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 - 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 ---

# This function returns a "uniqe id" as output
#
get_unique() {
	date "+%s.$$.`/sbin/ifconfig -a | 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 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," )"
}

# 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/doc/$pkg"
		infodir="$root/usr/info"
		mandir="$root/usr/man"
	else
		datadir="$root/$prefix/share"
		includedir="$root/$prefix/include"

		docdir="$root/$prefix/doc/$pkg"
		infodir="$root/$prefix/info"
		mandir="$root/$prefix/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 ] ; 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
			if grep AM_INIT_AUTOMAKE configure.in
				then automake ; 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 $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_status "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
}

# 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,\],,;'`"
	for tag in $tag ; do
		tagdata="`egrep "^\[($tag)\]" $confdir/$1.desc | \
		          cut -f2- -d']' | sed 's,^ ,,'`"
		tag="`echo $tag | cut -f1 -d'|' | tr - _`"
		eval "desc_$tag=\"\$tagdata\""
	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 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 $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 "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_c_bigendian=$arch_bigendian"
	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-$pkg.err
	echo_errorquote "`cat $root/var/adm/logs/$stagelevel-$pkg.err`"
	echo_pkg_abort $stagelevel $repository $pkg
	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 = 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 for a package in configuration
#
pkgcheck() {
        egrep -q "^$2.* ($1) " $base/config/$config/packages
}
# Check if a package is already installed
#
pkginstalled() {
	[ -f $root/var/adm/flists/$1 ]
}

# 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 an application
#
register_application() {
	[ -e /usr/share/rock-registry/app ] \
		|| mkdir -p /usr/share/rock-registry/app
	echo -e "name=\"$2\"\nexec=\"$3\"\n" > /usr/share/rock-registry/app/$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() {
	rm -f $3.tmp
	for file in $( ls -dr $1/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' \
                                $1/packages/$pkg | cut -f6 -d' ')
		else
			v=""
		fi
		if [ "$ROCKCFG_CREATE_GEM" = 1 ] ; then
			bfile=${pkg}${v}.gem
		else
			bfile=${pkg}${v}.tar.bz2
		fi

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

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

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

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

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

			  echo -e "\004"
			) >> $3.tmp
		else
			echo_error "Binary file for $bfile not present." \
			           "Skipped in package database."
		fi
	done
	gzip -c $3.tmp > $3 ; rm -f $3.tmp
}

# 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
        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 '$pkg'!"
				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
		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 \
							   "`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 $docdir $root/$prefix/bin $root/$prefix/lib \
				 $root/$prefix/share $sysconfdir $localstatedir
			do
				if [ ! -e $x ]; then
					mkdir -p $x
					rmemptydir="$rmemptydir $x"
				fi
			done
		fi
		
		if [ ".$custmain" = "." ]
		then

			# Run configure scripts etc.
			#
			hook_eval preconf
			#
			if [ $runconf = 1 ]; then 
			  if [ -f $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
					perl Makefile.PL
				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

		for file in $confdir/*.desktop ; do 
			[ -f $file ] || continue
	
			echo -n "Install desktop file '$file': "

			mkdir -p $root/usr/share/rock-registry/app

			rock_substitute $file > \
			  $root/usr/share/rock-registry/app/`basename $file`
		done

		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
	done
  
	if [ "$rmemptydir" ]; then
		rmdir $rmemptydir 2> /dev/null || true
	fi

	return 0
}