#!/bin/sh -efu

arch="$1"; shift

. gb-sh-functions

. shell-quote

comps="$(set +f && cd "$GB_TMP_REPO_DIR/$arch" && ls -d RPMS.?* |
	sed 's/^RPMS\.//' | tr -s '[:space:]' ' ')"
[ -n "$comps" ]

# Prepare remote node for $arch install check.
# Note that now we use $remote_host:gb-repo, not $GB_REPO_DIR.
cp -f "$GB_REPO_SOURCES" "$GB_HOME/remote/apt/sources-$GB_REPO_NAME.list"
gb-x-rsync-loop -a "$GB_HOME/remote/" "$remote_host:"
remote_home=$(ssh "$remote_host" pwd)
gb-x-ssh "$remote_host" ./gb-remote-plant \
	"\"$(quote_shell "$(cat task/owner)")\"" \
	"\"$(quote_shell "$GB_REPO_NAME")\"" \
	"\"$(quote_shell "$remote_home/apt/sources-$GB_REPO_NAME.list")\"" \
	"\"$(quote_shell "$GB_REPO_FLAVOUR")\"" \
	"\"$(quote_shell "$GB_NPROCS")\"" \
	"\"$(quote_shell "$remote_home/gb-repo")\"" \
	"\"$(quote_shell "$arch")\"" \
	"\"$(quote_shell "$comps")\"" \
	"\"$(quote_shell "$GB_APT_CACHE_LIMIT")\"" \
	cache_dir=cache.check-install

# Copy the temporary repo generated by gb-task-gen-testrepo.
gb-x-rsync-loop -a --exclude '*list.*.bz2' \
	"$GB_TMP_REPO_DIR"/{$arch,noarch} "$remote_host:gb-repo/"

rc=0

while read -r N EVR A F P I; do
	[ "$A" = "$arch" -o "$A" = 'noarch' ] || continue

	if [ -f task/swift ]; then
		if [ -f "install/$N/$arch/chroot_install" ]; then
			stamp_echo >&2 "[$arch] #$I $N: install check swiftly skipped"
			continue
		fi
	fi

	if [ -f task/abort ]; then
		stamp_echo >&2 "[$arch] #$I $N: install check ABORTED"
		rc=1
		break
	fi

	# copy install chroot identification to remote side
	(umask 002; mkdir -p "install/$N/$arch") || false
	gb-x-rsync-loop -qrlt --delete -- "install/$N/$arch/" "$remote_host:install/"

	if gb-x-ssh "$remote_host" ./gb-remote-check-install \
	       "$GB_REPO_NAME" "$arch" "$N" "$EVR" "$A" "$F" "$I" </dev/null; then
		# copy install chroot identification from remote side
		gb-x-rsync-loop -qrlt --delete -- "$remote_host:install/" "install/$N/$arch/"
	else
		rm -rf "install/$N/$arch"
		stamp_echo >&2 "[$arch] #$I $N: install check FAILED"
		rc=1
	fi
done <plan/add-bin

# Purge temporary repo.
gb-x-rsync-loop -a --delete /var/empty/ "$remote_host:gb-repo/"

exit $rc
