#!/bin/bash

NDK=$ANDROID_NDK_ROOT
SDK=`grep sdk.dir local.properties | tr '=' '\n' | tail -1`
package="net.momodalo.app.vimtouch"

if ! [ -f $NDK/ndk-build ] ; then
    # If ANDROID_NDK_ROOT is not set, try this heuristics: look up all the
    # siblings of SDK that start with 'android-ndk*', sort them by revision and
    # pick the latest one
    parent=$(dirname $SDK)
    all_ndks=`find $parent -maxdepth 1 -type d -name android-ndk* -printf '%f\n'`
    latest_ndk=`echo $all_ndks | tr ' ' '\n' | sort -t'r' -k3n | tail -1`
    NDK=$(dirname $SDK)/$latest_ndk

    # If still nothing, well, then bark and quit
    if ! [ -f $NDK/ndk-build ] ; then
        echo Android NDK not found. Please export ANDROID_NDK_ROOT. Exiting.
        exit
    fi
fi

function build {
    set -e
    ant debug
    ant installd
    $SDK/platform-tools/adb shell am start -n $package/.VimTouch
}

function build_native {
    set -e
    gen_signatures
    $NDK/ndk-build -j`grep -c ^processor /proc/cpuinfo`
}

function gen_signatures {
    signatures="./gen/signatures.h"
    echo "#ifndef SIGNATURES_H__" > $signatures
    echo "#define SIGNATURES_H__" >> $signatures
    echo "" >> $signatures

    class="./bin/classes/`echo $package | tr '.' '/'`/Exec"
    javap -s $class \
        | awk '/native/,/Signature/{ print };' \
        | awk '/Signature/{ print "\011\042"$2"\042;\n"; next }{ split($5,a1,/\(/); print "char const* jni_signature_"a1[1]" = " };' \
        >> $signatures

    echo "#endif // SIGNATURES_H__" >> $signatures
}

if [ $# -eq 0 ] ; then
    build
    exit
fi

if [ $1 == "lint" ] ; then
    $SDK/tools/lint .
fi

case $1 in
    "lint")
        $SDK/tools/lint .
        ;;
    "rm")
        $SDK/platform-tools/adb uninstall $package
        ;;
    "log")
        $SDK/platform-tools/adb logcat
        ;;
    "adb")
        shift
        $SDK/platform-tools/adb $*
        ;;
    "buildnative")
        build_native
        ;;
esac
