#!/bin/sh
#
# Posted to the projectbuilder-users list by Mike Ferris
# Modified for vlc by Jon Lech Johansen
#

set -e

# Requires at least three args
if [ $# -lt 2 ] ; then
    echo "usage: $0 imgName dirName ..." 1>&2
    exit 1
fi

# Grab size and name
imgName=$1
shift
dirName=$1
shift

imgSize=`du -sk ${dirName} | cut -f1`
imgSize=$((${imgSize} / 1024 + 2))

if [ $((${imgSize} < 5)) != 0 ] ; then
    imgSize=5;
fi

# Create the image and format it
rm -f "${imgName}.dmg"
echo; echo "Creating ${imgSize} MB disk image named ${imgName}"
hdiutil create "${imgName}.dmg" -megabytes "${imgSize}" -layout NONE -quiet
dev=`hdid -nomount "${imgName}.dmg" | grep '/dev/disk[0-9]*' | cut -d " " -f 1`
/sbin/newfs_hfs -w -v "${imgName}" -b 4096 "${dev}" > /dev/null

# Mount the image and copy stuff
mkdir ./mountpoint
mount -t hfs ${dev} ./mountpoint

echo "Copying contents to ${imgName}:"
for i in ${dirName}/* ; do
    echo "  ${i}"
    /Developer/Tools/CpMac -r "${i}" ./mountpoint
done

umount ./mountpoint
rmdir ./mountpoint
hdiutil eject "${dev}" -quiet

# Compress the image
echo "Compressing ${imgName} disk image"
mv "${imgName}.dmg" "${imgName}.orig.dmg"
hdiutil convert "${imgName}.orig.dmg" -format UDZO -o "${imgName}" -quiet
rm "${imgName}.orig.dmg"

# Done
echo; echo "Disk image creation completed:"
ls -la "${imgName}.dmg"; echo
