#!/bin/bash

# easy_iso_crypt.sh - version 0.1, 28-Mar-2005
#
# (c) by Oliver Paukstadt <oliver@sourcentral.org> in 2005
# licensed under the Terms of GPL v2 or Artistic License
#
# use at your own risk

ISODIR=/my/data		# Directories for iso
MAXSIZE=$(( 4700 *2 ))k	# Number of 512 blocks (can you see the k? ;-)
ISO=/var/tmp/image.iso	# name of the iso image (enough space needed there!)
CRYPT="-s256 -c aes"	# Options for cryptsetup
MAPPER="crypt1"		# Name for mapped volume
MKISOFS="-allow-leading-dots -l -J -r"
			# Options for mkisofs
exit			# remove this line

unset LANG		# we need C output for parsing
LOOP=""			# determine free loop device
for i in /dev/loop* ; do
  losetup $i >/dev/null 2>&1 
  if [ $? -eq 1 ] ; then LOOP=$i ;break ; fi
done
if [ -z "$LOOP" ] ; then 
  echo "no free loop device" >&2
  exit
fi

dd if=/dev/urandom of=$ISO bs=512 count=2048
dd if=/dev/urandom of=$ISO bs=512 count=1 seek=$MAXSIZE

losetup $LOOP $ISO
cryptsetup $CRYPT luksFormat $LOOP
cryptsetup luksOpen  $LOOP $MAPPER

SIZE=`mkisofs $MKISOFS $ISODIR | dd of=/dev/mapper/$MAPPER bs=512 2>&1 | grep "records out" | cut -f1 -d+`
SIZE_VOL1=`blockdev --getsize /dev/mapper/$MAPPER`
SIZE_LOOP=`blockdev --getsize $LOOP`
dmsetup remove $MAPPER
losetup -d $LOOP

SIZE=$(( $SIZE + ($SIZE_LOOP - $SIZE_VOL1) ))
dd if=$ISO of=$ISO bs=512 count=0 skip=$SIZE seek=$SIZE


echo "Do the following commands to test the image:"
echo "  losetup $LOOP $ISO"
echo "  cryptsetup -r luksOpen  $LOOP $MAPPER"
echo "  mount  /dev/mapper/$MAPPER /media/cdrom"
echo "or burn $ISO using your favorite tool" 

