#!/usr/bin/env bash

set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
release_version="${HT_MOBILE_RELEASE_VERSION:-}"
export_method="${HT_IOS_EXPORT_METHOD:-app-store-connect}"
team_id="${HT_IOS_TEAM_ID:-8A45MXKLQK}"
build_root="$repo_root/build/ios-release"
archive_path="$build_root/HTPortalVPN.xcarchive"
export_path="$build_root/export"
export_options="$build_root/ExportOptions.plist"
api_key_dir=""
auth_args=()

require_command() {
	if ! command -v "$1" >/dev/null 2>&1; then
		echo "Required command not found: $1" >&2
		exit 1
	fi
}

cleanup() {
	if [[ -n "$api_key_dir" && -d "$api_key_dir" ]]; then
		rm -rf "$api_key_dir"
	fi
}
trap cleanup EXIT

require_command xcodebuild
require_command xcodegen
require_command shasum

if [[ -n "${HT_IOS_KEYCHAIN_PASSWORD:-}" ]]; then
	security unlock-keychain -p "$HT_IOS_KEYCHAIN_PASSWORD" "${HT_IOS_KEYCHAIN_PATH:-$HOME/Library/Keychains/login.keychain-db}"
fi

if [[ -n "${HT_IOS_ASC_PRIVATE_KEY_BASE64:-}" ]]; then
	: "${HT_IOS_ASC_KEY_ID:?HT_IOS_ASC_KEY_ID is required with HT_IOS_ASC_PRIVATE_KEY_BASE64}"
	: "${HT_IOS_ASC_ISSUER_ID:?HT_IOS_ASC_ISSUER_ID is required with HT_IOS_ASC_PRIVATE_KEY_BASE64}"
	api_key_dir=$(mktemp -d)
	api_key_path="$api_key_dir/AuthKey_${HT_IOS_ASC_KEY_ID}.p8"
	printf '%s' "$HT_IOS_ASC_PRIVATE_KEY_BASE64" | /usr/bin/base64 -D > "$api_key_path"
	chmod 600 "$api_key_path"
	auth_args=(
		-authenticationKeyPath "$api_key_path"
		-authenticationKeyID "$HT_IOS_ASC_KEY_ID"
		-authenticationKeyIssuerID "$HT_IOS_ASC_ISSUER_ID"
	)
fi

cd "$repo_root"
scripts/apply-n3n-patches.sh
xcodegen generate

if [[ -z "$release_version" ]]; then
	release_version=$(sed -n 's/^[[:space:]]*MARKETING_VERSION:[[:space:]]*"\([^"]*\)"/\1/p' project.yml | head -1)
fi
if [[ -z "$release_version" ]]; then
	echo "Unable to determine the iOS release version" >&2
	exit 1
fi

mkdir -p "$build_root" "$repo_root/dist"

if [[ -n "${HT_IOS_EXPORT_OPTIONS_PLIST_BASE64:-}" ]]; then
	printf '%s' "$HT_IOS_EXPORT_OPTIONS_PLIST_BASE64" | /usr/bin/base64 -D > "$export_options"
else
	cat > "$export_options" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>destination</key>
	<string>export</string>
	<key>manageAppVersionAndBuildNumber</key>
	<false/>
	<key>method</key>
	<string>$export_method</string>
	<key>signingStyle</key>
	<string>automatic</string>
	<key>stripSwiftSymbols</key>
	<true/>
	<key>teamID</key>
	<string>$team_id</string>
	<key>uploadSymbols</key>
	<true/>
</dict>
</plist>
EOF
fi

xcodebuild \
	-project HTPortalVPN.xcodeproj \
	-scheme HTPortalVPN \
	-configuration Release \
	-destination 'generic/platform=iOS' \
	-archivePath "$archive_path" \
	-allowProvisioningUpdates \
	"${auth_args[@]}" \
	archive

xcodebuild \
	-exportArchive \
	-archivePath "$archive_path" \
	-exportPath "$export_path" \
	-exportOptionsPlist "$export_options" \
	-allowProvisioningUpdates \
	"${auth_args[@]}"

ipa=""
for candidate in "$export_path"/*.ipa; do
	if [[ -f "$candidate" ]]; then
		ipa=$candidate
		break
	fi
done
if [[ -z "$ipa" ]]; then
	echo "Xcode did not export an IPA" >&2
	exit 1
fi

release_ipa="$repo_root/dist/HT-Portal-VPN-$release_version.ipa"
cp "$ipa" "$release_ipa"
(
	cd "$repo_root/dist"
	shasum -a 256 "$(basename "$release_ipa")" > "$(basename "$release_ipa").sha256"
)

echo "iOS release IPA: $release_ipa"
