From 472ca6fb301fd9744c9729482221978bc42a4ce8 Mon Sep 17 00:00:00 2001
From: Sergii Dmytruk <sergii.dmytruk@3mdeb.com>
Date: Sun, 6 Nov 2022 00:13:05 +0200
Subject: [PATCH] flash-gui.sh: accept tgz package for Talos boards

Signed-off-by: Sergii Dmytruk <sergii.dmytruk@3mdeb.com>
---
 initrd/bin/flash-gui.sh |  4 ++--
 initrd/bin/flash.sh     | 35 ++++++++++++++++++++++++++++++++++-
 2 files changed, 36 insertions(+), 3 deletions(-)

diff --git a/initrd/bin/flash-gui.sh b/initrd/bin/flash-gui.sh
index 366e7969..dcf04373 100755
--- a/initrd/bin/flash-gui.sh
+++ b/initrd/bin/flash-gui.sh
@@ -22,10 +22,10 @@ while true; do
     ;;
     f|c )
       if (whiptail $BG_COLOR_WARNING --title 'Flash the BIOS with a new ROM' \
-          --yesno "You will need to insert a USB drive containing your BIOS image (*.rom).\n\nAfter you select this file, this program will reflash your BIOS.\n\nDo you want to proceed?" 0 80) then
+          --yesno "You will need to insert a USB drive containing your BIOS image (*.rom or *.tgz).\n\nAfter you select this file, this program will reflash your BIOS.\n\nDo you want to proceed?" 0 80) then
         mount_usb
         if grep -q /media /proc/mounts ; then
-          find /media ! -path '*/\.*' -type f -name '*.rom' | sort > /tmp/filelist.txt
+          find /media ! -path '*/\.*' -type f \( -name '*.rom' -o -name '*.tgz' \) | sort > /tmp/filelist.txt
           file_selector "/tmp/filelist.txt" "Choose the ROM to flash"
           if [ "$FILE" == "" ]; then
             return
diff --git a/initrd/bin/flash.sh b/initrd/bin/flash.sh
index 70d927f3..cc2ac031 100755
--- a/initrd/bin/flash.sh
+++ b/initrd/bin/flash.sh
@@ -159,8 +159,41 @@ else
 fi
 
 if [ ! -e "$ROM" ]; then
-	die "Usage: $0 [-c|-r] <path_to_image.rom>"
+    die "Usage: $0 [-c|-r] <path/to/image.(rom|tgz)>"
+fi
+
+if [ "$READ" -eq 0 ] && [ "${ROM##*.}" = tgz ]; then
+    if [ "${CONFIG_BOARD%_*}" = talos-2 ]; then
+        rm -rf /tmp/verified_rom
+        mkdir /tmp/verified_rom
+
+        tar -C /tmp/verified_rom -xf $ROM
+        if ! (cd /tmp/verified_rom/ && sha256sum -cs hashes.txt); then
+            die "Provided tgz image did not pass hash verification"
+        fi
+
+        echo "Reading current flash and building an update image"
+        flashrom $CONFIG_FLASHROM_OPTIONS -r /tmp/flash.sh.bak \
+            || die "Read of flash has failed"
+
+        # ROM and bootblock already have ECC
+        bootblock=$(echo /tmp/verified_rom/*.bootblock)
+        rom=$(echo /tmp/verified_rom/*.rom)
+        kernel=$(echo /tmp/verified_rom/*-zImage.bundled)
+        pnor /tmp/flash.sh.bak -aw HBB < $bootblock
+        pnor /tmp/flash.sh.bak -aw HBI < $rom
+        pnor /tmp/flash.sh.bak -aw BOOTKERNEL < $kernel
+        rm -rf /tmp/verified_rom
+
+        ROM=/tmp/flash.sh.bak
+    else
+        die "$CONFIG_BOARD doesn't support tgz image format"
+    fi
 fi
 
 flash_rom $ROM
+
+# don't leave temporary files lying around
+rm -f /tmp/flash.sh.bak
+
 exit 0