#!/bin/sh
# vm-build.sh — rsync the Mountaineer-build repo into the builder VM,
# run ./build.sh inside it, copy artifacts back out to ./out/.
#
# Assumes the builder VM is running (./tools/qemu/vm-up.sh).

. "$(dirname "$0")/common.sh"

BUILDER_KEY="$KEYS_DIR/builder_ed25519"
REMOTE_PATH="${REMOTE_PATH:-/home/build/mountaineer-build}"

SSH_OPTS="-p $BUILDER_SSH_PORT \
    -i $BUILDER_KEY \
    -o StrictHostKeyChecking=accept-new \
    -o UserKnownHostsFile=$VMS/known_hosts \
    -o LogLevel=ERROR"

if [ ! -f "$BUILDER_KEY" ]; then
    echo "error: builder ssh key not found at $BUILDER_KEY" >&2
    echo "       run tools/qemu/vm-up.sh first" >&2
    exit 1
fi

# Sanity: is the VM reachable?
# shellcheck disable=SC2086
if ! ssh $SSH_OPTS -o ConnectTimeout=3 -o BatchMode=yes build@127.0.0.1 true 2>/dev/null; then
    echo "error: cannot reach builder VM at 127.0.0.1:$BUILDER_SSH_PORT" >&2
    echo "       start it with: tools/qemu/vm-up.sh" >&2
    exit 1
fi

echo "==> syncing repo into builder VM at $REMOTE_PATH"
# shellcheck disable=SC2086
rsync -az --delete \
    --exclude '.vms/' --exclude '.aports/' --exclude 'out/' --exclude '.work/' \
    -e "ssh $SSH_OPTS" \
    "$ROOT/" "build@127.0.0.1:$REMOTE_PATH/"

echo "==> running ./build.sh inside builder VM"
# shellcheck disable=SC2086
ssh $SSH_OPTS build@127.0.0.1 "cd $REMOTE_PATH && ./build.sh"

echo "==> copying artifacts back from builder VM"
mkdir -p "$ROOT/out"
# shellcheck disable=SC2086
rsync -az -e "ssh $SSH_OPTS" \
    "build@127.0.0.1:$REMOTE_PATH/out/" "$ROOT/out/"

echo "==> done. artifacts:"
ls -lh "$ROOT/out/"
