#!/bin/bash
#This script will create a DMG disk to contain the package
#EasyQuantis to be distributed.
#
#The script has 2 parameter
#    1) the name of a directory containing the exact image 
#       of the data to be put in the DMG disk.
#    2) the name of the directory which will contain the image dmg

#To debug, uncomment the following line.
#set -x

#Name of the disk created
typeset -r DISK_NAME="EasyQuantis"

if [[ $# -ne 2 ]]
then
     echo "$0 InstallDir ImageDir"
     echo ""
     echo "Create a dmg disk and copy the content of the directory"
     echo "given as the first argument inside it. The disk image will be put in"
     echo "the directory \"ImageDir\"."
     echo ""
     exit 1
fi

typeset -r DirName="$1"
typeset -r ImageDir="$2"
typeset -r cmdLog="/tmp/${0##*/}.$$" #All except what is before the last /

if [[ ! -r "${DirName}" ]]
then
   echo "The file \"${DirName}\" can not be read"
   exit 2
fi

typeset dataSize=$(du -ks "${DirName}" | cut -f 1,1)

#To have some extra space in disk without decimal point
dataSize=$(echo "2 k $dataSize 1.2 * p" | dc | cut -d '.' -f 1,1)

if [[ -e "${ImageDir}"/${DISK_NAME}.dmg.sparseimage ]] 
then
   hdiutil detach "${ImageDir}"/${DISK_NAME}.dmg.sparseimage > /dev/null 2>&1
   rm "${ImageDir}"/${DISK_NAME}.dmg.sparseimage
   rc=$?
   if [[ $rc -ne 0 ]]
   then
       echo "The file \"${ImageDir}/${DISK_NAME}.dmg.sparseimage\" can not be removed."
   fi
fi

hdiutil create -type SPARSE -size ${dataSize}k -fs HFS+J -volname ${DISK_NAME}  "${ImageDir}"/${DISK_NAME}.dmg
hdiutil attach "${ImageDir}"/${DISK_NAME}.dmg.sparseimage > "${cmdLog}" 2>&1
rc=$?
if [[ $rc -ne 0 ]]
then
   echo "The disk \"${ImageDir}/${DISK_NAME}.dmg.sparseimage\" can not be mounted. RC=$rc."
   rm -f "${cmdLog}"
   exit $rc
fi

typeset line=$(fgrep "${DISK_NAME}" "${cmdLog}")
typeset mountPoint="${line#*/Volumes/}" #Everything removed except what follows "/Volumes/"
typeset device="${line%% *}" #Remove everything after the first blank

find "${DirName}" -name \*.DS_Store\* -exec rm {} +

ditto "${DirName}" /Volumes/"${mountPoint}"

hdiutil detach "${device}"

rm -f "${cmdLog}"
