#!/bin/bash

# Get this by:
#    aapt dump xmltree foo.apk AndroidManifest.xml
# component=jp.bio100.android.superdepth/.SuperDepth
# component=com.johnemulators.johnneslite/.MainActivity
# component=com.facebook.katana:nodex/.LoginActivity
# component=com.facebook.katana:dash/com.facebook.dash.activities.DashActivity
# component=com.example.dragon/.MainActivity
# component=net.mandaria.tippytipper/net.mandaria.tippytipperlibrary.activities.TippyTipper
component=com.google.earth/.EarthActivity
# component=com.android.deskclock/.DeskClock
# component=com.instagram.android/.activity.MainTabActivity

proc_name=${component%%/*}
component=${proc_name%:*}/${component##*/}

echo "Waiting for the device..."
adb wait-for-device

# Make sure the screen is on.
adb shell dumpsys power | grep "mScreenOn=true" \
    | xargs -0 test -z && adb shell input keyevent 26 && adb shell input keyevent 82

# Start the app by sending an explicit intent.
adb shell am start -S -n $component -D

# Port forward.
jdwp_pid=`adb shell ps | awk '$9 == "'$proc_name'\r" { print $2 }'`
if [[ -z "$jdwp_pid" ]]; then
    echo "Error: failed to find the PID"
    exit 1
fi
echo "jdwp_pid: $jdwp_pid"
adb forward --remove-all && adb -d forward tcp:6100 jdwp:$jdwp_pid

# Start Jitana in the background.
# rm -rf output/insn/*.dot
mkdir -p output/insn

if [[ "$1" == "monkey" ]]; then
    ./jitana-travis &
    jitana_pid=$!

    sleep 5

    # Start Monkey.
    echo "=== Monky: started ============================"
    time adb shell monkey -p ${component%%/*} 3000
    echo "=== Monky: stopped ============================"

    # Kill Jitana.
    echo "Killing Jitana in 5 seconds..."
    sleep 5
    kill -INT $jitana_pid
    wait
    echo "Done."
else
    ./jitana-travis
fi