#!/bin/bash
#
# Sets CFBundleVersion + CFBundleShortVersionString on the app target's Info.plist
# at build time:
#   CFBundleVersion            = git commit count
#   CFBundleShortVersionString = YYYY.M.<commit-count>
#
# Declares "$(TARGET_BUILD_DIR)/$(INFOPLIST_PATH)" as an input so Xcode schedules
# this AFTER ProcessInfoPlistFile; otherwise the stamped version is lost in
# parallel Release builds. (Ported from AppVersionChecker.)

set -euo pipefail

git_bin=$(command -v git || true)
if [ -z "$git_bin" ]; then
  for cand in /usr/bin/git /opt/homebrew/bin/git /usr/local/bin/git; do
    if [ -x "$cand" ]; then git_bin="$cand"; break; fi
  done
fi

number_of_commits=$("$git_bin" -C "${SRCROOT:-.}" rev-list HEAD --count 2>/dev/null || echo "0")
year=$(date +%Y)
month=$(date +%-m)
short_version="${year}.${month}.${number_of_commits}"

target_plist="${TARGET_BUILD_DIR}/${INFOPLIST_PATH}"

if [ ! -f "$target_plist" ]; then
  echo "error: built Info.plist not found at $target_plist — version not stamped" >&2
  exit 1
fi

/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $number_of_commits" "$target_plist"
/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $short_version" "$target_plist"

dsym_plist="${DWARF_DSYM_FOLDER_PATH:-}/${DWARF_DSYM_FILE_NAME:-}/Contents/Info.plist"
if [ -f "$dsym_plist" ]; then
  /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $number_of_commits" "$dsym_plist"
  /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $short_version" "$dsym_plist"
fi
