#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2024-present ROCKNIX (https://github.com/ROCKNIX)
# Fedora-adapted: defaults HW_DEVICE/SYSTEM_ROOT for distros that don't ship the
# ROCKNIX-flavoured os-release.
#
# Flashes /usr/share/bootloader/rocknix_abl/abl_signed-${HW_DEVICE}.elf to both
# abl_a and abl_b on the internal eMMC/UFS, but only when the SHA-256 differs.

[ -r /etc/os-release ] && . /etc/os-release

: "${SYSTEM_ROOT:=}"
: "${HW_DEVICE:=SM8550}"

case "$HW_DEVICE" in
  SM6115|SM8250|SM8550|SM8650) ;;
  *)
    echo "updateabl: HW_DEVICE='$HW_DEVICE' is not a ROCKNIX-supported Qualcomm platform" >&2
    exit 1
    ;;
esac

ELF="${SYSTEM_ROOT}/usr/share/bootloader/rocknix_abl/abl_signed-${HW_DEVICE}.elf"
TMP_ABL_A="$(mktemp)"
TMP_ABL_B="$(mktemp)"
trap 'rm -f "$TMP_ABL_A" "$TMP_ABL_B"' EXIT

if [ ! -f "${ELF}" ]; then
  echo "updateabl: ABL image not found at ${ELF}" >&2
  exit 1
fi

ABL_A="$(/usr/sbin/blkid -t PARTLABEL=abl_a -o device)"
ABL_B="$(/usr/sbin/blkid -t PARTLABEL=abl_b -o device)"
if [ ! -b "${ABL_A}" ] || [ ! -b "${ABL_B}" ]; then
  echo "updateabl: abl_a/abl_b partitions not visible — are you running on the device?" >&2
  exit 1
fi

SS="$(/usr/sbin/blockdev --getss "${ABL_A}")"
[ -z "${SS}" ] && { echo "updateabl: failed to get sector size" >&2; exit 1; }

ELF_SIZE=$(/usr/bin/stat -c%s "${ELF}")
COUNT=$(( (ELF_SIZE + SS - 1) / SS ))

echo "Reading ${COUNT} sectors from ${ABL_A}..."
dd if="${ABL_A}" of="${TMP_ABL_A}" bs="${SS}" count="${COUNT}" status=none

echo "Reading ${COUNT} sectors from ${ABL_B}..."
dd if="${ABL_B}" of="${TMP_ABL_B}" bs="${SS}" count="${COUNT}" status=none

SUM_A="$(/usr/bin/sha256sum "${TMP_ABL_A}" | awk '{print $1}')"
SUM_B="$(/usr/bin/sha256sum "${TMP_ABL_B}" | awk '{print $1}')"
SUM_UPDATE="$(/usr/bin/sha256sum "${ELF}"  | awk '{print $1}')"

echo "Checksum abl_a:  ${SUM_A}"
echo "Checksum abl_b:  ${SUM_B}"
echo "Checksum update: ${SUM_UPDATE}"

if [ "${SUM_A}" = "${SUM_UPDATE}" ] && [ "${SUM_B}" = "${SUM_UPDATE}" ]; then
    echo "ABL_A and ABL_B already match the shipped ABL — nothing to do."
    exit 0
fi

echo "Flashing ${ELF} -> ${ABL_A}, ${ABL_B}..."
dd if="${ELF}" of="${ABL_A}" bs="${SS}" conv=fsync,notrunc status=none
dd if="${ELF}" of="${ABL_B}" bs="${SS}" conv=fsync,notrunc status=none
sync

echo "ABL update completed."
