#!/bin/bash
# Copyright 2014 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; version 2.1.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Zoltán Balogh <zoltan.balogh@canonical.com>

set -e

SCRIPTPATH=`dirname $0`
EMULATOR_NAME=$1

# wait for the emulator process to come up
until pid=$(${SCRIPTPATH}/local_emulator_pid ${EMULATOR_NAME}); 
do
        sleep 0.1;
done;

# wait for the emulator to assign the port
until port=$(netstat -anp 2>&1|grep tcp|grep ${pid}|head -1|awk '{print $4}'|sed -n  's/.*\:\([0-9]*$\)/\1/p'|egrep -v "^$")
do
        sleep 0.1;
done;

# disable the setup wizard for the emulator, so it can boot straight to the shell
set +e
adb -s emulator-${port} wait-for-device
phablet-config -s emulator-${port} welcome-wizard --disable|grep -v "already disabled"
set -e

# return the serial number the adb will use for that emulator
echo "emulator-${port}"

