#!/bin/sh
set -eu

## Notes: platform-aware build info (post-build phase).
##
## Sets, on every build:
##   - CFBundleVersion   = git commit count, platform-partitioned (see below)
##   - BuildDate         = today's date, e.g. 2026-07-14
##   - BuildHash         = short git commit hash
## in both the target Info.plist and its dSYM Info.plist, so IndieAbout's
## version line has something to read.
##
## Platform partitioning: the iOS and macOS targets share one bundle ID and
## therefore one App Store Connect build-number sequence, so stamping both
## with the raw commit count makes the second upload collide ("bundle version
## already used"). iOS gets even numbers, macOS odd — both strictly increase
## with every commit and can never equal each other. (Same scheme as
## QuickRabbit's update_build_number.sh.)

git=$(sh /etc/profile; which git || true)
if [ -z "$git" ] || [ ! -x "$git" ]; then
  echo "error: update_build_number.sh: could not resolve a 'git' executable — refusing to stamp a build number." >&2
  exit 1
fi

number_of_commits=$("$git" rev-list HEAD --count)
case "$number_of_commits" in
  ''|*[!0-9]*)
    echo "error: update_build_number.sh: 'git rev-list HEAD --count' returned '$number_of_commits', not a positive integer." >&2
    exit 1
    ;;
esac

case "${PLATFORM_NAME:-}" in
  macosx*) build_number=$((number_of_commits * 2 + 1)) ;;
  *)       build_number=$((number_of_commits * 2)) ;;
esac

git_commit=$("$git" rev-parse --short HEAD)
build_date=$(date +%F)

target_plist="$TARGET_BUILD_DIR/$INFOPLIST_PATH"
dsym_plist="$DWARF_DSYM_FOLDER_PATH/$DWARF_DSYM_FILE_NAME/Contents/Info.plist"

if [ ! -f "$target_plist" ] && [ ! -f "$dsym_plist" ]; then
  echo "warning: update_build_number.sh: neither $target_plist nor $dsym_plist exists — check the phase's Input Files"
fi

echo "update_build_number: b$build_number ($PLATFORM_NAME) $git_commit $build_date"

for plist in "$target_plist" "$dsym_plist"; do
  if [ -f "$plist" ]; then
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $build_number" "$plist"

    /usr/libexec/PlistBuddy -c "Set :BuildDate $build_date" "$plist" 2>/dev/null || \
    /usr/libexec/PlistBuddy -c "Add :BuildDate string $build_date" "$plist"

    /usr/libexec/PlistBuddy -c "Set :BuildHash $git_commit" "$plist" 2>/dev/null || \
    /usr/libexec/PlistBuddy -c "Add :BuildHash string $git_commit" "$plist"
  fi
done
