#!/bin/bash

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

## Copy Libsystem pieces from ~rc
copylibs=0
## Install results in /
noinstall=0
build=$(sw_vers -buildVersion)
train=$(~rc/bin/getTrainForBuild --quiet "$build")

while [ $# -gt 0 ]; do
	if [ "${1/=*/}" = "--build" ]; then
		build="${1/*=/}"
	elif [ "$1" = "--noinstall" ]; then
		noinstall=1
	elif [ "$1" = "--copylibs" ]; then
		copylibs=1
	else
		echo "install: [--build=10A400] [--noinstall] [--copylibs]" 2>&1
		exit 1
	fi
	shift
done

ROOTS=/var/tmp/GCDRoots."$build"

# Building for another version implies copylibs and noinstall
if [ "$build" != "$(sw_vers -buildVersion)" ]; then
	copylibs=1
	noinstall=1
fi

set -ex
mkdir -p "$ROOTS"

function BUILDIT() {
	~rc/bin/buildit -arch i386 -arch ppc -arch x86_64 -arch armv6 \
		-release "$train" -rootsDirectory "$ROOTS" "$@" .
}

BUILDIT -project libdispatch -merge / -noverify

if [ $copylibs = 1 ]; then
	ALTUSRLOCALLIBSYSTEM="$ROOTS"/system
	mkdir -p "$ALTUSRLOCALLIBSYSTEM"
	export ALTUSRLOCALLIBSYSTEM
	./install_Libsystem_pieces "$build"
	cp /usr/local/lib/system/libdispatch* "$ALTUSRLOCALLIBSYSTEM"
fi

LIBSYSTEM=$(~rc/bin/getvers "$train$build" Libsystem)
if [ -z "$LIBSYSTEM" ]; then
	exit 1
fi
SRCROOT="/var/tmp/$LIBSYSTEM"
if [ ! -e "$SRCROOT" ]; then
	cd $(dirname "$SRCROOT")
	svn co http://src.apple.com/svn/BSD/Libsystem/tags/"$LIBSYSTEM"
fi
cd "$SRCROOT"
BUILDIT

if [ $noinstall -eq 1 ]; then
	exit 0
fi

if [ ! -e /usr/lib/libSystem.B.dylib.orig ]; then
	cp /usr/lib/libSystem.B.dylib /usr/lib/libSystem.B.dylib.orig
fi
if [ ! -e /usr/lib/libSystem.B_debug.dylib.orig ] ; then
	cp /usr/lib/libSystem.B_debug.dylib /usr/lib/libSystem.B_debug.dylib.orig
fi
if [ ! -e /usr/lib/libSystem.B_profile.dylib.orig ] ; then
	cp /usr/lib/libSystem.B_profile.dylib /usr/lib/libSystem.B_profile.dylib.orig
fi
cp -R "$ROOTS"/"$LIBSYSTEM".roots/"$LIBSYSTEM"~sym/libSystem* /usr/lib/
update_dyld_shared_cache
