#!/bin/bash

# Todo: Avoid moving packages into the wrong repo (e.g. kernel26 to [extra]
# Todo: Try using svnmerge instead of svn mv

exit 1

cmd=`basename $0`

if [ "$cmd" == "testing2core" ]; then
	repo="core"
	carch='i686'
	post=""
elif [ "$cmd" == "testing2extra" ]; then
	repo="extra"
	carch='i686'
	post=""
elif [ "$cmd" == "testing2core64" ]; then
	repo="core"
	carch='x86_64'
	post="64"
elif [ "$cmd" == "testing2extra64" ]; then
	repo="extra"
	carch='x86_64'
	post="64"
fi

if [ $# -lt 1 ]; then
	echo "Usage: ${cmd} package1 [package2] [package3] [...]"
	exit 0
fi

if [ -f "/tmp/${cmd}.lock" ]; then
	echo "Error: ${cmd} allready in progress."
	exit 1
fi

touch "/tmp/${cmd}.lock" || exit 1
TMPDIR=$(mktemp -d /tmp/${cmd}.XXXXXX) || exit 1

showError() {
	echo "Error: $1"
	rm -rf ${TMPDIR}
	rm -f "/tmp/${cmd}.lock"
	exit 1
}

cd ${TMPDIR}

for i in "$@"; do
	[ "$i" == "$0" ] && continue
	echo "Processing ${i}..."
	svn co "/home/svn-packages/${i}"

	if [ -f "${i}/repos/testing-${carch}/PKGBUILD" ]; then
		cd "$i"
		source "repos/testing-${carch}/PKGBUILD"
		pkgfile=${pkgname}-${pkgver}-${pkgrel}-${carch}.pkg.tar.gz

		[ ! -f "/home/ftp/testing/os/${carch}/${pkgfile}" ] && showError "$i is not in [testing]"
		[ -f "/home/ftp/${repo}/os/${carch}/${pkgfile}" ] && showError "$i is allready in [${repo}]"
		[ -f "~/staging/testing${post}/del/${pkgfile}" ] && showError "$i is allready in ~/staging/testing${post}/del"
		[ -f "~/staging/${repo}${post}/add/${pkgfile}" ] && showError "$i is allready in ~/staging/${repo}${post}/add"

		echo "Moving ${pkgfile} from [testing] to [${repo}]"
		cp /home/ftp/testing/os/${carch}/${pkgfile} ~/staging/testing${post}/del
		mv /home/ftp/testing/os/${carch}/${pkgfile} ~/staging/${repo}${post}/add

# 		cd "repos/testing-${carch}"
# 		svnmerge merge "../repos/${repo}-${carch}"
# 		cd ..
# 		svn rm "repos/testing-${carch}"
# 		if [ -f trunk/svnmerge-commit-message.txt ]; then
# 			svn commit -F trunk/svnmerge-commit-message.txt
# 			rm trunk/svnmerge-commit-message.txt
# 		else
# 			echo "Nothing to commit"
# 		fi

		[ -d "repos/${repo}-${carch}" ] && svn rm "repos/${repo}-${carch}"
		svn mv -r HEAD "repos/testing-${carch}" "repos/${repo}-${carch}"
		svn commit -m "${cmd}: moved ${i} from [testing] to [${repo}] (${carch})"

		cd ../
	else
		showError "$i was not found in [testing] (${carch})!"
	fi
done

rm -rf ${TMPDIR}
echo "Updating package database..."
/arch/db-${repo}${post}
/arch/db-testing${post}

rm -f "/tmp/${cmd}.lock"