#!/bin/sh

set -eu

if [ -z "${SRCROOT:-}" ]; then
  echo "error: SRCROOT is empty; cannot locate the Aliyun NUI framework." >&2
  exit 1
fi

if [ -z "${DWARF_DSYM_FOLDER_PATH:-}" ]; then
  echo "error: DWARF_DSYM_FOLDER_PATH is empty; refusing to collect the Aliyun NUI dSYM." >&2
  exit 1
fi

FRAMEWORK_BINARY="${SRCROOT}/Vendor/AliyunNui/nuisdk.framework/nuisdk"
VENDORED_DSYM="${SRCROOT}/Vendor/AliyunNui/nuisdk.framework.dSYM"
ARCHIVE_DSYM="${DWARF_DSYM_FOLDER_PATH}/nuisdk.framework.dSYM"
ARCHIVE_DWARF="${ARCHIVE_DSYM}/Contents/Resources/DWARF/nuisdk"

if [ ! -f "${FRAMEWORK_BINARY}" ]; then
  echo "error: Aliyun NUI binary not found at ${FRAMEWORK_BINARY}" >&2
  exit 1
fi

mkdir -p "${DWARF_DSYM_FOLDER_PATH}"
rm -rf "${ARCHIVE_DSYM}"

if [ -d "${VENDORED_DSYM}" ]; then
  /usr/bin/rsync -a "${VENDORED_DSYM}" "${DWARF_DSYM_FOLDER_PATH}/"
  echo "Using the vendored Aliyun NUI dSYM."
else
  # The distributed framework contains a symbol table but no companion dSYM.
  # Generate one during Archive so App Store Connect can match its Mach-O UUID.
  if ! DSYMUTIL_OUTPUT="$(/usr/bin/xcrun dsymutil "${FRAMEWORK_BINARY}" -o "${ARCHIVE_DSYM}" 2>&1)"; then
    echo "${DSYMUTIL_OUTPUT}" >&2
    echo "error: Failed to generate the Aliyun NUI dSYM." >&2
    exit 1
  fi
  echo "Generated the Aliyun NUI dSYM from the framework's symbol table."
fi

if [ ! -f "${ARCHIVE_DWARF}" ]; then
  echo "error: Aliyun NUI dSYM has no DWARF binary at ${ARCHIVE_DWARF}" >&2
  exit 1
fi

FRAMEWORK_UUIDS="$(/usr/bin/xcrun dwarfdump --uuid "${FRAMEWORK_BINARY}" | /usr/bin/awk '{ print $2 }' | /usr/bin/sort)"
DSYM_UUIDS="$(/usr/bin/xcrun dwarfdump --uuid "${ARCHIVE_DWARF}" | /usr/bin/awk '{ print $2 }' | /usr/bin/sort)"

if [ -z "${FRAMEWORK_UUIDS}" ] || [ "${FRAMEWORK_UUIDS}" != "${DSYM_UUIDS}" ]; then
  echo "error: Aliyun NUI dSYM UUID mismatch." >&2
  echo "error: Framework UUIDs: ${FRAMEWORK_UUIDS:-none}" >&2
  echo "error: dSYM UUIDs: ${DSYM_UUIDS:-none}" >&2
  exit 1
fi

echo "Aliyun NUI dSYM UUIDs verified: ${DSYM_UUIDS}"
