#!/bin/bash

# Copyright (C) 2019 ECORP SAS - Author: Romain Hunault
# Copyright (C) 2020 ECORP SAS - Author: Vincent Bourgmayer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# Parameter
# $1: DEVICE_ID Device we are waiting for reboot
# $2: ADB_FOLDER_PATH: the path where runnable adb is stored

# Exit status
# - 0 : success
# - 1 : Error
# - 10 : DEVICE_ID is missing
# - 101 : device with DEVICE_ID is not detected

DEVICE_ID=$1
ADB_FOLDER_PATH=$2

ADB_PATH=${ADB_FOLDER_PATH}"adb"

echo "ADB path: $ADB_PATH"

if [ -z "$DEVICE_ID" ]
then
  exit 10
fi


#1 On check that device is in recovery mode
if ! "$ADB_PATH" -s "$DEVICE_ID" get-state 2>&1 | grep "recovery"
then
	echo "Device not detected in recovery"
	exit 101
fi

#Then we wait that it left this state
while "$ADB_PATH" -s "$DEVICE_ID" get-state 2> /dev/null
do
	sleep 1
done
