#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$repo_root"

platform="${1:-all}"
out_dir="${BURROW_APPLE_PROFILES_OUT_DIR:-.forgejo/actions/export}"
app_id="${BURROW_APPLE_BUNDLE_ID:-net.burrow.app}"
network_id="${BURROW_APPLE_NETWORK_EXTENSION_BUNDLE_ID:-${app_id}.network}"
replace_certificate_mismatch="${BURROW_APPLE_REPLACE_CERTIFICATE_MISMATCH:-false}"
if [[ -n "${BURROW_IOS_DISTRIBUTION_CERTIFICATE_ID:-}" || -n "${BURROW_DEVELOPER_ID_CERTIFICATE_ID:-}" ]]; then
  replace_certificate_mismatch="${BURROW_APPLE_REPLACE_CERTIFICATE_MISMATCH:-true}"
fi

key_id="${ASC_API_KEY_ID:-${APPSTORE_KEY_ID:-}}"
issuer_id="${ASC_API_ISSUER_ID:-${APPSTORE_KEY_ISSUER_ID:-}}"
key_path="${ASC_API_KEY_PATH:-${APPSTORE_KEY_PATH:-}}"
key_base64="${ASC_API_KEY_BASE64:-}"

if [[ -z "$key_id" || -z "$issuer_id" ]]; then
  echo "::notice ::App Store Connect credentials are not available; provisioning profile sync skipped."
  exit 0
fi

temp_key=""
cleanup() {
  [[ -z "$temp_key" ]] || rm -f "$temp_key"
}
trap cleanup EXIT

if [[ -z "$key_path" ]]; then
  if [[ -z "$key_base64" ]]; then
    echo "::notice ::ASC_API_KEY_PATH/ASC_API_KEY_BASE64 is not available; provisioning profile sync skipped."
    exit 0
  fi
  temp_key="$(mktemp "${RUNNER_TEMP:-/tmp}/burrow-asc-key.XXXXXX.p8")"
  printf '%s' "$key_base64" | base64 --decode > "$temp_key"
  chmod 600 "$temp_key"
  key_path="$temp_key"
fi

if [[ ! -f "$key_path" ]]; then
  echo "::error ::App Store Connect key path does not exist: ${key_path}" >&2
  exit 1
fi

mkdir -p "$out_dir"
profile_args=(
  --platform "$platform"
  --key-id "$key_id"
  --issuer-id "$issuer_id"
  --key-file "$key_path"
  --out-dir "$out_dir"
  --app-id "$app_id"
  --network-id "$network_id"
  --create-missing-bundle-ids "${BURROW_APPLE_CREATE_MISSING_BUNDLE_IDS:-false}"
  --enable-capabilities "${BURROW_APPLE_ENABLE_CAPABILITIES:-false}"
  --replace-certificate-mismatch "$replace_certificate_mismatch"
  --bundle-platform "${BURROW_APPLE_BUNDLE_PLATFORM:-UNIVERSAL}"
  --associated-domains "${BURROW_APPLE_ASSOCIATED_DOMAINS:-applinks:burrow.rs?mode=developer,webcredentials:burrow.rs?mode=developer}"
)

if [[ -n "${BURROW_IOS_DISTRIBUTION_CERTIFICATE_ID:-}" ]]; then
  profile_args+=(--ios-certificate-id "$BURROW_IOS_DISTRIBUTION_CERTIFICATE_ID")
fi

if [[ -n "${BURROW_DEVELOPER_ID_CERTIFICATE_ID:-}" ]]; then
  profile_args+=(--macos-certificate-id "$BURROW_DEVELOPER_ID_CERTIFICATE_ID")
fi

node Scripts/apple/sync-provisioning-profiles.mjs "${profile_args[@]}"
