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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
IOS_DIR="${ROOT_DIR}/apps/ios"
TEAM_ID_SCRIPT="${ROOT_DIR}/scripts/ios-team-id.sh"
LOCAL_SIGNING_FILE="${IOS_DIR}/.local-signing.xcconfig"

if [[ ! -x "${TEAM_ID_SCRIPT}" ]]; then
  echo "ERROR: Missing team detection helper: ${TEAM_ID_SCRIPT}" >&2
  exit 1
fi

team_id=""
if team_id="$("${TEAM_ID_SCRIPT}" 2>/dev/null)"; then
  :
else
  if [[ "${IOS_SIGNING_REQUIRED:-0}" == "1" ]]; then
    "${TEAM_ID_SCRIPT}"
    exit 1
  fi

  echo "WARN: Unable to detect an Apple Team ID; keeping existing iOS signing override (if any)." >&2
  exit 0
fi

tmp_file="$(mktemp "${TMPDIR:-/tmp}/openclaw-ios-signing.XXXXXX")"
cat >"${tmp_file}" <<EOF
// Auto-generated by scripts/ios-configure-signing.sh.
// This file is local-only and should not be committed.
OPENCLAW_DEVELOPMENT_TEAM = ${team_id}
// Keep legacy key for compatibility with older signing config paths.
OPENCLAW_IOS_SELECTED_TEAM = ${team_id}
EOF

if [[ -f "${LOCAL_SIGNING_FILE}" ]] && cmp -s "${tmp_file}" "${LOCAL_SIGNING_FILE}"; then
  rm -f "${tmp_file}"
  echo "iOS signing team already configured: ${team_id}"
  exit 0
fi

mv "${tmp_file}" "${LOCAL_SIGNING_FILE}"
echo "Configured iOS signing team: ${team_id}"
