#!/bin/sh
# Hands a repomon job's artifacts back to the machine running release.fish
# -- repomon has no artifact-return channel of its own (each job's workspace
# is deleted immediately on completion), so this is a plain scp to a staging
# path that dispatch-remote-builds.fish polls, same pattern as
# windows-handoff.ps1.
#
# Shared by every non-Windows release.toml job (linux-build-x86_64,
# linux-build-aarch64, macos-build) *and* audit.toml's audit job -- each
# passes its own filenames as arguments, since the scp target and logic are
# identical across all of them and only the file list differs. audit.toml
# passes a single bare "audit.ok" marker file rather than a real build
# artifact; this script doesn't care either way.
#
# Each file is scp'd to a `.partial` suffix, then atomically mv'd into its
# final name via a script piped into `ssh ... sh -s`. Plain `scp foo "$dest"`
# creates the destination file and starts streaming into it immediately, so
# dispatch-remote-builds.fish's `test -f`-based poll (rel_wait_for_files in
# lib.fish) can observe and hand off a partially-written file if it lands
# mid-transfer. The rename is a same-filesystem mv (atomic), so the poller
# never sees the final name until every byte has landed.
#
# The rename script is piped to `sh -s` over stdin rather than passed as an
# `ssh host "..."` command string -- jozias@jasonozias.com's login shell is
# fish, and ssh hands a command-string argument straight to the login shell,
# so POSIX syntax like `set -e` would be misparsed as fish's own
# (incompatible) `set -e VARNAME`. `sh -s` sidesteps the login shell
# entirely.
#
# mkdir -p's $dest_dir itself before scp'ing, rather than assuming
# dispatch-remote-builds.fish's own `mkdir -p $staging_dir` already ran: that
# script only creates the directory as a side effect of *it* being the one
# that pushes the release tag. If the tag is ever pushed directly instead
# (bypassing `cargo rake release`), every job here would otherwise fail scp
# with "No such file or directory" -- this happened on the first real
# v0.4.6-rc.1 test push. Idempotent and harmless when the directory already
# exists.
set -eu

tag=$(git describe --tags --exact-match)
host="jozias@jasonozias.com"
dest_dir="/opt/releases/cargo-matrix/staging/$tag"

ssh "$host" mkdir -p "$dest_dir"

for f in "$@"; do
    scp "$f" "$host:$dest_dir/$f.partial"
done

{
    echo "set -e"
    for f in "$@"; do
        printf 'mv -- "%s/%s.partial" "%s/%s"\n' "$dest_dir" "$f" "$dest_dir" "$f"
    done
} | ssh "$host" sh -s
