#!/usr/bin/env bash

# Generates apple/VniDrop/Generated/AppConfig.swift from the shared app.properties
# so app-wide constants (privacy policy URL, …) have a single source of truth
# across Apple and KMP. Regenerate instead of editing the output.

set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../.." && pwd)"
config_file="${VNIDROP_APP_PROPERTIES:-$repo_root/app.properties}"
output_dir="${VNIDROP_APPLE_GENERATED_DIR:-$repo_root/apple/VniDrop/Generated}"

read_property() {
	local key=$1
	local value
	value="$(sed -n "s/^${key}=//p" "$config_file")"
	[[ -n "$value" ]] || { printf 'Missing %s in %s\n' "$key" "$config_file" >&2; exit 1; }
	[[ $(printf '%s\n' "$value" | wc -l | tr -d ' ') == 1 ]] ||
		{ printf 'Duplicate %s in %s\n' "$key" "$config_file" >&2; exit 1; }
	printf '%s' "$value"
}

# Escape for a Swift string literal.
swift_escape() {
	printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'
}

privacy_url="$(read_property PRIVACY_POLICY_URL)"

mkdir -p "$output_dir"
tmp="$(mktemp "$output_dir/.AppConfig.swift.XXXXXX")"
cat > "$tmp" <<EOF
// Generated by apple/scripts/generate-appconfig.sh from app.properties.
// Regenerate this file instead of editing it.

import Foundation

/// App-wide constants injected at build time from the shared \`app.properties\`.
enum AppConfig {
	static let privacyPolicyURL = URL(string: "$(swift_escape "$privacy_url")")!
}
EOF
mv "$tmp" "$output_dir/AppConfig.swift"
