#!/bin/bash

# Copyright (C) 2022 - Author: Frank
#
# 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 : Fastboot functionnal
# - 101 : ARCHIVE_PATH missing

# Context 
#  On MacOS Fastboot starts not to work anymore (in case of fFP4 precisely during the flash of the partitions (it is systematic) 
#  Fastboot is locked and returns < waiting for any device > whereas some time before it still worked)
#  The only remedy I found to continue the process is to restart in recovery from the recovery menu. 
#  This script is a trigger to perform this action 

ARCHIVE_PATH=$1
ARCHIVE_FOLDER_PATH=$(dirname "$1")"/"
FASTBOOT_FOLDER_PATH=$2
FASTBOOT_PATH=${FASTBOOT_FOLDER_PATH}"fastboot"

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

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

cd "$ARCHIVE_FOLDER_PATH"

if [[ $OSTYPE == 'darwin'* ]]; then
    CHECK_FASTBOOT=1
    while [ $CHECK_FASTBOOT = 1 ]
    do
        echo "CHECK..."
        ("$FASTBOOT_PATH" flashing get_unlock_ability) & pid=$!
        ( sleep 10 && kill -HUP $pid ) 2>/dev/null & watcher=$!
        if wait $pid 2>/dev/null; then
            echo "fastboot works finished"
            pkill -HUP -P $watcher
            wait $watcher
            CHECK_FASTBOOT=0
        else
            (killall -9 fastboot) &  
            echo "fastboot failed"
            CHECK_FASTBOOT=1
            sleep 10
        fi
    done
fi

exit 0


