#!/bin/bash

# Copyright (C) 2022 ECORP SAS - Author: Frank Preel
#
# 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 id
# $2: ARCHIVE_PATH path to archive
# $3: fastboot folder path


# Exit status
# - 0 : device flashed
# - 1 : generic error

DEVICE_ID=$1
ARCHIVE_FILE=$2
FASTBOOT_FOLDER_PATH=$3

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

# check path to rom has been provided
if [ -z "$ARCHIVE_FILE" ]
then
  exit 102
fi

#check path to adb/fasboot has been provided
if [ -z "$FASTBOOT_FOLDER_PATH" ]
then
  exit 103
fi

# Build fastboot and adb commands
ADB_CMD=${FASTBOOT_FOLDER_PATH}"adb"

# Some devices require adb usb command to switch to sideload mode
"$ADB_CMD" usb
sleep 5
"$ADB_CMD" sideload ${ARCHIVE_FILE}
ret=${?}

echo "adb sideload retuns = "${ret}
# ret = 0 if adb command is fine, 1 on error

if [ ${ret} -lt 2 ]
then
    echo "handle  adb: failed to read command: Success."
    exit 0
fi

exit ${ret}
