#!/bin/bash

REMOTE="softwareheritage@gitorious.org"
REMOTE_SRC="/dev/nbd0"
LOCAL_DEST="gitorious.img"

# bytes; for "dd bs="
BLOCK_SIZE=1M

# bytes/second; for "pv --rate-limit"
RATE_LIMIT=3M

if [ "$1" = "-h" -o "$1" = "--help" ] ; then
    echo "Usage: $0 [OFFSET] [DD_OPTIONS...]"
    echo "E.g.:  $0 1T"
    echo "       $0 1T count=42  # note: bs=${BLOCK_SIZE} is fixed"
    shift
    exit 0
fi

dd_flags="bs=${BLOCK_SIZE} iflag=fullblock"
dd_in_flags="${dd_flags} if=${REMOTE_SRC}"
dd_out_flags="${dd_flags} of=${LOCAL_DEST}"

if [ -n "$1" ] ; then
    offset="$1"
    shift
    dd_in_flags="${dd_in_flags} skip=${offset} $*"
    dd_out_flags="${dd_out_flags} seek=${offset} $*"
fi

echo "IN:  dd ${dd_in_flags} <- ${REMOTE_SRC}"
echo "OUT: dd ${dd_out_flags} -> ${LOCAL_DEST}"

ssh "$REMOTE" \
    "dd $dd_in_flags | nice lz4 -c | pv --rate-limit ${RATE_LIMIT} --quiet" \
    | lz4 -dc | pv | dd $dd_out_flags
