#!/bin/bash -e

function usage() {
  echo "Usage: `basename $0` <Lion install app> <Target volume>" 1>&2
}

if [ $# -ne 2 ]; then
  usage
  exit 1
fi

LION_INSTALL_APP=$1
TARGET_VOLUME=$2
BASE_TARGET='/Volumes/Mac OS X Base System'
IN_APP_DMG='Contents/SharedSupport/InstallESD.dmg'
SCRIPT_DIR=`dirname $0`

if [ ! -d "$LION_INSTALL_APP" ]; then
  echo "$LION_INSTALL_APP: No such file" 1>&2
  usage
  exit 2
fi

if [ ! -d "$TARGET_VOLUME" ]; then
  echo "$TARGET_VOLUME: No such directory" 1>&2
  usage
  exit 3
fi

if [ $EUID -ne 0 ]; then
   echo "This script must be run as root" 1>&2
   exit 4
fi

function echob() {
  echo "`tput bold`$1`tput sgr0`"
}

echob "Attaching OS X Lion..."
hdiutil attach -mountpoint $SCRIPT_DIR/lioninst "$LION_INSTALL_APP/$IN_APP_DMG"

pushd `dirname $0` > /dev/null

echob "Restoring BaseSystem.dmg to $TARGET_VOLUME..."
asr --source lioninst/BaseSystem.dmg --target "$TARGET_VOLUME" --erase --noprompt

echob "Adopting on-disk ownership on $BASE_TARGET..."
vsdbutil -a "$BASE_TARGET"

echob "Copying Packages from OS X Lion main image..."
rm "$BASE_TARGET/System/Installation/Packages"
rsync -r --progress lioninst/Packages "$BASE_TARGET/System/Installation/"

echob "Copying mach_kernel from OS X Lion main image..."
cp -r lioninst/mach_kernel "$BASE_TARGET"

echob "Detaching OS X Lion main image..."
hdiutil detach lioninst

echob "Ejecting $BASE_TARGET..."
diskutil eject "$BASE_TARGET"

echob "All done."

popd > /dev/null
