#!/usr/bin/env sh
# Pin an explicit, monotonic Android versionCode.
#
# Tauri derives one from the semver as
#
#   major * 1000000 + minor * 1000 + patch
#
# which is monotonic but leaves the pre-1.0 series crowded down at the bottom of
# the range: 0.1.0 is versionCode 1000. Android refuses to install an APK whose
# versionCode is not greater than the installed one, and a rider who cannot
# update is a rider who stops updating, so this pins the number rather than
# leaving it to a default that a Tauri upgrade could change under us:
#
#   code = 1000 + major * 10000 + minor * 100 + patch
#
# so 0.1.0 -> 1100, 0.1.3 -> 1103, 0.2.0 -> 1200, 1.0.0 -> 11000. Monotonic in
# semver order for any minor/patch below 100, which is well past where this
# project will ever get.
#
# The 1000 floor is not decoration: Tauri's default gives 0.1.0 versionCode
# 1000, so anyone carrying an APK from before this script already has that
# number installed. A bare major/minor/patch code would be 100 — a *downgrade*,
# which Android refuses outright.
#
# This writes bundle.android.versionCode in tauri.conf.json, NOT
# gen/android/app/tauri.properties. tauri.properties is generated by
# `cargo tauri android build`, not by `android init` — it does not exist at init
# time, and the build overwrites it from the config on every run, so an edit
# there is either a crash or a no-op. The config is the only durable input.
#
# POSIX sh: the runner's /bin/sh is dash. No here-strings, no \s in sed.
set -e

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CONF="$ROOT/src-tauri/tauri.conf.json"

VERSION=$(grep '"version"' "$CONF" | head -1 | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
MAJ=$(echo "$VERSION" | cut -d. -f1)
MIN=$(echo "$VERSION" | cut -d. -f2)
PAT=$(echo "$VERSION" | cut -d. -f3)
# Guard a malformed or short version so we can never emit code 0, which Android
# treats as "older than everything".
: "${MAJ:=0}" "${MIN:=0}" "${PAT:=0}"
CODE=$(( 1000 + MAJ * 10000 + MIN * 100 + PAT ))

echo "version=$VERSION -> versionCode=$CODE"

# The key is committed to tauri.conf.json, so a missing one means the config was
# restructured and this sed would otherwise silently do nothing — shipping an
# APK with a stale versionCode that no device would accept as an update.
grep -q '"versionCode"' "$CONF" || {
  echo "❌ no \"versionCode\" key in $CONF — add bundle.android.versionCode back" >&2
  exit 1
}
sed -i "s/\"versionCode\"[[:space:]]*:[[:space:]]*[0-9]*/\"versionCode\": $CODE/" "$CONF"

grep -q "\"versionCode\": $CODE" "$CONF" || {
  echo "❌ failed to set versionCode to $CODE in $CONF" >&2
  exit 1
}
grep -A2 '"android"' "$CONF"
