#!/bin/ksh

# MakeDMG.ksh
# Thu Jan  8 16:20:36 PST 2009
# Chieh Cheng
# http://www.CynosureX.com/

# GNU General Public License (GPL) Version 2, June 1991

  scriptName=`basename "$0"`

  createBucket ()
  {
    pos=0
    for content do
      bucket[${pos}]="${content}"
      pos=`expr ${pos} + 1`
    done
  }

  createDMG ()
  {
    diskName="${archiveName}.dmg.sparseimage"

    hdiutil create "${archiveName}.dmg" -volname "${archiveName}" -type SPARSE -fs HFS+ -size ${diskSize}m
    hdid "${diskName}"

    num=${#bucket[*]}
    pos=0

    while [ ${pos} -lt ${num} ]
    do
      content="${bucket[${pos}]}"
      if [ -e "${content}" ]
      then
        name=`basename "${content}"`
        ditto -rsrcFork "${content}" "${volume}/${name}"
      else
        echo "${content} does not exist!"
      fi
      pos=`expr ${pos} + 1`
    done

    hdiutil detach "${volume}"
    hdiutil convert "${diskName}" -format UDZO -o "${archiveName}.dmg" -imagekey zlib-devel=9
  }

  estimateDiskSize ()
  {
    total=0
    num=${#bucket[*]}
    pos=0

    while [ ${pos} -lt ${num} ]
    do
      if [ -e "${bucket[${pos}]}" ]
      then
        size=`du -k "${bucket[${pos}]}" | cut -d "	" -f 1`
        total=`expr ${total} + ${size}`
      fi
      pos=`expr ${pos} + 1`
    done

    mb=`expr ${total} / 1024 + 5`

    return ${mb}
  }

  usage ()
  {
    echo "  Usage: ${scriptName} \"archive name\" \"content 1\" [ . . . \"content 2\" ]"
    echo
    echo "         Content could be either directory or file."
  }

  if [ $# -ge 2 ]
  then
    archiveName=`basename "$1" ".dmg"`
    shift

    volume="/Volumes/${archiveName}"

    if [ -e "${volume}" ]
    then
      echo "${volume} already exists and is mounted. Operation cannot continue."
    else
      createBucket "$@"

      estimateDiskSize
      diskSize=$?

      createDMG
    fi
  else
    usage
  fi
