#!/bin/bash

# Copyright (C) 2021 - 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: What if 2 devices detected?
# Parameter
# $1: serial number of the device
# $2: The folder where fastboot runnable is stored

# Exit status
# - 0 : Device in fastboot mode detected
# - 1 : unknown Error
# - 10: rebooting in bootloader failed
# - 101: Device ID not provided
# - 102: Missing path to adb and fastboot

DEVICE_ID=$1
ADBFASTBOOT_FOLDER_PATH=$2

# Check DEVICE ID has been provided
if [ -z "$DEVICE_ID" ]
then
  exit 101
fi

# Check adb and fastboot parent path has been provided
if [ -z "$ADBFASTBOOT_FOLDER_PATH" ]
then
  exit 102
fi

# Construct path to ADB and FASTBOOT
FASTBOOT_PATH=${ADBFASTBOOT_FOLDER_PATH}"fastboot"
ADB_PATH=${ADBFASTBOOT_FOLDER_PATH}"adb"

# reboot device in bootloader mode
if ! "$ADB_PATH" -s "$DEVICE_ID" reboot bootloader
then 
  exit 10;
fi

# Wait device to reboot in fastboot mode
while [ "$($FASTBOOT_PATH devices | grep -q fastboot; echo $?)" = 1 ]
do
  sleep 3
done
#TODO: we should handle the case where this doesn't work

sleep 5
echo "fastboot mode detected"