#!/usr/bin/make -f
# Copyright: Proton AG 2023.
# Author: John Biggs
# Makefile for Swift xcframeworks, for deploying the ProTun library on Apple platforms.
# This build first takes all of the arches for a platform, then combines them into one binary.
# Once it has all of the multi-arch binaries for each platform, it then packages them into one multi-platform xcframework.
# This makefile should probably be run on a Mac, unless you've somehow figured out how to run Xcode on your machine.

# The name of the organization publishing the software (for copyright purposes)
ORG_NAME := Proton AG
# The name of the module as imported by Swift
MODULE_NAME := PVPNClient
# The name of the library binary as generated by Rust, without the file extension
LIBRARY_NAME := libpvpnclient
# The bundle identifier for use at runtime to get at the properties defined in the framework's Info.plist
PRODUCT_BUNDLE_IDENTIFIER := ch.proton.vpn.rust.$(LIBRARY_NAME)

ifeq ($(ARCHS),)
	ARCHS := aarch64 x86_64
endif

# Mac Catalyst requires Cargo nightly + commercial version of mold linker for now (https://github.com/bluewhalesystems/sold)
# because Cargo isn't emitting the correct LC_BUILD_VERSION load command to get ld64 to understand what it wants to do.
# See thread: https://github.com/rust-lang/rust/issues/106021
ifeq ($(PLATFORMS),)
	PLATFORMS := darwin ios ios-sim # ios-macabi
endif

ifeq ($(OBJROOT),)
	OBJROOT := ./target
endif

# Rust tools
ifeq ($(CARGO),)
	CARGO := $(shell which cargo)
endif
ifeq ($(CARGO),)
	CARGO := $(shell command -v "$(HOME)/.cargo/bin/cargo")
endif
ifeq ($(CARGO),)
	$(error "No executable found for cargo")
endif

# Apple tools and strings
ifeq ($(XCRUN),)
	XCRUN := $(shell which xcrun)
endif
ifeq ($(CARGO),)
	$(error "No executable found for xcrun")
endif
#
# Install and build paths/strings
ifeq ($(CONFIG),)
ifeq ($(CONFIGURATION),Release)
	CONFIG := release
else
	CONFIG := debug
endif
endif

ifeq ($(CONFIG),release)
	CARGO_FLAGS += --release
endif

ifeq ($(BUNDLE_VERSION),)
	BUNDLE_VERSION := $(shell grep '^version = "\d' Cargo.toml 2> /dev/null | grep -E -o "\d+\.\d+\.\d+" || echo "999.0.0")
endif

# PLATFORM is defined in each recipe, for each platform in PLATFORMS.
SDKNAME = $(subst ios,iphoneos,$(subst ios-macabi,iphoneos,$(subst ios-sim,iphonesimulator,$(subst darwin,macosx,$(PLATFORM)))))
SDKROOT = $(shell $(XCRUN) --sdk "$(SDKNAME)" --show-sdk-path)
SDK_RUSTFLAGS = -L$(SDKROOT)/usr/lib -Lframework=$(SDKROOT)/System/Library/Frameworks
SDK_CARGO_CFLAGS = -isysroot $(SDKROOT)
SDK_CARGO_LIBRARY_PATH = $(SDKROOT)/usr/lib:$(LIBRARY_PATH)

LIPO = $(shell $(XCRUN) --sdk "$(SDKROOT)" -f lipo)
XCODEBUILD = $(shell $(XCRUN) --sdk "$(SDKROOT)" -f xcodebuild)
PLUTIL = $(shell $(XCRUN) --sdk "$(SDKROOT)" -f plutil)

CARGO_VERSION := $(shell $(CARGO) --version)
XCODE_VERSION := $(shell $(XCODEBUILD) -version | grep "Build version" | cut -d " " -f 3)

