#!/usr/bin/env bash
# bump-version.sh — bump the app version everywhere in lockstep.
#
# Usage:
#   ./scripts/bump-version.sh 1.0.2
#
# Bumps:
#   1. frontend/package.json            → "version"
#   2. frontend/android/app/build.gradle → versionName  + versionCode (auto-increment)
#
# After running, rebuild the APK (yarn cap:build && cd android && ./gradlew assembleRelease)
# and upload it to your server. Then on /admin (or the PHP admin panel) set
# "Latest version" to the same number — users on the OLD apk will see the
# popup, users on the NEW apk will not.
set -euo pipefail

if [ "$#" -ne 1 ]; then
  echo "Usage: $0 <new-version>   e.g. $0 1.0.2" >&2
  exit 1
fi

NEW_VERSION="$1"

if ! [[ "$NEW_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Refusing: '$NEW_VERSION' is not a valid semver (X.Y.Z)." >&2
  exit 2
fi

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PKG="$REPO_ROOT/frontend/package.json"
GRADLE="$REPO_ROOT/frontend/android/app/build.gradle"

# 1. package.json
node -e "const fs=require('fs');const p='$PKG';const j=JSON.parse(fs.readFileSync(p,'utf8'));j.version='$NEW_VERSION';fs.writeFileSync(p,JSON.stringify(j,null,2)+'\n');console.log('package.json →', j.version);"

# 2. build.gradle
CURRENT_CODE="$(grep -oE 'versionCode[[:space:]]+[0-9]+' "$GRADLE" | awk '{print $2}')"
NEW_CODE=$((CURRENT_CODE + 1))
sed -i.bak -E \
  -e "s/versionCode[[:space:]]+[0-9]+/versionCode ${NEW_CODE}/" \
  -e "s/versionName[[:space:]]+\"[^\"]+\"/versionName \"${NEW_VERSION}\"/" \
  "$GRADLE"
rm -f "${GRADLE}.bak"
echo "build.gradle  → versionName ${NEW_VERSION}, versionCode ${NEW_CODE}"

cat <<MSG

Done. Now:
  1. Rebuild the APK:
       cd frontend && yarn cap:sync && cd android && ./gradlew assembleRelease
  2. Upload the .apk to your server (e.g. https://4kmovies.vip/.../nadiplayer-${NEW_VERSION}.apk).
  3. Open the admin panel (in-app /admin OR PHP /nadiplayer/admin_panel/) →
     In-App Update → set "Latest version" = ${NEW_VERSION} → set the new APK URL → Save.
  4. Users on older APKs will see the popup once; users on ${NEW_VERSION} won't.

⚠️  SIGNING REMINDER
   Make sure frontend/android/keystore.properties exists. If it doesn't,
   the APK will be signed with a throwaway debug key and users will get
   "App not installed as package conflicts with an existing package".
   First time? Run: ./scripts/generate-release-keystore.sh
   See: RELEASE_SIGNING.md
MSG
