#!/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 identifier
# $2: ARCHIVE_PATH path to the /e/ archive to flash
# $3: ADB_FOLDER_PATH: the path where runnable adb is stored

# Exit status
# - 0 : /e/ installed
# - 1 : Problems occurred (adb returns only 1 if an error occurs)
# - 2 : Problems occurred during file transfer
# - 3 : Problems occurred /e/ installation
# - 101 : DEVICE_ID missing
# - 102 : ARCHIVE_PATH missing

DEVICE_ID=$1
ARCHIVE_PATH=$2
ARCHIVE_NAME=$(basename "$2")
ADB_FOLDER_PATH=$3
ADB_PATH=${ADB_FOLDER_PATH}"adb"


echo "adb path : $ADB_PATH"
if [ -z "$DEVICE_ID" ]
then
  exit 101
fi

if [ -z "$ARCHIVE_PATH" ]
then
  exit 102
fi

sleep 10

"$ADB_PATH" -s "$DEVICE_ID" shell "twrp wipe system" ;

echo "system wiped"

sleep 10

"$ADB_PATH" -s "$DEVICE_ID" shell "twrp wipe cache" ;

echo "cache wiped"

sleep 10
"$ADB_PATH" -s "$DEVICE_ID" shell "twrp wipe data" ;

echo "data wiped"

sleep 10


if ! "$ADB_PATH" -s "$DEVICE_ID" push "$ARCHIVE_PATH" /sdcard ; 
then exit 2 ; fi

if ! "$ADB_PATH" -s "$DEVICE_ID" shell twrp install /sdcard/"$ARCHIVE_NAME" ; 
then exit 3 ; fi

sleep 1

"$ADB_PATH" -s "$DEVICE_ID" shell rm /sdcard/"$ARCHIVE_NAME" ;

sleep 1