# "You keep on using this compiler triple. I don't think it means what you think it means."
#
# We generate all of the targets by doing the cartesian product of { archs } x { platforms }.
# However, x86_64-apple-ios, which one might think would be a magical iPhone with an Intel chip,
# is actually the simulator target for Intel Macs. (The simulator target for Arm Macs is
# aarch64-apple-ios-sim.) So, we need to filter out x86_64-apple-ios where it's generated, because
# we probably don't want to build for the simulator in those instances. Similarly, we want
# to replace x86_64-apple-ios-sim with x86_64-apple-ios, because the former isn't a valid target.
CURSED_TARGET := x86_64-apple-ios
remove_cursed_target_name = $(filter-out $(CURSED_TARGET),$(1))
replace_ios_sim = $(subst x86_64-apple-ios-sim,$(CURSED_TARGET),$(1))
fix_cursed_target = $(call replace_ios_sim,$(call remove_cursed_target_name,$(1)))

PLATFORM_TARGETS = $(call fix_cursed_target,$(foreach arch,$(ARCHS),$(arch)-apple-$(PLATFORM)))

# Ensure a target's directory is created.
dir_guard=@mkdir -p $(@D)

RUST_TARGETS := $(call fix_cursed_target,$(foreach arch,$(ARCHS),$(foreach platform,$(PLATFORMS),$(arch)-apple-$(platform))))
RUST_LIBS := $(foreach target,$(RUST_TARGETS),$(OBJROOT)/$(target)/$(CONFIG)/$(LIBRARY_NAME).a)
XCFRAMEWORK := $(OBJROOT)/$(MODULE_NAME).xcframework

.PHONY: clean $(RUST_TARGETS) $(PLATFORMS) xcframework

xcframework: $(XCFRAMEWORK)/Info.plist

clean:
	rm -rf "$(OBJROOT)"

# Step 1: generate the Rust library for a given arch and platform by calling cargo.

$(RUST_LIBS): $(OBJROOT)/%/$(CONFIG)/$(LIBRARY_NAME).a:
	$(dir_guard)
	export RUSTFLAGS="$(SDK_RUSTFLAGS) $(RUSTFLAGS)"; \
	export LIBRARY_PATH="$(SDK_CARGO_LIBRARY_PATH)"; \
	export CFLAGS_$(shell echo "$*" | tr - _)="$(SDK_CARGO_CFLAGS)"; \
	$(CARGO) build $(CARGO_FLAGS) --target-dir "$(OBJROOT)" --target "$*"

$(RUST_TARGETS): %: $(OBJROOT)/%/$(CONFIG)/$(LIBRARY_NAME).a

# Step 2: for each platform, use the binaries generated for each relevant triple from step 1 and lipo them all together.

define platform_binary
.SECONDEXPANSION:
$$(OBJROOT)/universal/$(1)/$$(LIBRARY_NAME).a: PLATFORM := $(1)
$$(OBJROOT)/universal/$(1)/$$(LIBRARY_NAME).a: $$$$(PLATFORM_TARGETS)
	$$(dir_guard)
	$$(LIPO) -create $$(foreach target,$$^,$(OBJROOT)/$$(target)/$(CONFIG)/$(LIBRARY_NAME).a) \
		-output "$$@"

endef

$(PLATFORMS): %: $(OBJROOT)/universal/%/$(LIBRARY_NAME).a

$(eval $(foreach platform,$(PLATFORMS),$(call platform_binary,$(platform))))

# Step 3: with the lipo'd binaries from each platform, create a universal xcframework.
$(XCFRAMEWORK)/Info.plist: $(PLATFORMS)
	$(XCODEBUILD) -create-xcframework $(foreach platform,$^,-library $(OBJROOT)/universal/$(platform)/$(LIBRARY_NAME).a -headers ./include) -output $(@D)
	$(PLUTIL) -insert CFBundleIdentifier -string "$(PRODUCT_BUNDLE_IDENTIFIER)" "$@"
	$(PLUTIL) -insert CFBundleShortVersionString -string "$(BUNDLE_VERSION)" "$@"
	$(PLUTIL) -insert NSHumanReadableCopyright -string "Copyright © $(shell date +%Y) $(ORG_NAME). All rights reserved." "$@"
	$(PLUTIL) -insert DTCargoVersion -string "$(CARGO_VERSION)" "$@"
	$(PLUTIL) -insert DTXcodeBuild -string "$(XCODE_VERSION)" "$@"

