#!/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/>.

# TODO: test if a device go from "sideload" mode to recovery

# Parameter
# $1: DEVICE_ID ID of the device to wait
# $2: ADB_FOLDER_PATH: the path where runnable adb is stored

# Exit status
# - 0 : success
# - 1 : twrp mount system failed
# - 101 : DEVICE_ID missing
# - 102 : adb wait recovery failed

DEVICE_ID=$1
ADB_FOLDER_PATH=$2
ADB_PATH=""

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

ADB_PATH=${ADB_FOLDER_PATH}"adb"

echo "waiting for recovery"
if "$ADB_PATH" -s "$DEVICE_ID" wait-for-recovery
then
    echo "device found in recovery"
    if ! "$ADB_PATH" -s "$DEVICE_ID" shell "twrp mount system" ;
    then
        echo "twrp mount system failed"
        exit 1
    fi
else
    echo "device not detected in recovery"
    exit 102
fi
