Fixes to the SL4A Build System

-Fix missing native libraries when rebuilt.
-Fix missing native libraries when not bundled on system.img
-Remove old shared libraries from project
-Fix a reflection bug passing wrong parameters to constructor
-Remove duplicate sdk/version version info from manifests
-Remove duplicate permissions from sl4a/AndroidManifest
-Remove deprecated build_all.sh script

Bug: 26139229
Bug: 26119338
Change-Id: Ibb1c971de2f3596913a084561f35261690faf0d1
diff --git a/sl4a/Android.mk b/sl4a/Android.mk
new file mode 100644
index 0000000..b00a67d
--- /dev/null
+++ b/sl4a/Android.mk
@@ -0,0 +1,6 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
+
diff --git a/sl4a/Common/src/com/googlecode/android_scripting/jsonrpc/RpcReceiverManager.java b/sl4a/Common/src/com/googlecode/android_scripting/jsonrpc/RpcReceiverManager.java
index 029fc15..c1e1e76 100644
--- a/sl4a/Common/src/com/googlecode/android_scripting/jsonrpc/RpcReceiverManager.java
+++ b/sl4a/Common/src/com/googlecode/android_scripting/jsonrpc/RpcReceiverManager.java
@@ -22,6 +22,7 @@
 import java.util.HashMap;
 import java.util.Map;
 
+import com.googlecode.android_scripting.facade.FacadeManager;
 import com.googlecode.android_scripting.Log;
 import com.googlecode.android_scripting.rpc.MethodDescriptor;
 
