#!/usr/bin/env bash
# Patch the freshly-generated Capacitor iOS project (mobile/ios/App) for App Store submission.
# Runs on the Codemagic macOS instance after `npx cap add ios`. Idempotent — safe to re-run.
set -euo pipefail

PLIST="mobile/ios/App/App/Info.plist"
PB=/usr/libexec/PlistBuddy

set_str() {  # set_str <key> <value>  — add the key if missing, else overwrite
  "$PB" -c "Add :$1 string $2" "$PLIST" 2>/dev/null || "$PB" -c "Set :$1 $2" "$PLIST"
}

echo "Patching $PLIST"

# ── Privacy usage strings (Apple REJECTS the build if a used capability has no purpose string) ──
set_str NSCameraUsageDescription      "Biz Connect uses the camera for video calls and to share photos and your screen."
set_str NSMicrophoneUsageDescription  "Biz Connect uses the microphone for voice and video calls."
set_str NSPhotoLibraryUsageDescription      "Biz Connect needs photo access so you can send images in chat."
set_str NSPhotoLibraryAddUsageDescription   "Biz Connect saves images and recordings you download to your photos."

# Human-readable display name on the home screen.
set_str CFBundleDisplayName "Biz Connect"

# CFBundleVersion (build number) MUST be unique AND higher than every previous App Store Connect upload,
# or publishing fails with "The bundle version must be higher than the previously uploaded version".
# Capacitor ships "1" by default, so every build collided. Use Codemagic's monotonically-increasing
# BUILD_NUMBER (this is build index 6+, already > the "1" that's on TestFlight). Fall back to an epoch
# timestamp if it's somehow unset, which is also strictly increasing.
BUILD_NO="${BUILD_NUMBER:-$(date +%s)}"
echo "Setting CFBundleVersion = $BUILD_NO"
set_str CFBundleVersion "$BUILD_NO"

# We use only standard encryption (HTTPS/TLS), which is exempt — declaring this up front stops App Store
# Connect from asking the "export compliance" question on every single build/TestFlight upload.
"$PB" -c "Add :ITSAppUsesNonExemptEncryption bool false" "$PLIST" 2>/dev/null \
  || "$PB" -c "Set :ITSAppUsesNonExemptEncryption false" "$PLIST"

# Allow the webview to load our HTTPS origin (we do NOT enable arbitrary cleartext).
"$PB" -c "Delete :NSAppTransportSecurity" "$PLIST" 2>/dev/null || true

echo "Info.plist patched:"
"$PB" -c "Print :NSCameraUsageDescription" "$PLIST"
"$PB" -c "Print :NSMicrophoneUsageDescription" "$PLIST"
