#!/bin/sh
# Script copyright (c) 2008 Shane Mc Cormack
# libDMG from: http://github.com/planetbeing/libdmg-hfsplus
#
# This script will:
#  - Download libdmg from the git repo
#  - Patch it not to include a master checksum (otherwise OSX complains)
#  - Compiles dmg
#  - Copies the resulting dmg binary to the current directory
THISDIR=${PWD}
THISFILE=${THISDIR}/${0}

GIT=`which git`

if [ "" = "${GIT}" ]; then
	echo "You need to have git installed to use this script"
	exit 1;
fi;

if [ -e "libdmg-hfsplus/.git" ]; then
	echo "git repo checkout already exists"
	cd libdmg-hfsplus
	echo "Removing previously patched version"
	rm dmg/dmglib.c nomasterchecksum.patch dmg/dmglib.c.rej
	git checkout dmg/dmglib.c
	echo "Updating git repo"
	git fetch
	git rebase origin
else
	echo "git repo checkout does not exist"
	if [ -e "libdmg-hfsplus" ]; then
		echo "non-git version found, deleteing"
		rm -Rf libdmg-hfsplus
	fi;
	echo "Checking out git repo"
	git clone git://github.com/planetbeing/libdmg-hfsplus.git
	cd libdmg-hfsplus
fi;
echo "Extracting Patch"
STARTLINE=`grep -n "^#### PATCH FILE BELOW ####$" ${THISFILE}`
STARTLINE=$((${STARTLINE%%:*} + 1))
tail -n +${STARTLINE} ${THISFILE} > nomasterchecksum.patch
echo "Patching"
patch -f -p0 < nomasterchecksum.patch
if [ -e dmg/dmglib.c.rej -o ${?} -ne 0 ]; then
	echo "Patching failed"
	exit 1;
fi;
echo "Building"
cd dmg
make
echo "Copying"
cp -Rfv dmg ${THISDIR}/dmg
echo "Done."
exit 1;
#### PATCH FILE BELOW ####
diff -Pur dmg/dmglib.orig dmg/dmglib.c
--- dmg/dmglib.orig	2008-06-09 09:29:11.000000000 +0100
+++ dmg/dmglib.c	2008-06-09 09:30:01.000000000 +0100
@@ -232,10 +232,10 @@
 	koly.fUDIFXMLLength = plistSize;
 	memset(&(koly.reserved1), 0, 0x78);
 	
-	koly.fUDIFMasterChecksum.type = CHECKSUM_CRC32;
+	koly.fUDIFMasterChecksum.type = CHECKSUM_NONE;
 	koly.fUDIFMasterChecksum.size = 0x20;
 	koly.fUDIFMasterChecksum.data[0] = calculateMasterChecksum(resources);
-	printf("Master checksum: %x\n", koly.fUDIFMasterChecksum.data[0]); fflush(stdout); 
+	printf("Master checksum: Disabled\n"); fflush(stdout); 
 	
 	koly.fUDIFImageVariant = kUDIFDeviceImageType;
 	koly.fUDIFSectorCount = EXTRA_SIZE + (volumeHeader->totalBlocks * volumeHeader->blockSize)/SECTOR_SIZE;
@@ -447,10 +447,10 @@
 	koly.fUDIFXMLLength = plistSize;
 	memset(&(koly.reserved1), 0, 0x78);
 	
-	koly.fUDIFMasterChecksum.type = CHECKSUM_CRC32;
+	koly.fUDIFMasterChecksum.type = CHECKSUM_NONE;
 	koly.fUDIFMasterChecksum.size = 0x20;
 	koly.fUDIFMasterChecksum.data[0] = calculateMasterChecksum(resources);
-	printf("Master checksum: %x\n", koly.fUDIFMasterChecksum.data[0]); fflush(stdout); 
+	printf("Master checksum: Disabled\n"); fflush(stdout); 
 	
 	koly.fUDIFSectorCount = numSectors;
 	koly.reserved2 = 0;
