#!/bin/sh -T
#
# (c) Copyright (c) 2006, Diomidis Spinellis. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# Monitor the progress of the specified command
#
# For each file the specified command is reading, display the percentage
# that has been read.  This command is modelled after a similar facility
# available on Permin-Elmer/Concurrent OS32
#
# Requires:
# - asynchronous trap notification (zsh -T extension)
# - lsof(8) with offset (-o) printing functionality
# - stat(1) (or substitute ls(1) with appropriate output parsing)
# - SIGINFO signal (or substitute another signal name)
#
# Tested under FreeBSD 4.11, FreeBSD 6.0, and FreeBSD 6.3
#
# $Id: monitor-freebsd.sh,v 1.1 2008/10/27 12:18:16 dds Exp $
#

CMD=$1

trap display SIGINFO

display()
{
	# Get the PID of the executed command
	if [ -z "$PID" ]
	then
		PID=`ps -o ppid,pid,command |
		     awk '$1 == '$$' && $3 == "'$CMD'" {print $2}'`
	fi
	# Obtain the offset and print it as a percentage
	/usr/local/sbin/lsof -o0 -o -p $PID |
	    awk '
		BEGIN { CONVFMT = "%.2f" }
		$4 ~ /^[0-9]+r$/ && $7 ~ /^0t/ {
			offset = substr($7, 3)
			fname = $9
			"stat -f %z '\''" fname "'\''" | getline
			len = $0
			print fname, offset / len * 100 "%"
		}
	' 1>&2
}

# Execute the specified command
$@

