#!/usr/bin/env bash
# build.sh — Build native-hello-android.
#
# Usage:
#   ./build.sh           # regenerate C sources + ./gradlew assembleDebug
#   ./build.sh gen       # regenerate C sources only
#   ./build.sh gradle    # run ./gradlew assembleDebug (skip elc step)
#   ./build.sh clean     # clean Gradle build outputs
#
# Requirements:
#   - Android SDK with NDK and CMake installed
#   - local.properties present (copy from local.properties.template and edit sdk.dir)
#   - Java 11+ on PATH (for Gradle)
#   - elc at ../../../lang/dist/platform/elc

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
EL_LANG_ROOT="${SCRIPT_DIR}/../../../lang"
EL_UI_ROOT="${SCRIPT_DIR}/../.."
EL_RUNTIME="${EL_LANG_ROOT}/el-compiler/runtime"
EL_NATIVE_VESSEL="${EL_UI_ROOT}/vessels/el-native/src/main.el"
EL_APP_ENTRY="${EL_UI_ROOT}/examples/native-hello/src/main.el"
EL_MANIFEST="${EL_UI_ROOT}/examples/native-hello/manifest.el"
JNI_DIR="${SCRIPT_DIR}/app/src/main/jni"

# Locate elc.
if command -v elc &>/dev/null; then
    ELC="elc"
elif [ -x "${EL_LANG_ROOT}/dist/platform/elc" ]; then
    ELC="${EL_LANG_ROOT}/dist/platform/elc"
else
    echo "Error: elc not found. Add it to PATH or place it at:"
    echo "  ${EL_LANG_ROOT}/dist/platform/elc"
    exit 1
fi

gen() {
    echo "==> Generating native_hello.c..."
    EL_MANIFEST="${EL_MANIFEST}" \
        "${ELC}" "${EL_APP_ENTRY}" \
        > "${JNI_DIR}/native_hello.c"

    echo "==> Generating el_native_vessel.c..."
    "${ELC}" "${EL_NATIVE_VESSEL}" \
        > "${JNI_DIR}/el_native_vessel.c"
    # Rename the vessel's main() to avoid symbol collision with native_hello.c's main().
    # The Android JNI entry point (nativeMain) calls native_hello.c's main() explicitly.
    sed -i '' 's/^int main(int _argc, char\*\* _argv) {/int el_vessel_main(int _argc, char** _argv) {/' \
        "${JNI_DIR}/el_native_vessel.c" 2>/dev/null || \
    sed -i 's/^int main(int _argc, char\*\* _argv) {/int el_vessel_main(int _argc, char** _argv) {/' \
        "${JNI_DIR}/el_native_vessel.c"

    echo "==> C source generation complete."
}

gradle_build() {
    echo "==> Running ./gradlew assembleDebug..."
    cd "${SCRIPT_DIR}"
    ./gradlew assembleDebug

    APK_PATH="${SCRIPT_DIR}/app/build/outputs/apk/debug/app-debug.apk"
    if [ -f "${APK_PATH}" ]; then
        echo "==> Build complete."
        echo "    APK: ${APK_PATH}"
    else
        echo "==> Build complete (APK path may differ — check app/build/outputs/apk/)."
    fi
}

clean() {
    echo "==> Cleaning..."
    cd "${SCRIPT_DIR}"
    ./gradlew clean
    echo "==> Clean complete."
}

case "${1:-all}" in
    gen)    gen ;;
    gradle) gradle_build ;;
    clean)  clean ;;
    all|*)  gen && gradle_build ;;
esac
