#!/bin/sh

[ $# -eq 4 -a x"$1" != x -a x"$2" != x -a x"$3" != x -a x"$4" != x ] || {
	1>&2 echo "$0: usage: $0 device mount_point type options"
	exit 1
}

cd / || exit

case X"$3" in
	Xext[23]|Xreiserfs)
		#normalize and make relative
		mount_point=`perl -e '$_=$ARGV[0];s|//+|/|og;s|^/||o;s|/$||o;s|^(.)|./$1|o;s|^$|.|o;print $_;' "$2"`

		#we use leading ./ (or bare .) with find to prevent pathname from
		#possibly looking like an option to find
		find "$mount_point" -xdev -depth -print0 |
		#strip unneded ^\./+
		perl -e '$/="\0";while(<>){chomp;s|^\./+([^/].*)$|$1|o;print "$_$/"}' |
		cpio -o -0 -H newc |
		gzip -9
	;;
	Xntfs|Xvfat|Xfat)
		dd if="$1" bs=512 |
		gzip -9
	;;
	*)
		1>&2 echo "$0: Don't know how to handle filesystem type $3"
		exit 1
	;;
esac
