#!/bin/sh
# $Id$

function stats {
	et=`date +%s`
	dt=`expr $et - $st`
	if [ $c -ne 0 -a $dt -ne 0 ] ; then
		mib=`expr $c \* 64`
		echo "dumped $c segments (${mib}Mib) in $dt seconds (`expr $mib / $dt` Mib/sec)" 1>&2
	fi
}

function dump {
	while read no ; do
		if [ "$no" = eol ] ; then
			stats
			break
		fi
		printf 'dumping %d...\r' $no 1>&2 ; echo $no ; dd if=$dn bs=8M count=1 skip=$no 2> /dev/null ; c=$((c+1))
	done | lzop | nc -l neo 8098
}

dn=`findfs LABEL=CYCLOPS`
fnxt=/root/nilfs-backup.next

nn=`dumpseg $dn $no | head -2 | tail -1 | sed 's:.* next segnum = ::'`

date
st=`date +%s`
c=0
if [ "$1" = full ] ; then
	ne=`lssu | grep '[0-9]  ad-' | sed -e 's:^ *::' -e 's: .*::'` ; echo -n $ne > $fnxt
	echo dumping segments up to $ne... 1>&2
	( echo 0 ; lssu | grep '[0-9]  [a-]d- ' | sed -e 's:^ *::' -e 's: .*::' ; echo eol ) | dump
elif [ "$1" = incr -a -f $fnxt ] ; then
	no=0
	nn=`cat $fnxt`
	ne=`lssu | grep '[0-9]  ad-' | sed -e 's:^ *::' -e 's: .*::'` ; echo -n $ne > $fnxt
	echo dumping segments from $nn to $ne... 1>&2
	while true ; do
		echo $no
		no=$nn
		if [ $no -eq $ne ] ; then
			echo $no
			echo eol
			break
		fi
		nn=`dumpseg $dn $no | head -2 | tail -1 | sed 's:.* next segnum = ::'`
		if [ `echo $nn | grep -c segment` -ne 0 ] ; then
			echo eol
			break
		fi
	done | dump
else
	echo 'usage: $0 {full|incr}'
fi
date
