#!/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
# $2: fastboot folder path

# Exit status
# - 0 : bootloader locked
# - 1 : unknown error
# - 2 : Flashing unlocked failed
# - 101 : $DEVICE_ID missing
# - 102 : $FASTBOOT_FOLDER_PATH is missing

DEVICE_ID=$1
FASTBOOT_FOLDER_PATH=$2

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

# Check fastboot parent folder path has been provided
if [ -z "$FASTBOOT_FOLDER_PATH" ]
then
  exit 102
fi

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

if [ "$($FASTBOOT_PATH getvar unlocked 2>&1 | grep -q yes; echo $?)" = 1 ]
then 
  # Unlock bootloader
  if ! "$FASTBOOT_PATH" -s "$DEVICE_ID" oem unlock
  then
    exit 2
  fi
else
  sleep 30
  # Already unlocked use the same way
  "$FASTBOOT_PATH" -s "$DEVICE_ID" reboot
  exit 0
fi

while [ "$($FASTBOOT_PATH getvar unlocked 2>&1 | grep -q yes; echo $?)" = 1 ]
do
  echo "locked"
  sleep 1
done

echo "unlock.."
sleep 1
