#!/usr/bin/env bash
# Re-applies the two patches better-sqlite3 needs to load correctly under
# nodejs-mobile (Node 12.19 / Android x86_64 emulator). Required after any
# fresh `npm install` in nodejs-assets/nodejs-project, since both patches
# target files inside node_modules.
#
# Usage: ./scripts/fix-better-sqlite3-android.sh
# Run from the mobile project root, after `npm install` has already built
# better-sqlite3 once via nodejs-mobile-gyp (so build/better_sqlite3.target.mk
# and the Release/ dir already exist).

set -euo pipefail

MOBILE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PKG_DIR="$MOBILE_DIR/nodejs-assets/nodejs-project/node_modules/better-sqlite3"
LIBNODE="$MOBILE_DIR/android/app/libs/cdvnodejsmobile/libnode/bin/x86_64/libnode.so"

if [[ ! -d "$PKG_DIR" ]]; then
  echo "Error: $PKG_DIR not found. Run npm install in nodejs-assets/nodejs-project first." >&2
  exit 1
fi

# 1. v8::Object::CreationContext() was removed in newer V8; nodejs-mobile's
#    bundled V8 (Node 12.19) only has the old non-checked accessor.
BINDER="$PKG_DIR/src/util/binder.cpp"
if grep -q 'GetCreationContext().ToLocalChecked()' "$BINDER"; then
  sed -i 's/obj->GetCreationContext().ToLocalChecked()/obj->CreationContext()/' "$BINDER"
  echo "Patched $BINDER"
else
  echo "$BINDER already uses CreationContext() (no patch needed)"
fi

# 2. nodejs-mobile-cordova's common.gypi only adds the libnode.so NEEDED entry
#    when target_arch=="x86_64", but gyp reports "x64" for 64-bit x86, so the
#    rule never fires. Add it to LIBS directly so the addon can resolve V8/Node
#    symbols (e.g. v8::Isolate::GetCurrent) at dlopen time on Android.
TARGET_MK="$PKG_DIR/build/better_sqlite3.target.mk"
if [[ ! -f "$TARGET_MK" ]]; then
  echo "Error: $TARGET_MK not found. Run npm install to build better-sqlite3 first." >&2
  exit 1
fi

if ! grep -q "libnode.so" "$TARGET_MK"; then
  sed -i "/^\t-llog \\\\\$/a\\\\\t$LIBNODE" "$TARGET_MK"
  echo "Patched $TARGET_MK"
else
  echo "$TARGET_MK already references libnode.so (no patch needed)"
fi

# Rebuild and relink with the patched sources/Makefile.
cd "$PKG_DIR/build"
rm -f Release/better_sqlite3.node Release/obj.target/better_sqlite3.node
make BUILDTYPE=Release better_sqlite3.node

# Keep the x86_64 prebuild (emulator) in sync — main.js picks the right one
# for the device's process.arch at runtime. arm64-v8a/armeabi-v7a prebuilds
# are produced separately by build-better-sqlite3-arm.sh.
PREBUILD_DIR="$MOBILE_DIR/nodejs-assets/nodejs-project/prebuilds/x86_64"
mkdir -p "$PREBUILD_DIR"
cp "$PKG_DIR/build/Release/better_sqlite3.node" "$PREBUILD_DIR/better_sqlite3.node"

echo "Done. Verify with: readelf -d \"$PKG_DIR/build/Release/better_sqlite3.node\" | grep libnode"
