#!/sbin/sh
# Xiaomi Firmware Updater Backend
# by yshalsager
# Based on TWRP A/B Installer Backend
# by osm0sis, Dees_Troy and topjohnwu

OUTFD=/proc/self/fd/$2
ZIPFILE="$3"

ui_print() { $BOOTMODE && echo "$1" || echo -e "ui_print $1\nui_print" >> "$OUTFD"; }
abort() { ui_print "$1"; exit 1; }

ui_print "####################################################"
ui_print "# Generated by Xiaomi Flashable Firmware Creator"
ui_print "# [-]datetime - [-]host"
ui_print "####################################################"
ui_print " "

# Check the activate slot and set suffixes
if [ "$(getprop ro.boot.slot_suffix)" = "_a" ]
then
  currentSlot="a"
#  inactiveSlot="b"
else
  currentSlot="b"
#  inactiveSlot="a"
fi

# Check if the active slot variable is set
[ -z "$currentSlot" ] && echo abort "[ERROR] Unable to detect activate slot! Aborting."

# /dev/tmp is safe for firmware installs
tmp=/dev/tmp/fw-install
backupDir=/sdcard/XFU/$currentSlot

# Extract firmware files
ui_print "[INFO] Unpacking firmware files...";
ui_print " "
rm -rf $tmp
mkdir -p $tmp
unzip -o "$ZIPFILE" -d $tmp || abort "[ERROR] Failed to extract zip! Check recovery logs."

# Create backup folder
rm -rf $backupDir
mkdir -p $backupDir

# Flash files
for firmwareFile in "$tmp"/*.img; do
  partitionFileName=${firmwareFile##*/}
  partitionName=${partitionFileName%.*}
  ui_print "[INFO] Making a backup of $partitionName\_$currentSlot..."
  dd if=/dev/block/bootdevice/by-name/"$partitionName"_$currentSlot of=$backupDir/"$partitionFileName"
  ui_print "[INFO] Flashing $partitionName on slot $currentSlot..."
  dd if="$firmwareFile" of=/dev/block/bootdevice/by-name/"$partitionName"_$currentSlot || abort "[ERROR] Unable to flash $partitionName! Aborting."
done;

# Cleanup
ui_print "[INFO] Cleaning up..."
cd /
rm -rf /dev/tmp/fw-install
ui_print "[INFO] Firmware has been successfully updated!"