#!/bin/bash
#
#	makefsz /dev/device {fs.z|-} [blocks]
#
#	Compresses a filesystem image, suitable for use by the cramdisk
#	code in the kernel.
#
#	The idea here is that you build a filesystem on a small
#	partition, and then use this program to convert that partition
#	into an optimally compressed filesystem image.  This is done by
#	tarring the contents of the partition, wiping the partition
#	clean, untarring back onto the partition, and then dd'ing the
#	partition through gzip.
#
#	Specify the output file name, or `-' for stdout.
#	
#	The optional `blocks' parameter specifies the size of the
#	partition, 4Mb by default.
#
#	The default filesystem type is minix, because it has the least
#	overhead. However, if you want to use a different type (to get
#	atime/ctime/>14 char names, etc), just change the fstype variable
#	below.
#

fstype=minix

[ $# -lt 2 -o $# -gt 4 ] && {
	echo "Usage: `basename $0` /dev/device {fs.z|-} [blocks]"
	exit 1
}

[ ! -b "$1" ] && {
	echo "$1 is not a block device"
	exit 2
}

[ ! -d /mnt ] && {
	mkdir /mnt || {
		echo "couldn't create mount point /mnt"
		exit 3
	}
}

fs=$2
[ "$fs" = - ] && fs=

dir=`pwd`
blocks=${3:-4096}
inodes=${4:-1000}
mount -t $fstype $1 /mnt && {
	cd /mnt
	tar -cf /tmp/temp.tar --exclude lost+found . || {
		echo "couldn't tar files from $1"
		exit 4
	}
	cd /
	umount $1
	dd if=/dev/zero of=$1 bs=1024 count=$blocks
	mkfs.$fstype $1 -i $inodes $blocks 1>&2
	mount -t $fstype $1 /mnt
	cd /mnt
	tar -xpf /tmp/temp.tar
	rm /tmp/temp.tar
	cd $dir
	umount $1
	eval "dd if=$1 bs=1024 count=$blocks | gzip -9 ${fs:+>}$fs"
}
