#!/bin/env bash
# sysextract.sh v07071101
# Restores basic system components from any Intel system install
# Created by Filipp Lepalaan <filipp@humac.fi>

# If something goes wrong, to restore NI:
# sh /etc/rc
# /usr/bin/niload -d -r -t / localhost/local < /var/backups/local.nidump

# TODO: - convert to compressed/scanned img
# hdiutil convert -format UDZO <pathtoimage> -o <compressedimage>
# asr -imagescan <compressedimage>

declare -a PKGS
PKGS=( BaseSystem Essentials BSD QuickTime716 MacOSXUpd10.4.10Intel SecUpd2007-006Univ )
USAGE="$(basename $0) src target [-pp]"

### That's all you should have to change ###

if [ $# -eq 0 ]
	then echo "Usage: $USAGE";
	exit 1
fi

if [ ! -d "$1" ]
  then
    echo "Invalid source." >&2
    exit 1
fi

while getopts "pp" option
	do
	 case $option in
		pp ) echo "Postprocessing enabled"; pp=true;;
	esac
done

echo Erasing target ...
diskutil reformat $2 > /dev/null 2>&1

# Make sure permissions are enabled on the source
sudo vsdbutil -d "$1"

for ((i=0; i < ${#PKGS}; i++))
  do
    PKG="$1/Library/Receipts/${PKGS[${i}]}.pkg"
    echo Copying: $PKG
    sudo ditto --rsrc "$PKG" "$2/Library/Receipts/${PKGS[${i}]}.pkg"
    sudo ditto --rsrc -bom "$PKG/Contents/Archive.bom" "$1" "$2"
  done

echo Cleaning up....

cat > "$2/.hidden" << EOF
mach
etc
var
tmp
private
EOF

if [ $pp ]
	then
		sudo rm -rf "$2/var/db/netinfo/local.nidb" \
		  "$2/var/db/.AppleSetupDone" \ 
		  "$2/Users/*" \ 
		  "$2/var/db/BootCache.playlist" \
		  "$2/var/db/volinfo.database" \
		  "$2/var/vm/swap*" \
		  "$2/Library/Caches/*" \
		  "$2/System/Library/Caches/*" \
		  "$2/System/Library/Extensions.kextcache"

		# Enable perms on the target
		echo * Enabling permissions on the target...
		sudo vsdbutil -d "$2"
		
		# Enable language chooser
		sudo touch "$2/var/db/.RunLanguageChooserToo"
		echo * Repairing permissions....

		diskutil repairPermissions "$2"

		echo Blessing target ....

		sudo bless --folder "$2/System/Library/CoreServices" --bootinfo --bootefi
fi

exit 0
