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

usage() {
  cat <<'EOF'
Usage:
  scripts/ios-beta-prepare.sh --build-number 7 [--team-id TEAMID]

Prepares local beta-release inputs without touching local signing overrides:
- reads package.json.version and writes apps/ios/build/Version.xcconfig
- writes apps/ios/build/BetaRelease.xcconfig with canonical bundle IDs
- regenerates apps/ios/OpenClaw.xcodeproj via xcodegen
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
IOS_DIR="${ROOT_DIR}/apps/ios"
BUILD_DIR="${IOS_DIR}/build"
BETA_XCCONFIG="${IOS_DIR}/build/BetaRelease.xcconfig"
TEAM_HELPER="${ROOT_DIR}/scripts/ios-team-id.sh"
VERSION_HELPER="${ROOT_DIR}/scripts/ios-write-version-xcconfig.sh"

BUILD_NUMBER=""
TEAM_ID="${IOS_DEVELOPMENT_TEAM:-}"
PACKAGE_VERSION="$(cd "${ROOT_DIR}" && node -p "require('./package.json').version" 2>/dev/null || true)"

prepare_build_dir() {
  if [[ -L "${BUILD_DIR}" ]]; then
    echo "Refusing to use symlinked build directory: ${BUILD_DIR}" >&2
    exit 1
  fi

  mkdir -p "${BUILD_DIR}"
}

write_generated_file() {
  local output_path="$1"
  local tmp_file=""

  if [[ -e "${output_path}" && -L "${output_path}" ]]; then
    echo "Refusing to overwrite symlinked file: ${output_path}" >&2
    exit 1
  fi

  tmp_file="$(mktemp "${output_path}.XXXXXX")"
  cat >"${tmp_file}"
  mv -f "${tmp_file}" "${output_path}"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --)
      shift
      ;;
    --build-number)
      BUILD_NUMBER="${2:-}"
      shift 2
      ;;
    --team-id)
      TEAM_ID="${2:-}"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

if [[ -z "${BUILD_NUMBER}" ]]; then
  echo "Missing required --build-number." >&2
  usage
  exit 1
fi

if [[ -z "${TEAM_ID}" ]]; then
  TEAM_ID="$(IOS_ALLOW_KEYCHAIN_TEAM_FALLBACK=1 bash "${TEAM_HELPER}")"
fi

if [[ -z "${TEAM_ID}" ]]; then
  echo "Could not resolve Apple Team ID. Set IOS_DEVELOPMENT_TEAM or sign into Xcode." >&2
  exit 1
fi

prepare_build_dir

(
  bash "${VERSION_HELPER}" --build-number "${BUILD_NUMBER}"
)

write_generated_file "${BETA_XCCONFIG}" <<EOF
// Auto-generated by scripts/ios-beta-prepare.sh.
// Local beta-release override; do not commit.
OPENCLAW_CODE_SIGN_STYLE = Automatic
OPENCLAW_DEVELOPMENT_TEAM = ${TEAM_ID}
OPENCLAW_IOS_SELECTED_TEAM = ${TEAM_ID}
OPENCLAW_APP_BUNDLE_ID = ai.openclaw.client
OPENCLAW_SHARE_BUNDLE_ID = ai.openclaw.client.share
OPENCLAW_ACTIVITY_WIDGET_BUNDLE_ID = ai.openclaw.client.activitywidget
OPENCLAW_WATCH_APP_BUNDLE_ID = ai.openclaw.client.watchkitapp
OPENCLAW_WATCH_EXTENSION_BUNDLE_ID = ai.openclaw.client.watchkitapp.extension
OPENCLAW_APP_PROFILE =
OPENCLAW_SHARE_PROFILE =
EOF

(
  cd "${IOS_DIR}"
  xcodegen generate
)

echo "Prepared iOS beta release: version=${PACKAGE_VERSION} build=${BUILD_NUMBER} team=${TEAM_ID}"
echo "XCODE_XCCONFIG_FILE=${BETA_XCCONFIG}"