@@ -63,7 +64,7 @@
 
         Constructor<? extends RpcReceiver> constructor;
         try {
-            constructor = clazz.getConstructor(getClass());
+            constructor = clazz.getConstructor(FacadeManager.class);
             object = constructor.newInstance(this);
             mReceivers.put(clazz, object);
         } catch (Exception e) {
diff --git a/sl4a/QuickAction/AndroidManifest.xml b/sl4a/QuickAction/AndroidManifest.xml
index dbc6573..7b78457 100644
--- a/sl4a/QuickAction/AndroidManifest.xml
+++ b/sl4a/QuickAction/AndroidManifest.xml
@@ -17,9 +17,8 @@
 */
 -->
 
-<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
-	package="net.londatiga.android"
-    android:versionCode="1"
-    android:versionName="1.0">
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="net.londatiga.android">
     <application android:icon="@drawable/icon" android:label="@string/app_name"/>
-</manifest> 
\ No newline at end of file
+</manifest>
+
diff --git a/sl4a/ScriptingLayerForAndroid/Android.mk b/sl4a/ScriptingLayerForAndroid/Android.mk
index 7ca725e..ab4e6d6 100644
--- a/sl4a/ScriptingLayerForAndroid/Android.mk
+++ b/sl4a/ScriptingLayerForAndroid/Android.mk
@@ -14,10 +14,13 @@
 #  limitations under the License.
 #
 
+
 LOCAL_PATH := $(call my-dir)
 
 include $(CLEAR_VARS)
 
+LOCAL_MODULE_TAGS := optional
+
 LOCAL_PACKAGE_NAME := sl4a
 LOCAL_MODULE_OWNER := google
 LOCAL_DEX_PREOPT := false
@@ -29,6 +32,11 @@
 
 LOCAL_AAPT_FLAGS := --auto-add-overlay
 
+LOCAL_MULTILIB := both
+
+# Builds on the Data Partition
+#LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
 LOCAL_STATIC_JAVA_LIBRARIES := guava android-common locale_platform android-support-v4
 LOCAL_STATIC_JAVA_LIBRARIES += sl4a.Utils sl4a.Common
 LOCAL_STATIC_JAVA_LIBRARIES += sl4a.InterpreterForAndroid sl4a.ScriptingLayer sl4a.QuickAction
@@ -36,15 +44,16 @@
 LOCAL_PRIVILEGED_MODULE := true
 LOCAL_PROGUARD_ENABLED := disabled
 
+
+LOCAL_JNI_SHARED_LIBRARIES := libcom_googlecode_android_scripting_Exec
+
+include $(PREBUILT_SHARED_LIBRARY)
+
 include $(BUILD_PACKAGE)
 
 include $(CLEAR_VARS)
 LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := locale_platform:libs/locale_platform.jar
 include $(BUILD_MULTI_PREBUILT)
 
-
-# only include rules to build other stuff for the original package, not the derived package.
-#ifeq ($(strip $(LOCAL_PACKAGE_OVERRIDES)),)
-# additionally, build unit tests in a separate .apk
 include $(call all-makefiles-under,$(LOCAL_PATH))
-#endif
+
diff --git a/sl4a/ScriptingLayerForAndroid/AndroidManifest.xml b/sl4a/ScriptingLayerForAndroid/AndroidManifest.xml
index 69750a2..b715d5d 100644
--- a/sl4a/ScriptingLayerForAndroid/AndroidManifest.xml
+++ b/sl4a/ScriptingLayerForAndroid/AndroidManifest.xml
@@ -17,8 +17,10 @@
 */
 -->
 
-<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.googlecode.android_scripting" android:installLocation="auto" android:versionCode="603" android:versionName="6x03"
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.googlecode.android_scripting"
     android:sharedUserId="android.uid.system">
+
     <permission android:name="com.android.permission.WHITELIST_BLUETOOTH_DEVICE"
         android:protectionLevel="signature" />
     <permission android:name="android.permission.ACCESS_BLUETOOTH_SHARE"
@@ -66,8 +68,6 @@
     <uses-permission android:name="android.permission.CAMERA" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
     <uses-permission android:name="android.permission.READ_CONTACTS" />
-    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
     <uses-permission android:name="android.permission.DEVICE_POWER" />
     <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
@@ -83,7 +83,6 @@
     <uses-permission android:name="com.android.certinstaller.INSTALL_AS_USER" />
     <uses-permission android:name="android.permission.CLEAR_APP_USER_DATA" />
     <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
-    <uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />
     <uses-permission android:name="android.permission.ACCESS_CHECKIN_PROPERTIES" />
     <uses-permission android:name="android.permission.READ_USER_DICTIONARY" />
     <uses-permission android:name="android.permission.WRITE_USER_DICTIONARY" />
@@ -91,13 +90,10 @@
     <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
     <uses-permission android:name="android.permission.BATTERY_STATS" />
     <uses-permission android:name="android.permission.MOVE_PACKAGE" />
-    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
     <uses-permission android:name="android.permission.BACKUP" />
     <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
     <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
     <uses-permission android:name="android.permission.READ_SYNC_STATS" />
-    <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
-    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
     <uses-permission android:name="android.permission.STATUS_BAR" />
     <uses-permission android:name="android.permission.MANAGE_USB" />
     <uses-permission android:name="android.permission.SET_POINTER_SPEED" />
@@ -117,7 +113,6 @@
     <uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />
     <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
     <uses-permission android:name="android.permission.RECEIVE_EMERGENCY_BROADCAST"/>
-    <uses-sdk android:targetSdkVersion="10" android:minSdkVersion="3" />
     <application android:icon="@drawable/sl4a_logo_48" android:label="@string/application_title" android:name=".Sl4aApplication">
         <activity android:name=".activity.ScriptManager" android:configChanges="keyboardHidden|orientation" android:windowSoftInputMode="adjustResize" android:launchMode="singleTop">
             <intent-filter>
diff --git a/sl4a/ScriptingLayerForAndroid/jni/Android.mk b/sl4a/ScriptingLayerForAndroid/jni/Android.mk
index 2a3c47a..1c5b96c 100644
--- a/sl4a/ScriptingLayerForAndroid/jni/Android.mk
+++ b/sl4a/ScriptingLayerForAndroid/jni/Android.mk
@@ -18,9 +18,9 @@
 
 include $(CLEAR_VARS)
 
-
 LOCAL_SRC_FILES := com_googlecode_android_scripting_Exec.cpp
 
+LOCAL_CFLAGS += -Wno-unused-parameter
 
 LOCAL_C_INCLUDES += \
     $(JNI_H_INCLUDE) \
@@ -30,9 +30,8 @@
     libnativehelper \
     libcutils \
     libutils \
-    liblog 
+    liblog
 
-LOCAL_MODULE    := com_googlecode_android_scripting_Exec
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE    := libcom_googlecode_android_scripting_Exec
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/sl4a/ScriptingLayerForAndroid/libs/armeabi/libcom_googlecode_android_scripting_Exec.so b/sl4a/ScriptingLayerForAndroid/libs/armeabi/libcom_googlecode_android_scripting_Exec.so
deleted file mode 100644
index 545c0ff..0000000
--- a/sl4a/ScriptingLayerForAndroid/libs/armeabi/libcom_googlecode_android_scripting_Exec.so
+++ /dev/null
Binary files differ
diff --git a/sl4a/ScriptingLayerForAndroid/libs/armeabi/liborg_connectbot_util_EastAsianWidth.so b/sl4a/ScriptingLayerForAndroid/libs/armeabi/liborg_connectbot_util_EastAsianWidth.so
deleted file mode 100644
index 6722290..0000000
--- a/sl4a/ScriptingLayerForAndroid/libs/armeabi/liborg_connectbot_util_EastAsianWidth.so
+++ /dev/null
Binary files differ
diff --git a/sl4a/android.py b/sl4a/android.py
deleted file mode 100644
index 63448a6..0000000
--- a/sl4a/android.py
+++ /dev/null
@@ -1,312 +0,0 @@
-# python3.4
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License"); you may not
-# use this file except in compliance with the License. You may obtain a copy of
-# the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-# License for the specific language governing permissions and limitations under
-# the License.
-
-"""
-JSON RPC interface to android scripting engine.
-
-Example:
-    a = Android()
-    a.makeToast("poptart")
-    a.close()
-
-Also supports serializing data objects (class instances). Register them with the android client object.
-
-
-class Mydata:
-    def __init__(self, value):
-        self.value = value
-
-a = Android()
-a.register(Mydata)
-
-data = Mydata(2)
-a.makeCall(data)
-a.close()
-
-This feature requires support on the SL4A side for the Jackson ObjectMapper.
-
-http://jackson.codehaus.org/1.7.3/javadoc/org/codehaus/jackson/map/ObjectMapper.html
-
-Where you also need a POJO on the server side. Otherwise this feature cannot be used.
-"""
-
-__author__ = 'Keith Dart <dart@google.com>'
-__oldauthor__ = 'Damon Kohler <damonkohler@gmail.com>'
-
-import os
-import sys
-import socket
-import logging
-from json.decoder import JSONDecoder
-from json.encoder import JSONEncoder
-
-
-HOST = os.environ.get('AP_HOST', None)
-PORT = os.environ.get('AP_PORT', 9999)
-
-LAUNCH_CMD=("adb {} shell am start -a com.googlecode.android_scripting.action.LAUNCH_SERVER "
-        "-n com.googlecode.android_scripting/.activity.ScriptingLayerServiceLauncher "
-        "--ei com.googlecode.android_scripting.extra.USE_SERVICE_PORT {}")
-
-class SL4AException(Exception):
-    pass
-
-class SL4AAPIError(SL4AException):
-    """Raised when remote API reports an error."""
-
-class SL4AProtocolError(SL4AException):
-    """Raised when there is some error in exchanging data with server on device."""
-
-
-class AndroidJSONDecoder(JSONDecoder):
-    def __init__(self):
-        super().__init__(object_hook=self._decode_object, parse_float=None, parse_int=None,
-                parse_constant=None, strict=True, object_pairs_hook=None)
-        self._regs = {}
-
-    def _decode_object(self, d):
-        if "@class" in d:
-            cname = d.pop("@class")
-            cls = _load_class(cname)
-            o = cls.__new__(cls)
-            while d:
-                k, v = d.popitem()
-                setattr(o, k, v)
-            return o
-        else:
-            return d
-
-    def register(self, cls, decoder=None):
-        self._regs[cls] = decoder
-
-    def decode(self, s):
-        return super().decode(str(s, encoding="utf8"))
-
-
-def _load_class(path):
-    modname, clsname = path.rsplit(".", 1)
-    try:
-        mod = sys.modules[modname]
-    except KeyError:
-        pass
-    __import__(modname)
-    mod = sys.modules[modname]
-    return getattr(mod, clsname)
-
-
-class AndroidJSONEncoder(JSONEncoder):
-    def __init__(self):
-        super().__init__ (skipkeys=False, ensure_ascii=False,
-                check_circular=True, allow_nan=True, sort_keys=False,
-                indent=None, separators=None, default=None)
-        self._regs = {}
-
-    def default(self, o):
-        try:
-            encoder = self._regs[type(o)]
-        except KeyError:
-            return super().default(o)
-        if encoder is not None:
-            return encoder(o)
-        d = o.__dict__.copy()
-        t = type(o)
-        d["@class"] = "{}.{}".format(t.__module__, t.__name__)
-        return d
-
-    def encode(self, o):
-        s = super().encode(o)
-        return s.encode("utf8")+b'\n'
-
-    def register(self, cls, encoder=None):
-        self._regs[cls] = encoder
-
-
-def IDCounter():
-    i = 0
-    while True:
-        yield i
-        i += 1
-
-class Android(object):
-    """Client interface to SL4A server running on Android.
-
-    Supports generic calling to SL4A APIs by getting an API method as an attribute.
-
-    Example:
-        a = Android()
-        a.makeToast("poptart")
-    """
-    COUNTER = IDCounter()
-
-    def __init__(self, cmd='initiate', uid=-1, port=PORT, addr=HOST):
-        self.client = None # prevent close errors on connect failure
-        self.uid = None
-        self._encoder = AndroidJSONEncoder()
-        self._decoder = AndroidJSONDecoder()
-        conn = socket.create_connection((addr, port))
-        self.client = conn.makefile(mode="brw")
-        handshake = {'cmd':cmd, 'uid':uid}
-        self.client.write(self._encoder.encode(handshake))
-        self.client.flush()
-        resp = self.client.readline(36384)
-        if not resp:
-            raise SL4AProtocolError("No response from handshake.")
-        result = self._decoder.decode(resp)
-        if result['status']:
-          self.uid = result['uid']
-        else:
-          self.uid = -1
-
-    def close(self):
-        if self.client is not None:
-            c = self.client
-            self.client = None
-            try:
-                # TODO gracefully terminate session when supported on server side.
-                # e.g.: c.write(self._encoder.encode({"cmd":"terminate", "uid":self.uid}))
-                c.close()
-            except (ValueError, OSError):
-                logging.warn("Closing Android interface that was already closed.")
-
-    def __del__(self):
-        self.close()
-
-    def register(self, cls, encoder=None, decoder=None):
-        """Register a class object that will support serialization to and
-        from sl4a server.
-
-        Different encoder and decoder callables may be supplied. If not
-        supplied, generic ones will be used.
-
-        A factory function can register objects as server side POJOs are developed.
-        """
-        self._encoder.register(cls, encoder)
-        self._decoder.register(cls, decoder)
-
-    def _rpc(self, method, *args):
-        apiid = next(Android.COUNTER)
-        data = {'id': apiid,
-                    'method': method,
-                    'params': args}
-        self.client.write(self._encoder.encode(data))
-        self.client.flush()
-        response = self.client.readline(16384)
-        if not response:
-            raise SL4AProtocolError("No response from server.")
-        result = self._decoder.decode(response)
-        if result['error']:
-            raise SL4AAPIError(result['error'])
-        if result['id'] != apiid:
-            raise SL4AProtocolError("Mismatched API id")
-        return result['result']
-
-    def __getattr__(self, name):
-        def rpc_call(*args):
-            return self._rpc(name, *args)
-        return rpc_call
-
-
-def start_forwarding(port, localport=PORT,serial=""):
-    if serial:
-        serial = " -s " + serial
-    os.system("adb {} forward tcp:{} tcp:{}".format(serial,localport, port))
-
-
-def kill_adb_server(serial=""):
-    if serial:
-        serial = " -s " + serial
-    os.system("adb {} kill-server".format(serial))
-
-
-def start_adb_server(serial=""):
-    if serial:
-        serial = " -s "+serial
-    os.system("adb {} start-server".format(serial))
-
-
-def start_sl4a(port=8080,serial=""):
-    if is_sl4a_running(serial):
-        return
-    start_adb_server(serial)
-    if serial:
-        serial = " -s " + serial
-    os.system(LAUNCH_CMD.format(serial,port))
-
-def is_sl4a_running(serial=""):
-    if serial:
-      serial = " -s " + serial
-    status = os.system("adb {} shell ps | grep com.googlecode.android_scripting".format(serial))
-    return status != 256
-
-def android(argv):
-    import getopt
-
-    def _usage():
-        print("""Usage: android [-p <remoteport>] [-l <localport>] [-u <uid>] <apicall>|start [<apiargs>...]
-            Example: android.py -p 8080 makeToast hello""")
-
-    localport = PORT
-    port = 8080
-    uid = -1
-    cmd = "initiate"
-    try:
-        opts, args = getopt.getopt(argv[1:], "l:p:u:", ["localport=", "port=", "uid="])
-    except getopt.GetoptError:
-        _usage()
-        return
-    for opt, optarg in opts:
-        if opt in ("-p", "--port"):
-            try:
-                port = int(optarg)
-            except ValueError:
-                _usage()
-                return
-        elif opt in ("-u", "--uid"):
-            try:
-                uid = int(optarg)
-            except ValueError:
-                _usage()
-                return
-            cmd = "continue"
-        elif opt in ("-l", "--localport"):
-            try:
-                localport = int(optarg)
-            except ValueError:
-                _usage()
-                return
-
-    if not args:
-        _usage()
-        return
-
-    if args[0] == "start":
-        kill_adb_server()
-        start_adb_server()
-        start_sl4a(port)
-        return
-
-    if cmd == "initiate":
-        start_forwarding(port, localport)
-
-    a = Android(cmd=cmd, uid=uid, port=localport)
-    print ("UID:", a.uid)
-    rpc = getattr(a, args[0])
-    rpc(*args[1:])
-    a.close()
-
-
-# Run as top-level script for handy test utility
-if __name__ == "__main__":
-    android(sys.argv)
diff --git a/sl4a/build_all.sh b/sl4a/build_all.sh
deleted file mode 100755
index 0b0db14..0000000
--- a/sl4a/build_all.sh
+++ /dev/null
@@ -1,159 +0,0 @@
-#! /bin/bash
-
-#
-#  Copyright (C) 2015 Google, Inc.
-#
-#  Licensed under the Apache License, Version 2.0 (the "License");
-#  you may not use this file except in compliance with the License.
-#  You may obtain a copy of the License at:
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-#  Unless required by applicable law or agreed to in writing, software
-#  distributed under the License is distributed on an "AS IS" BASIS,
-#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#  See the License for the specific language governing permissions and
-#  limitations under the License.
-#
-
-#This script does a clean build of sl4a and install it to your device through adb
-#Requires envsetup.sh in the branch
-
-#function to change jdk version
-function setup_jdk() {
-  # Remove the current JDK from PATH
-  if [ -n "${JAVA_HOME}" ] ; then
-    PATH=${PATH/${JAVA_HOME}\/bin:/}
-  fi
-  export JAVA_HOME=${1}
-  export PATH=${JAVA_HOME}/bin:${PATH}
-}
-
-#Color code for echo
-r='\e[0;31m'
-brn='\e[0;33m'
-y='\e[1;33m'
-g='\e[0;32m'
-cy='\e[0;36m'
-lb='\e[1;34m'
-p='\e[0;35m'
-lg='\e[0;37m'
-NC='\e[0m' # No Color
-
-echo -e "Welcome to ${r}U${brn}N${y}I${g}C${lb}O${cy}R${p}N${NC} build system for ${g}sl4a${NC}"
-
-#List of sl4a dependency libs to be built in order
-declare -a lib_list=("Utils" "Common" "InterpreterForAndroid" "ScriptingLayer" "QuickAction")
-
-declare -a test_list=("Utils" "Common")
-
-#ensure that user has exported a lunch target
-[ -z "${TARGET_PRODUCT}" ] && echo "Please choose a lunch target prior to running!" && exit 1
-
-#If target is aosp_ then cut the prefix for build directory
-export TP=$(echo ${TARGET_PRODUCT} | sed "s/aosp_//")
-
-APP_NAME=sl4a
-APP_PACKAGE_NAME=com.googlecode.android_scripting
-
-BRANCH_ROOT=${PWD}/../../../../..
-SL4A_ROOT=${BRANCH_ROOT}/packages/apps/Test/connectivity/sl4a
-SHARED_LIB_JAR_ROOT=${BRANCH_ROOT}/out/target/common/obj/JAVA_LIBRARIES
-APP_JAR_ROOT=${BRANCH_ROOT}/out/target/common/obj/APPS
-APK_ROOT=${BRANCH_ROOT}/out/target/product/${TP}/system/priv-app/sl4a
-SL4A_PROJ_DIR=${SL4A_ROOT}/ScriptingLayerForAndroid
-
-function sl4a_build {
-
-echo -e "${y}Removing intermediates of all the dependency libs${NC}"
-for i in "${lib_list[@]}"
-do
-  rm -r ${SHARED_LIB_JAR_ROOT}/sl4a."${i}"_intermediates
-done
-
-echo -e "${y}Removing intermeidates of the app${NC}"
-rm -r ${APP_JAR_ROOT}/"${APP_NAME}"_intermediates
-#Remove the apk file
-rm ${APK_ROOT}/"${APP_NAME}".apk
-
-#Build all the dependency libs
-. ${BRANCH_ROOT}/build/envsetup.sh
-
-exec () {
-  ${@:1:($#-1)}
-  if [ $? -ne 0 ]; then
-    echo -e "${r}Encountered error when ${@:$#}${NC}"
-    echo -e "${lg}UNICORN ${r}DIED${NC}!"
-    exit 1
-  fi
-}
-
-
-for i in "${lib_list[@]}"
-do
-  echo -e "${lb}+++++++ Building ${i} +++++++${NC}"
-  cd $SL4A_ROOT/"${i}"
-  exec mm -j8 -B "building ${i}"
-  echo
-done
-
-echo -e "${lb}+++++++ Building ${APP_NAME}.apk +++++++${NC}"
-cd ${SL4A_PROJ_DIR}
-exec mm -j8 -B "building ${APP_NAME}.apk"
-echo
-
-}
-
-function sl4a_flash {
-for SERIAL in $(adb devices | tail -n +2 | cut -sf 1);
-do
-  if [ "${SELECT_SERIAL}" == "0" ] || [ "${SELECT_SERIAL}" == "${SERIAL}" ]; then
-    echo "flashing serial number = ${SERIAL}"
-    export ANDROID_SERIAL="${SERIAL}"
-    echo -e "${y}Switching to root${NC}"
-    adb root
-    adb wait-for-device remount
-
-    echo -e "${y}Uninstalling old apk from device${NC}"
-    adb uninstall ${APP_PACKAGE_NAME}
-    adb shell rm -r /system/priv-app/${APP_NAME}.apk
-
-    echo -e "${lb}Installing apk to device${NC}"
-    cd ${APK_ROOT}
-    #exec adb install $APP_NAME.apk "installing apk to device"
-    #exec adb push $APP_NAME.apk /system/priv-app "installing apk to previliged dir"
-    echo -e "installing apk to previliged dir"
-    adb install -r ${APP_NAME}.apk
-  fi
-done
-}
-
-DO_BUILD=1
-DO_FLASH=1
-SELECT_SERIAL=0
-
-if [ $# -ne 0 ] ; then
-  DO_BUILD=0
-  DO_FLASH=0
-  while getopts "bfs:" ARG
-  do
-    case ${ARG} in
-      b) DO_BUILD=1 && echo "Build it we will.";;
-      f) DO_FLASH=1 && echo "Flash it we must.";;
-      s) SELECT_SERIAL=${OPTARG} && echo "flash serial number: ${SELECT_SERIAL}";;
-      ?) echo "Invalid Argument ${ARG}" && exit 1;;
-    esac
-  done
-fi
-
-if [ ${DO_BUILD} -eq "1" ] ; then
-  sl4a_build
-fi
-
-if [ ${DO_FLASH} -eq "1" ] ; then
-  sl4a_flash
-fi
-
-echo "All clear!"
-echo -e " ${r}U${brn}N${y}I${g}C${cy}O${lb}R${p}N ${r}P${brn}O${y}W${g}E${cy}R${lb}!${p}!${NC}"
-