#!/bin/bash

# Copyright (C) 2020 - Author: Ingo
#
# 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: ARCHIVE_PATH path to the /e/ archive to flash
# $2: FASTBOOT_FOLDER_PATH: the path where runnable fastboot is stored
# $3: JAVA_FOLDER_PATH: the path where runnable jar is stored (to unpack ZIP file)

# Exit status
# - 0 : /e/ installed
# - 1 : user data wipe failed
# - 2 : flashing of a partition failed
# - 101 : ARCHIVE_PATH missing
# - 102 : archive could not be unpacked

ARCHIVE_PATH=$1
ARCHIVE_FOLDER_PATH=$(dirname "$1")"/"
FASTBOOT_FOLDER_PATH=$2
FASTBOOT_PATH=${FASTBOOT_FOLDER_PATH}"fastboot"
JAVA_FOLDER_PATH=$3
JAR_PATH=${JAVA_FOLDER_PATH}"/bin/jar"

echo "archive path : $ARCHIVE_PATH"
echo "archive folder path : $ARCHIVE_FOLDER_PATH"
echo "fastboot path : $FASTBOOT_PATH"
echo "jar path : $JAR_PATH"

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

cd "$ARCHIVE_FOLDER_PATH"

sleep 1

if ! "$JAR_PATH" -x -v -f "$ARCHIVE_PATH" ;
then exit 102 ; fi

echo "unpacked archive"

sleep 1

if ! "$FASTBOOT_PATH" -w ;
then exit 1 ; fi

echo "user data wiped"

sleep 5

echo "=== Flash slot A"

if ! "$FASTBOOT_PATH" flash system_a system.img -S 522239K ;
then exit 2 ; fi

echo "flashed system"

sleep 1

if ! "$FASTBOOT_PATH" flash boot_a boot.img ;
then exit 2 ; fi

echo "flashed boot"

sleep 1

if ! "$FASTBOOT_PATH" flash vendor_a vendor.img -S 522239K ;
then exit 2 ; fi

echo "flashed vendor"

sleep 1

if ! "$FASTBOOT_PATH" flash dtbo_a dtbo.img ;
then exit 2 ; fi

echo "flashed dtbo"

sleep 1

if ! "$FASTBOOT_PATH" flash vbmeta_a vbmeta.img ;
then exit 2 ; fi

echo "flashed vbmeta"

echo "=== Flash slot B"

if ! "$FASTBOOT_PATH" flash system_b system.img -S 522239K ;
then exit 2 ; fi

echo "flashed system"

sleep 1

if ! "$FASTBOOT_PATH" flash boot_b boot.img ;
then exit 2 ; fi

echo "flashed boot"

sleep 1

if ! "$FASTBOOT_PATH" flash vendor_b vendor.img -S 522239K ;
then exit 2 ; fi

echo "flashed vendor"

sleep 1

if ! "$FASTBOOT_PATH" flash dtbo_b dtbo.img ;
then exit 2 ; fi

echo "flashed dtbo"

sleep 1

if ! "$FASTBOOT_PATH" flash vbmeta_b vbmeta.img ;
then exit 2 ; fi

echo "flashed vbmeta"

sleep 1
