#!/usr/bin/env bash

set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../.." && pwd)"
resolver="$script_dir/resolve-version.sh"
output_dir="${VNIDROP_APPLE_XCCONFIG_DIR:-$repo_root/apple/Generated}"
mode="${1:-all}"

case "$mode" in
	store|direct|all) ;;
	*)
		printf 'Usage: %s {store|direct|all}\n' "$0" >&2
		exit 1
		;;
esac

export VNIDROP_BUILD_TIME_UTC="${VNIDROP_BUILD_TIME_UTC:-$(date -u +%Y%m%d%H%M%S)}"
product_version="$("$resolver" product)"
mkdir -p "$output_dir"

write_config() {
	local filename=$1
	local build_field=$2
	local destination="$output_dir/$filename"
	local temporary
	local build_number

	build_number="$("$resolver" "$build_field")"
	temporary="$(mktemp "$output_dir/.${filename}.XXXXXX")"
	printf '%s\n' \
		'// Generated by packaging/version/generate-apple-xcconfig.sh.' \
		'// Regenerate this file instead of editing it.' \
		'#include "../Signing.xcconfig"' \
		'' \
		"PRODUCT_VERSION = $product_version" \
		"CURRENT_PROJECT_VERSION = $build_number" \
		> "$temporary"
	mv "$temporary" "$destination"
}

if [[ $mode == store || $mode == all ]]; then
	write_config StoreVersion.xcconfig apple-store-build
fi
if [[ $mode == direct || $mode == all ]]; then
	write_config DirectVersion.xcconfig apple-direct-build
fi
