#!/bin/sh 
# ddprogress - show dd progress every 3 seconds
# Copyright (C) 2008 Lucio Crusca <lucio@sulweb.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# getddpid
# outputs a string containing the pid of the dd process.
function getddpid
{
  DDSTARTED=""
  while [ "$DDSTARTED" != "0" ] && [ -f "$CANARY" ] ;
  do
    ddpid=`ps --ppid $mypid -o pid=`
    DDSTARTED="$?"
  done

  # now we should have two pids in $ddpid, one is the
  # background portion of this script (you are reading
  # it just now) and the other is dd. We have to choose
  # dd...

  for tempid in $ddpid ; 
  do
    WRONGPID=`ps -p $tempid -o comm= | grep "$mybasename" | wc -l`
    if [ $WRONGPID -eq 0 ] ; 
    then
      ddpid=$tempid
    fi
  done

  echo $ddpid
}

# showprogress
# sends USR1 signals to dd every 3 seconds
function showprogress
{
  pid=`getddpid`
  if [ "$pid" != "" ] ; 
    then
      while ( ps -p $pid > /dev/null ) && [ -f "$CANARY" ] ; 
        do
          sleep 3
	  currentpid=`ps -p "$pid" -o pid=`
          kill -USR1 $currentpid 2> /dev/null
        done
  fi  
}

# we need our pid in order to find our child dd's pid
mypid=$$
mybasename=`basename "$0"`

# dd must be executed in foregroud in order to keep stdin & stdout, so
# we start the progress stats loop in background. We use a canary
# to signal time to stop
CANARY=`mktemp`
showprogress &

# we finally start dd with any and all the arguments on the command line
dd $*

# we notify the background loop that dd has finished
rm -f "$CANARY"
