#!/bin/sh

isTest() { # {{{1
	[[ ! -z "$isTest" ]]
}

cd() { # {{{1
	builtin cd "$@"
	if isTest ; then
		if [[ $OLDPWD != $PWD ]]; then
			echo cd "$PWD"
		fi
	fi
}

getOutputDir() { # {{{1
	valueof "$1"OutputDir
}

getSubdirs() { # {{{1
	pushd "$1" >/dev/null 2>&1
	local dir
	for dir in *; do
		[[ -d $dir ]] && echo "$dir"
	done
	popd >/dev/null 2>&1
}
# }}}

getExtVersions() { # {{{1
	local ext=$1
	local len=${#ext}
	local dir
	((len=len+1))
	getSubdirs "$topdir/$1" | while read dir; do
		echo ${dir:$len}
	done
}

loadExt() { # {{{1
	ext="$1"
	extDir="$topdir/$ext"

	phpVersions=("${phpVersions[@]}")
	extVersions=($(getExtVersions "$ext"))

	configFile="$extDir/.config"
	if [[ ! -f $configFile ]]; then
		die "$configFile not found"
	fi
	. "$configFile"
	unset configFile
}

foreachExt() { # {{{1
	local ext
	for ext in "${exts[@]}"; do (
			loadExt "$ext"
			"$@"
	); done
}

loadExtVersion() { # {{{1
	extVersion="$1"
	extDirVersioned="$topdir/$ext/$ext-$extVersion"
	configFile="$extDirVersioned/.config"
	if [[ -f $configFile ]]; then
		. "$configFile"
	fi
	unset configFile
}

foreachExtVersion() { # {{{1
	local extVersion
	for extVersion in "${extVersions[@]}"; do (
			loadExtVersion "$extVersion"
		"$@"
	); done
}

loadPhpVersion() { # {{{1
	phpVersion="$1"
	phpSourcePackage="$sourceDir/php-$phpVersion.tar.bz2"
	develDirVersioned="$develDir/php-$phpVersion"
}

foreachPhpVersion() { # {{{1
	local phpVersion
	for phpVersion in "${phpVersions[@]}"; do (
		loadPhpVersion "$phpVersion"
		"$@"
	); done
}
foreachPhpReleaseVersion() { # {{{1
	local arch
	local compiler
	local nts
	local phpReleaseVersion
	local phpReleaseDir

	for nts in '' '-nts'; do
		case "$phpVersion" in
		4.*|5.0.*|5.1.*)
			phpReleaseVersion="php-$phpVersion-Win32"
			phpReleaseDir="$develDir/$phpReleaseVersion"
			arch=x86
			compiler=VC6
			nts=
			"$@"
			break
			;;
		*)
			for compiler in "${compilers[@]}"; do
				for arch in "${arches[@]}"; do
					phpReleaseVersion=php-$phpVersion$nts-Win32-$compiler-$arch$snapVersion
					phpReleaseDir="$develDir/$phpReleaseVersion"
					phpReleaseFile="$sourceDir/$phpReleaseVersion"
					if [[ -d $phpReleaseDir || -f $phpReleaseFile ]]; then
						"$@"
					fi
				done
			done
		esac
	done
}
# }}}
