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

usage() {
  cat <<'EOF'
Usage:
  scripts/ios-write-version-xcconfig.sh [--build-number 7]

Writes apps/ios/build/Version.xcconfig from apps/ios/version.json:
- OPENCLAW_IOS_VERSION = exact canonical iOS version
- OPENCLAW_MARKETING_VERSION = short iOS/App Store version
- OPENCLAW_BUILD_VERSION = explicit build number or local numeric fallback
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
IOS_DIR="${ROOT_DIR}/apps/ios"
BUILD_DIR="${IOS_DIR}/build"
VERSION_XCCONFIG="${IOS_DIR}/build/Version.xcconfig"
VERSION_HELPER="${ROOT_DIR}/scripts/ios-version.ts"
IOS_VERSION=""
MARKETING_VERSION=""
BUILD_NUMBER=""

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
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

while IFS='=' read -r key value; do
  case "${key}" in
    OPENCLAW_IOS_VERSION)
      IOS_VERSION="${value}"
      ;;
    OPENCLAW_MARKETING_VERSION)
      MARKETING_VERSION="${value}"
      ;;
  esac
done < <(cd "${ROOT_DIR}" && node --import tsx "${VERSION_HELPER}" --shell)

if [[ -z "${IOS_VERSION}" || -z "${MARKETING_VERSION}" ]]; then
  echo "Unable to resolve iOS version metadata from ${ROOT_DIR}/apps/ios/version.json." >&2
  exit 1
fi

if [[ -z "${BUILD_NUMBER}" ]]; then
  BUILD_NUMBER="$(cd "${ROOT_DIR}" && git rev-list --count HEAD 2>/dev/null || printf '0')"
fi

if [[ ! "${BUILD_NUMBER}" =~ ^[0-9]+$ ]]; then
  echo "Invalid build number '${BUILD_NUMBER}'. Expected digits only." >&2
  exit 1
fi

prepare_build_dir

write_generated_file "${VERSION_XCCONFIG}" <<EOF
// Auto-generated by scripts/ios-write-version-xcconfig.sh.
// Local version override; do not commit.
OPENCLAW_IOS_VERSION = ${IOS_VERSION}
OPENCLAW_MARKETING_VERSION = ${MARKETING_VERSION}
OPENCLAW_BUILD_VERSION = ${BUILD_NUMBER}
EOF

echo "Prepared iOS version settings: ios=${IOS_VERSION} marketing=${MARKETING_VERSION} build=${BUILD_NUMBER}"
