#!/usr/bin/env bash
# Fail if any hand-written Android source has ended up only in gen/android.
#
# src-tauri/gen/ is not tracked and `tauri android init` rewrites it, so a
# Kotlin file edited *there* is a file that will be silently deleted by the next
# init and has never existed in git. That failure is quiet in exactly the wrong
# way: the build keeps working locally for as long as nobody re-inits, and then
# a CI release APK ships without whatever the file did.
#
# Every source under gen/android/app/src/main/java must therefore be one of:
#
#   1. Tauri's own, under <pkg>/generated/ and carrying the AUTO-GENERATED
#      banner. Regenerated on every init; not ours to keep.
#   2. A copy of a tracked file in src-tauri/android/, byte for byte. If it
#      differs, the edit was made in gen/ and is about to be lost.
#   3. Vendored from a crate by sync-android-sources.sh — the btleplug and
#      jni-utils Java backends.
#
# Anything else is hand-written and untracked, and this exits non-zero.
#
#   scripts/check-android-sources.sh
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TRACKED="$ROOT/src-tauri/android/src/main/java"
GEN="$ROOT/src-tauri/gen/android/app/src/main/java"

if [ ! -d "$GEN" ]; then
  echo "ℹ️  No generated Android project — nothing to check."
  echo "   (run 'cargo tauri android init' then scripts/sync-android-sources.sh)"
  exit 0
fi

fail=0
drift=0

while IFS= read -r file; do
  rel="${file#"$GEN"/}"

  case "$rel" in
    # 3. Vendored from the crates.
    com/nonpolynomial/btleplug/*|io/github/gedgygedgy/rust/*)
      continue
      ;;
  esac

  # 1. Tauri's own.
  if [ "${rel#*/generated/}" != "$rel" ] && head -8 "$file" | grep -q 'AUTO-GENERATED'; then
    continue
  fi

  # 2. Ours — must exist in src-tauri/android and match.
  if [ -f "$TRACKED/$rel" ]; then
    if ! cmp -s "$TRACKED/$rel" "$file"; then
      echo "❌ $rel differs from the tracked copy."
      echo "   Edited in gen/ — the next 'tauri android init' will delete it."
      echo "   Move the change into src-tauri/android/src/main/java/$rel"
      drift=1
    fi
    continue
  fi

  echo "❌ $rel is hand-written and untracked."
  echo "   Move it to src-tauri/android/src/main/java/$rel and add it to the"
  echo "   copy list in scripts/sync-android-sources.sh."
  fail=1
done < <(find "$GEN" -type f \( -name '*.kt' -o -name '*.java' \))

# The other direction: a tracked source the sync script never copies is dead
# code that looks live.
while IFS= read -r file; do
  rel="${file#"$TRACKED"/}"
  if [ ! -f "$GEN/$rel" ]; then
    echo "❌ src-tauri/android/src/main/java/$rel is tracked but never reached gen/."
    echo "   Add it to scripts/sync-android-sources.sh, or delete it."
    fail=1
  fi
done < <(find "$TRACKED" -type f \( -name '*.kt' -o -name '*.java' \) 2>/dev/null || true)

if [ "$fail" = 1 ] || [ "$drift" = 1 ]; then
  exit 1
fi

echo "✅ Every hand-written Android source is tracked in src-tauri/android/"
