#!/bin/sh
# Portable rsync wrapper with duration and transfer statistics.

set -eu

if [ "$#" -lt 2 ]; then
    echo "Usage: $0 SOURCE DESTINATION [rsync-options...]"
    echo "Example: $0 /data/source/ user@host:/data/target/"
    exit 1
fi

SOURCE=$1
DESTINATION=$2
shift 2

LOGFILE=$(mktemp "${TMPDIR:-/tmp}/rsync-sync.XXXXXX")
START_TS=$(date +%s)

echo "Starting rsync..."
echo "Source:      $SOURCE"
echo "Destination: $DESTINATION"
echo "Options:     ${@:-<none>}"
echo

LC_ALL=C rsync \
    -aHAXx \
    --numeric-ids \
    --info=progress2 \
    --stats \
    "$@" \
    "$SOURCE" "$DESTINATION" | tee "$LOGFILE"

RSYNC_STATUS=${PIPESTATUS:-0}

END_TS=$(date +%s)
DURATION=$((END_TS - START_TS))

echo
echo "Summary"
echo "-------"
printf "Duration: %02d:%02d:%02d\n" \
    $((DURATION / 3600)) \
    $(((DURATION % 3600) / 60)) \
    $((DURATION % 60))

awk '
/^Number of files:/ {
    print "Number of files: " $0
}
/^Number of regular files transferred:/ {
    print $0
}
/^Total file size:/ {
    print $0
}
/^Total transferred file size:/ {
    print $0
}
/^Literal data:/ {
    print $0
}
/^Total bytes sent:/ {
    print $0
}
/^Total bytes received:/ {
    print $0
}
' "$LOGFILE"

rm -f "$LOGFILE"

exit "$RSYNC_STATUS"
