#!/bin/sh

function die
{
  echo "$1" >&2
  exit 1
}

function progress
{
  while [ -f "$DONEQFN" ] ;
  do
    sleep 1
    dd if="$DONEQ" bs=100M count=1 of=/dev/null
    TOT=$(($TOT + 100))
    echo -n "$TOT" >&2
    if [ "$MAX" != "unset" ] ; then
      echo -n " of $MAX" >&2
    fi
    echo "M transferred" >&2
    sleep 2
  done
}

DONEQFN=`mktemp || die "Cannot create temporary file"`
rm -f "$DONEQFN" 2>/dev/null
mkfifo "$DONEQFN" || die "Cannot create pipe $DONEQFN"
TOT=0
if [ "$1" != "" ] ; then
  MAX="$1"
else
  MAX="unset"
fi

progress &

tee "$DONEQFN"

rm -f "$DONEQFN"

echo "Done." >&2
exit 0
