#!/bin/sh
# rsync-publish -- move a tree with rsync the way our publish/pull scripts always did,
# in ONE place: dry-run by default, a fixed safe flag set, ownership forced by the
# caller (never inherited from the local tree), and readable output -- only real
# changes, plus one live progress line per percent on --apply.
#
# Usage:
#   rsync-publish [--dry-run|-n|--apply] [--chown=USER:GROUP] [--<rsync-long-option>[=VALUE] ...] SRC DEST
#
#   SRC, DEST       exactly as rsync takes them: a local path or user@host:/path.
#                   A trailing slash on SRC means "contents of", as in rsync.
#   --dry-run, -n   THE DEFAULT. Nothing is written; the itemized list is what --apply
#                   would do. Read it for files you did not intend to send.
#   --apply         transfer for real; adds a live progress line (--info=progress2).
#   --chown=U:G     force this owner:group on every file that lands at DEST.
#   --<long>[=V]    every other LONG option goes to rsync verbatim, in order:
#                   --checksum, --perms, --exclude=PAT, --exclude-from=FILE,
#                   --files-from=FILE, --delete ... Use the --opt=VALUE form; the
#                   two-word form (--exclude PAT) is not understood.
#
# Always on:   --recursive --times --links --human-readable --itemize-changes
#              --mkpath --partial-dir=_partial
# Never added: --delete. Local deletions are not propagated unless the caller
#              passes --delete itself, visibly, on its own command line.
# REFUSED:     -a/--archive, -o/--owner, -g/--group, and any short option cluster.
#              These make rsync carry the LOCAL owner across. On a tree that is
#              the publisher here (uid 1000) and root-owned on the box, a real run of
#              `rsync -a` once stood to chown /etc/shadow, /etc/passwd, /etc/fstab
#              and the runit services on the target box to uid 1000 = its service user
#              (sync-to-live.sh, deleted 2026-09-20; only its dry-run had ever run).
#              Ownership at the destination is a decision the caller states with
#              --chown, or it is whatever the receiving login creates: never "same
#              as here".
#
# Exit status is rsync's, even though its output runs through a filter (a plain
# pipeline would return the filter's status and hide a dead host or a partial
# transfer from `set -e` callers).
#
# Callers: the rootfs publishers of two box families and their live-config puller. Change rsync
# behaviour HERE, not in the callers.

set -eu

usage() {
    sed -n '2,/^$/p' "$0" | sed 's/^# \{0,1\}//'
}

die() {
    echo "rsync-publish: $*" >&2
    exit 2
}

command -v rsync >/dev/null 2>&1 || die "rsync not found in PATH"

DRY=-n
PROG=
CHOWN=
SRC=
DEST=

# One pass over the arguments. Options we own set variables; every other long
# option is re-appended to "$@" so it reaches rsync as ONE word, spaces and globs
# intact (--exclude='* copy.yml' must survive). After the loop "$@" holds exactly
# the pass-through options, in their original order.
N=$#
I=0
while [ "$I" -lt "$N" ]; do
    ARG=$1
    shift
    I=$((I + 1))
    case "$ARG" in
        -n|--dry-run)   DRY=-n; PROG= ;;
        --apply)        DRY=;   PROG=--info=progress2 ;;
        -h|--help)      usage; exit 0 ;;
        --chown=?*:?*)  CHOWN=$ARG ;;
        --chown|--chown=*) die "--chown needs the form --chown=USER:GROUP" ;;
        --archive|--owner|--group)
                        die "$ARG refused: it would carry the LOCAL owner to the destination (see the header)" ;;
        --)             die "'--' is not supported; give SRC and DEST as the two non-option words" ;;
        --*)            set -- "$@" "$ARG" ;;
        -*)             die "short option '$ARG' refused: only long options, so nothing can smuggle -a/-o/-g in" ;;
        *)
            if   [ -z "$SRC" ];  then SRC=$ARG
            elif [ -z "$DEST" ]; then DEST=$ARG
            else die "too many non-option words: '$ARG' (SRC and DEST already given)"
            fi ;;
    esac
done
[ -n "$SRC" ] && [ -n "$DEST" ] || { usage >&2; die "SRC and DEST are required"; }

# Output filter: only actual changes (attribute-only and time-only itemize lines
# dropped) PLUS a live progress line each time the overall percentage ticks, so
# long pushes visibly move. rsync's progress updates are \r-separated; tr turns
# them into lines the filter can pass through (line-buffered via stdbuf where
# available, i.e. not busybox).
show_changes_and_progress() {
    if command -v stdbuf >/dev/null 2>&1; then
        stdbuf -oL tr '\r' '\n'
    else
        tr '\r' '\n'
    fi | awk '
        /^ /       { if ($2 != last) { last = $2; print }; next }  # progress2 line, dedup by %
        /^$/       { next }
        /^\.[fd]/  { next }                                        # attrs-only
        /^.f\.\.t/ { next }                                        # time-only
        { print }
    '
}

# rsync's exit status crosses the pipe via a file: the pipeline's own status is
# awk's, which is always 0.
STATUS_FILE=$(mktemp)
trap 'rm -f "$STATUS_FILE"' EXIT
echo 0 > "$STATUS_FILE"

{
    rsync ${DRY:+"$DRY"} \
        --recursive --times --links --human-readable --itemize-changes \
        --mkpath --partial-dir=_partial \
        ${PROG:+"$PROG"} ${CHOWN:+"$CHOWN"} \
        "$@" \
        "$SRC" "$DEST" || echo $? > "$STATUS_FILE"
} | show_changes_and_progress

read -r STATUS < "$STATUS_FILE"
exit "$STATUS"
