#!/bin/bash -e
dmg_outside="`cd "$1";pwd`/Contents/SharedSupport/InstallESD.dmg"
restoreto="`cd "$2";pwd`"
cd "$(dirname "$0")"
hdiutil eject mntesd >/dev/null 2>&1 || true 
rm -rf mntesd 
mkdir mntesd

hdiutil attach -nobrowse "$dmg_outside" -mountpoint mntesd
sudo asr restore --source "mntesd/BaseSystem.dmg" --erase --target "$restoreto"
while [ ! -d "/Volumes/Mac OS X Base System/System/Installation" ]; do sleep 1; done
sudo rm -rf "/Volumes/Mac OS X Base System/System/Installation/Packages" # a symlink
echo Copying packages
sudo cp -rv "mntesd/Packages" "/Volumes/Mac OS X Base System/System/Installation/Packages"
hdiutil eject mntesd >/dev/null 2>&1 || true 
rm -rf mntesd

rm -rf oi
pkgutil --expand "/Volumes/Mac OS X Base System/System/Installation/Packages/OSInstall.mpkg" oi
/usr/bin/sed -i '' 's/"VMM"/"FPU"/g' oi/Distribution
/usr/bin/sed -i '' 's@<pkg-ref id="com.apple.pkg.OSInstall"/>@<pkg-ref id="com.parrotgeek.mllegacysupport"/><pkg-ref id="com.apple.pkg.OSInstall"/>@g' oi/Distribution
/usr/bin/sed -i '' 's@</installer-gui-script>@<pkg-ref id="com.parrotgeek.mllegacysupport" auth="root">mllegacy.pkg</pkg-ref></installer-gui-script>@g' oi/Distribution
find oi -name .DS_Store -delete
pkgutil --flatten oi OSInstall_new.mpkg
rm -rf oi

sudo cp OSInstall_new.mpkg "/Volumes/Mac OS X Base System/System/Installation/Packages/OSInstall.mpkg"
rm -f OSInstall_new.mpkg

sudo cp mllegacy.pkg "/Volumes/Mac OS X Base System/System/Installation/Packages/mllegacy.pkg"
sudo cp mllegacygfx.pkg "/Volumes/Mac OS X Base System/mllegacygfx.pkg"
sudo chflags nouchg "/Volumes/Mac OS X Base System/System/Library/CoreServices/boot.efi"
sudo cp boot.efi "/Volumes/Mac OS X Base System/System/Library/CoreServices/boot.efi"
sudo chflags nouchg "/Volumes/Mac OS X Base System/usr/standalone/i386/boot.efi"
sudo cp boot.efi "/Volumes/Mac OS X Base System/usr/standalone/i386/boot.efi"
sudo cp com.apple.PowerManagement.plist "/Volumes/Mac OS X Base System/Library/Preferences/SystemConfiguration/com.apple.PowerManagement.plist"

echo Done
