# Builds an iOS app and runs it on a simulator or on a paired iPhone or iPad.
# Written by Edit's Run menu, which runs it in the project's folder:
#   sh ios.sh simulator|device|test|archive|xcode <name.xcodeproj|name.xcworkspace> <scheme>
set -e
mode=$1 container=$2 scheme=$3

say() { printf '\033[2m%s\033[0m\n' "$*"; }
fail() { printf '%s\n' "$*" >&2; exit 1; }

case $container in
*.xcworkspace) kind=-workspace ;;
*) kind=-project ;;
esac

if [ -f project.yml ] && [ "$kind" = -project ]; then
	if command -v xcodegen >/dev/null 2>&1; then
		xcodegen generate --use-cache --quiet
	elif [ ! -d "$container" ]; then
		fail "This project is made with XcodeGen. Install it with: brew install xcodegen"
	fi
fi

if [ "$mode" = xcode ]; then
	exec open "$container"
fi

hash=$(printf '%s' "$PWD/$container" | shasum | cut -c1-10)
derived="$HOME/Library/Developer/Xcode/DerivedData/Edit-$scheme-$hash"

# EDIT_SIMULATOR (a name or UDID); else the one this project ran on last, when it's booted; else the
# booted one on the newest iOS; else the first iPhone on the newest iOS. The choice is remembered.
remembered="$HOME/Library/Caches/runnables/simulator-$hash"
pick_simulator() {
	list=$(xcrun simctl list devices available)
	ios=$(printf '%s\n' "$list" | awk '/^-- /{ ios = /^-- iOS / } ios && /\([0-9A-F-]{36}\)/')
	line=
	if [ -n "${EDIT_SIMULATOR:-}" ]; then
		line=$(printf '%s\n' "$ios" | awk -v want="$EDIT_SIMULATOR" '
			{ name = $0; sub(/^ */, "", name); sub(/ \([0-9A-F-]{36}\).*/, "", name) }
			name == want || index($0, "(" want ")") { pick = $0; if (/\(Booted\)/) { print; found = 1; exit } }
			END { if (!found && pick) print pick }')
		[ -n "$line" ] || fail "No simulator called $EDIT_SIMULATOR. See: xcrun simctl list devices available"
	fi
	if [ -z "$line" ] && [ -f "$remembered" ]; then
		line=$(printf '%s\n' "$ios" | grep -F "($(cat "$remembered"))" | grep -F '(Booted)' || true)
	fi
	if [ -z "$line" ]; then
		line=$(printf '%s\n' "$ios" | grep -F '(Booted)' | tail -1)
	fi
	if [ -z "$line" ]; then
		line=$(printf '%s\n' "$list" | awk '/^-- /{ ios = /^-- iOS /; first = 1 } ios && first && /iPhone/ { pick = $0; first = 0 } END { print pick }')
	fi
	udid=$(printf '%s\n' "$line" | grep -oE '[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}' | tail -1)
	[ -n "$udid" ] || fail "No iOS simulator found. Add one in Xcode under Window > Devices and Simulators."
	simulator=$(printf '%s\n' "$line" | sed -E 's/^ *//; s/ \([0-9A-F-]{36}\).*//')
	mkdir -p "$(dirname "$remembered")" && printf '%s\n' "$udid" >"$remembered"
	booted=$(printf '%s\n' "$ios" | grep -c '(Booted)' || true)
	if [ "$booted" -gt 1 ]; then
		say "$booted simulators are running; using $simulator. Set EDIT_SIMULATOR to pick another."
	fi
}

# The first paired iPhone or iPad that isn't unavailable.
pick_device() {
	json=$(mktemp)
	xcrun devicectl list devices -q -j "$json" >/dev/null 2>&1 || true
	get() { plutil -extract "result.devices.$i.$1" raw -o - "$json" 2>/dev/null || true; }
	i=0 id=
	while [ -n "$(get identifier)" ]; do
		if [ "$(get hardwareProperties.platform)" = iOS ] &&
			[ "$(get hardwareProperties.reality)" != simulated ] &&
			[ "$(get connectionProperties.pairingState)" = paired ] &&
			[ "$(get connectionProperties.tunnelState)" != unavailable ]; then
			id=$(get identifier) udid=$(get hardwareProperties.udid) device=$(get deviceProperties.name)
			break
		fi
		i=$((i + 1))
	done
	rm -f "$json"
	[ -n "$id" ] || fail "No iPhone or iPad found. Connect one with a cable or on the same network, and pair it in Xcode."
}

# A project that names its team is built as it is set up in Xcode: no team passed, and no
# -allowProvisioningUpdates, which signs in with every account Xcode knows. Only a project
# without a team gets the team of the first Apple Development certificate and that flag.
pick_team() {
	signing=
	team=$(xcodebuild "$kind" "$container" -scheme "$scheme" -showBuildSettings 2>/dev/null |
		awk '$1 == "DEVELOPMENT_TEAM" && $3 != "" { print $3; exit }')
	[ -z "$team" ] || return 0
	sha=$(security find-identity -v -p codesigning | awk '/"Apple Development/ { print $2; exit }')
	[ -n "$sha" ] || fail "No Apple Development certificate. Sign in under Xcode > Settings > Accounts."
	team=$(security find-certificate -a -c "Apple Development" -Z -p |
		awk -v sha="$sha" '/^SHA-1 hash:/ { on = ($3 == sha); next } on' |
		openssl x509 -noout -subject 2>/dev/null | sed -nE 's/.*OU ?= ?([A-Z0-9]+).*/\1/p')
	signing="-allowProvisioningUpdates DEVELOPMENT_TEAM=$team"
	say "Signing with team $team. Set DEVELOPMENT_TEAM in the project to pick another."
}

# The app that was built, and its bundle identifier.
find_app() {
	products="$derived/Build/Products/Debug-$1"
	app="$products/$scheme.app"
	if [ ! -d "$app" ]; then
		app=$(find "$products" -maxdepth 1 -name '*.app' ! -name '*-Runner.app' | head -1)
	fi
	[ -d "$app" ] || fail "The build made no app in $products."
	bundle=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Info.plist")
}

case $mode in
simulator)
	pick_simulator
	say "Building $scheme for ${simulator}…"
	xcrun simctl boot "$udid" 2>/dev/null || true
	# Xcode 27 replaced Simulator.app with DeviceHub.app.
	dev=$(xcode-select -p)
	if [ -d "$dev/../Applications/DeviceHub.app" ]; then
		open "$dev/../Applications/DeviceHub.app"
	else
		open -a Simulator --args -CurrentDeviceUDID "$udid"
	fi
	xcodebuild "$kind" "$container" -scheme "$scheme" -configuration Debug \
		-destination "id=$udid" -derivedDataPath "$derived" -quiet build
	find_app iphonesimulator
	xcrun simctl install "$udid" "$app"
	say "Running $bundle on $simulator. Stop ends it."
	exec xcrun simctl launch --console-pty --terminate-running-process "$udid" "$bundle"
	;;
