#!/bin/bash
# vim:set et ts=4 sw=4 ft=bash ai:

# WARNING: This script works only for main (no contrib)

ARCHIVE='local'
SUITES="sid"
ARCHES="amd64 i386"

REPOSITORY='/org/ftp.debian.org/ftp/apt/dists'

. common

# Redirect the output to a log file
#exec >> /org/wanna-build/db/merge.$ARCHIVE.log 2>&1

if [ ! -d $REPOSITORY ]
then
	echo "Could not find repository $REPOSITORY"
	exit 1
fi

if [ -f /org/wanna-build/NO-TRIGGERS ]
then
	echo Trigger for $ARCHIVE skipped due to NO-TRIGGERS, aborting. >&2
	exit 0
fi

echo "`date`: Running trigger for $ARCHIVE ..."

fetch() {
	src="$1"
	dest="$2"

	if [ -f "$src" ]
	then
		mkdir -p "$dest"
		cp "$src" "$dest"
	fi
}

main() {
	set -eE
	trap cleanup ERR TERM HUP INT QUIT

	ensure_lock
	ensure_workdir

	# Fetch the most recent Packages and Sources files.
	for suite in $SUITES
	do
		fetch "$REPOSITORY/$suite/main/source/Sources.gz" "$ARCHIVE_BASE/archive/$suite/main/source/"
		#fetch "$REPOSITORY/$suite/contrib/source/Sources.gz" "$ARCHIVE_BASE/archive/$suite/contrib/source/"

		for arch in $ARCHES
		do
			fetch "$REPOSITORY/$suite/main/binary-$arch/Packages.gz" "$ARCHIVE_BASE/archive/$suite/main/binary-$arch/"
			#fetch "$REPOSITORY/$suite/contrib/binary-$arch/Packages.gz" "$ARCHIVE_BASE/archive/$suite/contrib/binary-$arch/"
		done
	done

	for suite in $SUITES
	do
		SOURCES="Sources.$suite.incoming-filtered.gz"
		filter_out_nonfree "$ARCHIVE_BASE/archive/$suite/main/source/Sources.gz" "$SOURCES"
		PACKAGES="$ARCHIVE_BASE/archive/$suite/main/binary-%ARCH%/Packages.gz"
		trigger_wb_update "$suite" "$ARCHES" "$SOURCES" "$PACKAGES"
	done

	cleanup
}

main
exit 0

