#!/bin/bash
. scripts/common
. scripts/svn

packSource() {
	local args="$1"
	local suffix="$2"
	local file="$outputDir/$ext-$extVersion$rev$suffix"

	if [[ ! -f $file ]]; then
		pushd "$extDir" >/dev/null || die
		tar $VERBOSE --exclude tags --exclude .svn "$args" "$file.tmp" $ext-$extVersion || die
		popd >/dev/null
		mv "$file.tmp" "$file"
		md5sum "$file" | sed 's#/.*/##' > "$file.md5.txt"
	fi
}

packBinary() {
	local buildDirVersioned="$buildDir/$extNiceName-$extVersion-$phpReleaseVersion"
	[[ ! -d "$buildDirVersioned" ]] && return
	local output="$outputDir$rev/"
	local _TS=
	[[ ! -z $nts ]] && _TS=
	[[ -z $nts ]] && _TS=_TS
	local distDir="$buildDirVersioned/php/Release${_TS}"

	local -a files
	local binaryPackagePath="$outputDir/$extNiceName-$extVersion$rev-$phpReleaseVersion.zip"
	local debugPackagePath="$outputDir/$extNiceName-debug-pack-$extVersion$rev-$phpReleaseVersion.zip"
	if [[ ! -f $binaryPackagePath || ! -f $debugPackagePath ]]; then
		pushd "$buildDirVersioned/php" >/dev/null || die
		pushv file "Release${_TS}/php_$ext.dll"
		local i
		for i in "${packageFiles[@]}" ; do
			local f="$buildDirVersioned/$ext/$i"
			if [[ -e $f ]]; then
				dstdir="$distDir/"$(dirname "$i")
				if [[ ! -d $dstdir ]]; then
					mkdir -p "$dstdir"
				fi
				rm -rf "$distDir/$i"
				cp -a "$f" "$distDir/$i"
				pushv file "Release${_TS}/$i"
			fi
		done

		zip tmp.zip $(find "${files[@]}") || die
		mv tmp.zip "$binaryPackagePath"
		md5sum "$binaryPackagePath" > "$binaryPackagePath.md5.txt"

		zip tmp.zip "Release${_TS}/php_$ext.pdb"
		mv tmp.zip "$debugPackagePath"
		md5sum "$debugPackagePath" > "$debugPackagePath.md5.txt"
		popd >/dev/null
	fi
}

pack() {
	local prefix=
	if [[ -z $release ]]; then
		rev=-r$(svnRevOf $extDirVersioned)
		prefix="$snapshotOutputDir/$extVersion"
	else
		prefix="$releaseOutputDir/$extVersion"
	fi
	local outputDir="$prefix$rev"
	mkdir -p "$outputDir"

	packSource -jcf .tar.bz2
	packSource -zcf .tar.gz
	foreachPhpVersion foreachPhpReleaseVersion packBinary
	
	local files=$(shopt -s nullglob; echo "$prefix"*)
	if [[ ! -z $files ]]; then
		rm $VERBOSE -rf `ls -td $files | sed -n ${snapshotCount:-8}',$p'`
	fi
}

if [ `find build -iname php_xcache.dll -size 0 | wc -l` -gt 0 ] ; then
	echo "corrupt file built"
	find build -iname php_xcache.dll -size 0
	exit 1
fi

case $# in
0)
	foreachExt foreachExtVersion pack
	;;
1)
	loadExt "$1"
	foreachExtVersion pack
	;;
2)
	loadExt "$1"
	loadExtVersion "$2"
	pack
	;;
*)
	die "Usage: $0 [ext [extVersion]]"
	;;
esac
