#!/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
# $4: Java folder path


# Exit status
# - 0 : device flashed
# - 1 : generic error
# - 10: can't unpack system.img
# - 11: can't wipe userdata
# - 12: can't wipe metadata
# - 13: can't active partition
# - 20-34 : see partition_name index below
# - 101 : DEVICE_ID missing
# - 102 : ARCHIVE_PATH missing
# - 103 : fastboot folder path missing

partition_name=(boot_a dtbo_a vbmeta_a vbmeta_system_a vbmeta_vendor_a super lk_a logo preloader_a tee_a gz_a sspm_a scp_a spmfw_a md1img_a)
partition_image=(boot.img dtbo.img vbmeta.img vbmeta_system.img vbmeta_vendor.img super.img lk.img logo.bin preloader_emerald.bin tee.img gz.img sspm.img scp.img spmfw.img md1img.img)
partition_error=(20 21 22 23 24 25 26 27 28 29 30 31 32 33 34)

DEVICE_ID=$1
ARCHIVE_PATH=$2
FASTBOOT_FOLDER_PATH=$3
JAVA_FOLDER_PATH=$4

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

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

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

# Check java folder has been provided
if [ -z "$JAVA_FOLDER_PATH" ]
then
  exit 104
fi

# Build fastboot path
FASTBOOT_PATH=${FASTBOOT_FOLDER_PATH}"fastboot"

# Build java jar path
JAR_PATH=${JAVA_FOLDER_PATH}"/bin/jar"

# Build archive folder path
ARCHIVE_FOLDER_PATH=$(dirname "$ARCHIVE_PATH")"/"

# unzip for system.img
cd "$ARCHIVE_FOLDER_PATH" || exit 104

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

echo "unpacked archive"

sleep 1

# Wipe user data
if ! "$FASTBOOT_PATH" erase userdata ;
then
  exit 11
fi

echo "user data wiped"
sleep 5

#Flash partition
for i in ${!partition_name[@]}; do
  if ! "$FASTBOOT_PATH" -s "$DEVICE_ID" flash ${partition_name[$i]} ${partition_image[$i]}
  then
    exit ${partition_error[$i]}
  fi
  sleep 1
  echo "Flased ${partition_name[$i]}"
done


if ! "$FASTBOOT_PATH" -s "$DEVICE_ID" --set-active=a ;
then
  exit 13
fi
