#!/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/>.

# TODO: What if 2 devices detected?
# Parameter
# $1: The folder where fastboot runnable is stored

# Exit status
# - 0 : Device in fastboot mode detected
# - 1 : Error (adb)
# - 2 : Error (device locked)

# Store ROM information on the file system 

FASTBOOT_FOLDER_PATH=$1
ADB_PATH=${FASTBOOT_FOLDER_PATH}"adb"

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

echo "Archive Path="$ARCHIVE_FOLDER_PATH

device_model=$3

echo "Model="$device_model


if ! "$ADB_PATH" shell getprop ro.build.version.security_patch
then
    exit 1
fi

SECURITY_PATCH=${ARCHIVE_FOLDER_PATH}""${device_model}"-security-patch"
DEVICE_STATE=${ARCHIVE_FOLDER_PATH}""${device_model}"-device-state"
MURENA_ROM_INFO=${ARCHIVE_FOLDER_PATH}""${device_model}"-rom-info"

curl -o $MURENA_ROM_INFO https://images.ecloud.global/stable/FP4/e-latest-FP4.zip.prop

MURENA__SECURITY_PATCH=`sed -n 's/^ro.build.version.security_patch=//p' $MURENA_ROM_INFO`
expr "$MURENA__SECURITY_PATCH" : '\(^[0-9]\{4\}-\(0[1-9]\|1[012]\)-\(0[1-9]\|[12][0-9]\|3[01]\)$\)' && echo "MURENA__SECURITY_PATCH is valid!" || exit 1

echo "MURENA__SECURITY_PATCH=$MURENA__SECURITY_PATCH"

# For FP4 on stock ROM the key [ro.build.flavor] returns [qssi-user].
# On Murena OS: returns [lineage_FP4-userdebug]
# This seems to be the most sane way to assert if we are on stock ROM
echo "" > $SECURITY_PATCH
if "$ADB_PATH" shell getprop ro.build.flavor 2>&1 | grep "qssi-user"
then
	if "$ADB_PATH" shell getprop ro.boot.vbmeta.device_state 2>&1 | grep "unlocked"
	then
		echo "Device is unlocked"
	else
		echo "Device is locked"
		# Device is locked and on stock ROM. The prop will NOT be spoofed and can be trusted.
		# NOTE: In case of an empty result we will skip locking later.
		"$ADB_PATH" shell getprop ro.build.version.security_patch> $SECURITY_PATCH
	fi
fi

exit 0
