HEADER_PATHS := `find download/JavaScriptCore/JavaScriptCore-$(JSC_VERSION) -name '*.h' | xargs -I{} dirname {} | uniq | xargs -I{} echo "-I {}"`

XCODE_PATH ?= $(shell xcode-select -p)
SDK_PATH = $(XCODE_PATH)/Platforms/$1.platform/Developer/SDKs/$1.sdk
SDK_VERSION = $(shell plutil -convert json -o - $(call SDK_PATH,iPhoneOS)/SDKSettings.plist | awk -f parseSDKVersion.awk)

CERT ?= iPhone Developer

ARCHS = x86_64 arm64 armv7 i386

PLATFORM = \
	if [[ "$*" = "x86_64" || "$*" = "i386" ]]; then \
		PLATFORM=iPhoneSimulator; \
	else \
		PLATFORM=iPhoneOS; \
	fi;

SYSROOT = -isysroot $(call SDK_PATH,$${PLATFORM})

IOS_LIBS = \
	download/JavaScriptCore/JavaScriptCore-$(JSC_VERSION) \
	download/WebCore/WebCore-$(WEB_CORE_VERSION) \
	download/WTF/WTF-$(WTF_VERSION) \
	download/JavaScriptCore/JavaScriptCore-$(JSC_VERSION)/Bytecodes.h

IOS_EXT=ios$(IOS_VERSION)

ifneq ($(SDK_VERSION), $(IOS_VERSION))

all:
	$(error "Expected to be compiled with iOS SDK version 8, found $(SDK_VERSION)")

else

all: RCTJSCProfiler.$(IOS_EXT).dylib /tmp/RCTJSCProfiler
	cp $^

endif

/tmp/RCTJSCProfiler:
	mkdir -p $@

RCTJSCProfiler.$(IOS_EXT).dylib: RCTJSCProfiler_unsigned.$(IOS_EXT).dylib
	cp $< $@
	codesign -f -s "${CERT}" $@

.PRECIOUS: RCTJSCProfiler_unsigned.$(IOS_EXT).dylib
RCTJSCProfiler_unsigned.$(IOS_EXT).dylib: $(patsubst %,RCTJSCProfiler_%.$(IOS_EXT).dylib,$(ARCHS))
	lipo -create -output $@ $^

.PRECIOUS: RCTJSCProfiler_%.$(IOS_EXT).dylib
RCTJSCProfiler_%.$(IOS_EXT).dylib: $(IOS_LIBS)
	$(PLATFORM) \
	clang -w -dynamiclib -o RCTJSCProfiler_$*.$(IOS_EXT).dylib -std=c++11 \
		-arch $* \
		-install_name RCTJSCProfiler.$(IOS_EXT).dylib \
		-include ./download/JavaScriptCore/JavaScriptCore-$(JSC_VERSION)/config.h \
		-I download \
		-I download/WebCore/WebCore-$(WEB_CORE_VERSION)/icu \
		-I download/WTF/WTF-$(WTF_VERSION) \
		-DNDEBUG=1 \
		-DIOS$(IOS_VERSION)=1 \
		-miphoneos-version-min=8.0 \
		$(SYSROOT) \
		$(HEADER_PATHS) \
		-undefined dynamic_lookup \
		JSCLegacyProfiler.mm

.PRECIOUS: %/Bytecodes.h
%/Bytecodes.h:
	python $*/generate-bytecode-files --bytecodes_h $@ $*/bytecode/BytecodeList.json

.PRECIOUS: download/%
download/%: download/%.tar.gz
	tar -zxvf $< -C `dirname $@` > /dev/null

.PRECIOUS: %.tar.gz
%.tar.gz:
	mkdir -p `dirname $@`
	curl -o $@ http://www.opensource.apple.com/tarballs/$(patsubst download/%,%,$@)