device)
	pick_device
	pick_team
	say "Building $scheme for ${device}…"
	# shellcheck disable=SC2086
	xcodebuild "$kind" "$container" -scheme "$scheme" -configuration Debug \
		-destination "id=$udid" -derivedDataPath "$derived" $signing -quiet build ||
		fail "The build failed. If it is about signing, open the project in Xcode once and build there, so Xcode makes the profile."
	find_app iphoneos
	say "Installing on ${device}…"
	xcrun devicectl device install app --device "$id" "$app" >/dev/null
	say "Running $bundle on $device. Stop ends it."
	exec xcrun devicectl device process launch --console --terminate-existing --device "$id" "$bundle"
	;;
archive)
	# Where Xcode keeps its own archives, so this one is in the Organizer, ready to upload to App Store Connect.
	pick_team
	stamp=$(date '+%Y-%m-%d')
	archive="$HOME/Library/Developer/Xcode/Archives/$stamp/$scheme $(date '+%-d.%-m.%Y, %H.%M').xcarchive"
	say "Archiving $scheme for App Store Connect…"
	# shellcheck disable=SC2086
	xcodebuild "$kind" "$container" -scheme "$scheme" -configuration Release \
		-destination 'generic/platform=iOS' -archivePath "$archive" $signing -quiet archive ||
		fail "The archive failed. If it is about signing, open the project in Xcode once and archive there, so Xcode makes the profile."
	say "Archived to $archive"
	say "Upload it from Xcode's Organizer (Window > Organizer > Distribute App)."
	open -R "$archive"
	;;
test)
	pick_simulator
	say "Testing $scheme on ${simulator}…"
	exec xcodebuild "$kind" "$container" -scheme "$scheme" -destination "id=$udid" \
		-derivedDataPath "$derived" -quiet test
	;;
*)
	fail "Unknown mode: $mode"
	;;
esac
