#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$SCRIPT_DIR"
SDK_DIR="$PROJECT_DIR/android-sdk"
NDK_DIR="$SDK_DIR/ndk/27.2.12479018"
TOOLBIN="$NDK_DIR/toolchains/llvm/prebuilt/linux-x86_64/bin"
TMP_DIR="$PROJECT_DIR/.tmp-android-build"
GIT_SRC_DIR="$TMP_DIR/git-src"
JNI_LIB_DIR="$PROJECT_DIR/app/src/main/jniLibs/arm64-v8a"

log() {
  printf '\n[%s] %s\n' "cross-compile" "$1"
}

require_path() {
  if [ ! -e "$1" ]; then
    echo "Required path not found: $1" >&2
    exit 1
  fi
}

require_tool() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Missing required tool: $1" >&2
    exit 1
  fi
}

main() {
  require_tool git
  require_tool make
  require_tool perl
  require_tool clang
  require_tool pkg-config
  require_tool readelf

  require_path "$NDK_DIR"
  require_path "$TOOLBIN/aarch64-linux-android24-clang"

  mkdir -p "$TMP_DIR"

  if [ ! -d "$GIT_SRC_DIR/.git" ]; then
    log "Cloning Git source"
    git clone --depth 1 https://github.com/git/git.git "$GIT_SRC_DIR"
  else
    log "Using existing Git source checkout"
  fi

  export PATH="$TOOLBIN:$PATH"

  log "Building native Git for Android arm64-v8a"
  cd "$GIT_SRC_DIR"
  make clean >/dev/null 2>&1 || true
  make -j4 \
    uname_S=Android \
    uname_O=Android \
    NO_PTHREADS=YesPlease \
    NO_OPENSSL=YesPlease \
    NO_CURL=YesPlease \
    NO_EXPAT=YesPlease \
    NO_GETTEXT=YesPlease \
    NO_TCLTK=YesPlease \
    NO_PERL=YesPlease \
    NO_PYTHON=YesPlease \
    NO_INSTALL_HARDLINKS=YesPlease \
    NO_ICONV=YesPlease \
    NO_LIBGEN_H=YesPlease \
    NO_REGEX=NeedsStartEnd \
    HAVE_ALLOCA_H=YesPlease \
    HAVE_PATHS_H=YesPlease \
    HAVE_DEV_TTY=YesPlease \
    HAVE_CLOCK_GETTIME=YesPlease \
    HAVE_CLOCK_MONOTONIC=YesPlease \
    HAVE_GETDELIM=YesPlease \
    FREAD_READS_DIRECTORIES=UnfortunatelyYes \
    CSPRNG_METHOD= \
    CC=aarch64-linux-android24-clang \
    AR=llvm-ar \
    RANLIB=llvm-ranlib \
    STRIP=llvm-strip \
    git

  log "Validating the produced binary"
  file git
  readelf -h git | sed -n '1,20p'
  readelf -d git | sed -n '1,40p'

  mkdir -p "$JNI_LIB_DIR"
  llvm-strip -s git -o "$JNI_LIB_DIR/libgit.so"
  chmod 755 "$JNI_LIB_DIR/libgit.so"

  log "Bundled stripped binary at: $JNI_LIB_DIR/libgit.so"
  ls -lh "$JNI_LIB_DIR/libgit.so"
}

main "$@"