#!/usr/bin/env bash
# fail if any commands fail
set -e
# make pipelines' return status equal the last command to exit with a non-zero status, or zero if all commands exit successfully
set -o pipefail
# debug log
set -x

# Parse tag: v<major>.<minor>.<patch>-<env>-<iteration>
if [[ ! "$BITRISE_GIT_TAG" =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)-(stg|dev|prod)-([0-9]+)$ ]]; then
    echo "Bad format for git tag"
    exit 1
fi

MAJOR="${BASH_REMATCH[1]}"
MINOR="${BASH_REMATCH[2]}"
PATCH="${BASH_REMATCH[3]}"
ITERATION="${BASH_REMATCH[5]}"

# Semantic build number — same formula used in android/app/build.gradle so
# iOS and Android stay in sync. Encodes major.minor.patch.iteration into a
# single monotonically increasing integer.
# Layout: MMM_mm_pp_iii (max: major=214, minor=99, patch=99, iteration=999).
BUILD_NUMBER=$((MAJOR * 10000000 + MINOR * 100000 + PATCH * 1000 + ITERATION))

echo "Using BUILD_NUMBER: $BUILD_NUMBER"

# Update Info.plist with the new build number for Humand
INFO_PLIST_PATH="ios/humand/Info.plist"
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $BUILD_NUMBER" "$INFO_PLIST_PATH"

# Update Info.plist with the new build number for ImageNotification
IMAGE_NOTIFICATION_INFO_PLIST_PATH="ios/ImageNotification/Info.plist"
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $BUILD_NUMBER" "$IMAGE_NOTIFICATION_INFO_PLIST_PATH"
