#!/bin/sh
#
# Author: Emmanuel VARAGNAT
# Site:   http://www.guzu.net
#

if [ $# -ne 2 ]; then
	echo "USAGE: $0 <file or block device> <image file prefix>"
	echo "USAGE:  the <image file> must have a extension comatible with convert (from ImageMagick)"
	echo "USAGE:  Example: $0 /dev/hda2 /tmp/blockbmp"
	exit
fi

DEV=$1

dumpe2fs $DEV > /dev/null 2>&1
if [ $? -eq 1 ]; then
	echo "ERROR: $DEV doesn't seems to contain a ext2 or ext3 filesystem" 
	exit
fi

if [ -e "$2" ]; then
	echo "ERROR: $2 already exists; can't overwrite"
	exit
fi


WIDTH=1024

BLOCKSIZE=$(dumpe2fs $DEV 2> /dev/null | grep "^Block size:" | sed 's/^.*[[:space:]]\([0-9]*\)$/\1/')

TMPFILE="$2.$(date '+%s')"

dumpe2fs $DEV 2> /dev/null | \
	grep "Block bitmap" | \
	sed 's/^.*Block bitmap at \([0-9]*\)[[:space:]].*$/\1/' | \
	while read BLOCK; do
	       	dd if=$DEV bs=$BLOCKSIZE count=1 skip=$BLOCK 2> /dev/null >> "$TMPFILE"
     	done

SIZE=$(( $(cat "$TMPFILE" | wc -c) * 8 ))

(
echo "#define blocks_width $WIDTH"
echo "#define blocks_height $(( $SIZE / $WIDTH ))"
echo "static unsigned char blocks_bits[] = {"
od -t x1 --width=10 -A n -v "$TMPFILE" | sed 's/[[:space:]]\([[:xdigit:]]\{2\}\)/ 0x\1,/g' | sed '$s/,$//'
echo "};"
) | convert - "${TMPFILE}.png"

rm -f "${TMPFILE}"


