#!/bin/bash

# Copyright (C) 2020-2022 ECORP SAS - Author: Vincent Bourgmayer, 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: ADB_FOLDER_PATH: the path where runnable adb is stored
# $2: The archive folder path
# $3: THe model of the device

# Exit status
# - 0 : success
# - 1 : Error
# - 101 : no device found in fastboot
# - 102 : locking the bootloader failed

FASTBOOT_FOLDER_PATH=$1
FASTBOOT_PATH=${FASTBOOT_FOLDER_PATH}"fastboot"

echo "fastboot path: $FASTBOOT_PATH"

ARCHIVE_PATH=$2
ARCHIVE_FOLDER_PATH=$(dirname "$2")"/"

echo "Archive Path="$ARCHIVE_FOLDER_PATH

device_model=$3

echo "Model="$device_model

SECURITY_PATCH=${ARCHIVE_FOLDER_PATH}""${device_model}"-security-patch"
ORIGINAL_SECURITY_PATCH=$(cat "$SECURITY_PATCH")
MURENA_ROM_INFO=${ARCHIVE_FOLDER_PATH}""${device_model}"-rom-info"
MURENA__SECURITY_PATCH=`sed -n 's/^ro.build.version.security_patch=//p' $MURENA_ROM_INFO`
echo "MURENA__SECURITY_PATCH=$MURENA__SECURITY_PATCH"

# Assuming format is xxxx-yy-zz with otional extra info ..
function versionToInt { printf "%03d%03d%03d%03d" $(echo "$1" | tr '-' ' '); }

I_ORIGINAL_SECURITY_PATCH=$(versionToInt "$ORIGINAL_SECURITY_PATCH")
I_MURENA__SECURITY_PATCH=$(versionToInt $MURENA__SECURITY_PATCH)

if [[ "$I_ORIGINAL_SECURITY_PATCH" -lt "1" ]]
then
    echo "ORIGINAL ROM INFO NOT AVAILABLE => DO NOT PROCESS"
    exit 0
elif [[ $I_MURENA__SECURITY_PATCH -ge $I_ORIGINAL_SECURITY_PATCH ]]
then
    echo "GREATER OR EQUALS => PROCESS"
else
    echo "LOWER => DO NOT PROCESS"
    exit 0
fi

#1 On check that device is in recovery mode
if ! "$FASTBOOT_PATH" devices 2>&1 | grep "fastboot"
then
	echo "Device not detected in fastboot"
	exit 101
fi

# Lock the bootloader
if ! "$FASTBOOT_PATH" flashing lock
then
	exit 102
fi

sleep 10
