#!/bin/sh -efu

arch="$1"; shift

. gb-sh-functions

. shell-quote
qvv() { quote_shell "$1=\"$(quote_shell "$2")\""; }

# Setup remote node to build $arch packages for $GB_REPO_NAME repository.
# Note that now we use $remote_host:gb-repo, not $GB_REPO_DIR (see below).
sed -e "s/@arch@/$arch/" "$GB_REPO_SOURCES" >"$GB_HOME/remote/apt/sources-$GB_REPO_NAME-$arch.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-$arch.list")\"" \
	"\"$(quote_shell "$GB_REPO_FLAVOUR")\"" \
	"\"$(quote_shell "$GB_NPROCS")\"" \
	"\"$(quote_shell "$remote_home/gb-repo")\"" \
	"\"$(quote_shell "$arch")\"" \
	"\"$(quote_shell "$GB_REPO_FLAVOUR")\"" \
	"\"$(quote_shell "$GB_APT_CACHE_LIMIT")\"" \
	"\"$(qvv rpmargs "$GB_REPO_RPMARGS")\""

# $GB_TMP_REPO_DIR has been generated by gb-task-gen-buildrepo already.
if [ -L "$GB_TMP_REPO_DIR" ]; then
	# Clever hack: simply change gb-repo symlink.  Note that we
	# do not want to pass $GB_REPO_DIR to remote-plant because
	# this is going to invalidate hasher's chroot cache.
	gb-x-ssh "$remote_host" rm gb-repo
	gb-x-ssh "$remote_host" ln -s "$GB_REPO_DIR" gb-repo
else
	# Need to copy.
	gb-x-rsync-loop -a "$GB_TMP_REPO_DIR"/{$arch,noarch} "$remote_host:gb-repo/"
fi

