#!/bin/sh
#supports_backup in PINN

set -ex
set +f

# shellcheck disable=SC2154
if [ -z "$part1" ] || [ -z "$part2" ]; then
  printf "Error: missing environment variable part1 or part2\n" 1>&2
  exit 1
fi

mkdir -p /tmp/1 /tmp/2

mount "$part1" /tmp/1
mount "$part2" /tmp/2

#-----------------------------
fixup()
{
    #Check for p5 on NVME drives as well to prevent partition resize.
    #$1 = initramfs filename

    #Dont do anything if PINN <3.9.5 which doesnt have zstd
    if ! command -v zstd >/dev/null 2>&1
    then
        return
    fi

    for f in $@
    do
        if [ -e /tmp/1/$f ]; then #file exists!

            #move from boot to root partition for temporary space
            mv /tmp/1/$f /tmp/2/ramdisk.cpio.zst
            cd /tmp/2
            zstd -d ramdisk.cpio.zst
            rm ramdisk.cpio.zst
            mkdir -p /tmp/2/tmp
            cd /tmp/2/tmp
            cpio -i -F ../ramdisk.cpio

            sed -i 's|^\(if ! \[ -b "${ROOT_DEV}5" ]\)|\1 \&\& ! [ -b "${ROOT_DEV}p5" ]|' scripts/local-premount/firstboot

            cpio -i -t -F ../ramdisk.cpio | cpio -o -H newc >../ramdisk_new.cpio
            cd ..
            rm ramdisk.cpio
            mv ramdisk_new.cpio ramdisk.cpio
            zstd ramdisk.cpio
            mv ramdisk.cpio.zst /tmp/1/$f
	    rm ramdisk.cpio
            rm -rf /tmp/2/tmp
        fi
    done
}
#-----------------------------

sed /tmp/1/cmdline.txt -i -e "s|root=[^ ]*|root=${part2}|"
sed /tmp/2/etc/fstab -i -e "s|^[^#].* / |${part2}  / |"
sed /tmp/2/etc/fstab -i -e "s|^[^#].* /boot|${part1}  /boot|"

# shellcheck disable=SC2154
if [ -z "$restore" ]; then
  if [ -f /mnt/ssh ]; then
    cp /mnt/ssh /tmp/1/
  fi

  if [ -f /mnt/ssh.txt ]; then
    cp /mnt/ssh.txt /tmp/1/
  fi

  if [ -f /settings/wpa_supplicant.conf ]; then
    cp /settings/wpa_supplicant.conf /tmp/1/
  fi

  if ! grep -q resize /proc/cmdline; then
    if ! grep -q splash /tmp/1/cmdline.txt; then
      sed -i "s| quiet||g" /tmp/1/cmdline.txt
    fi
    sed -i 's| init=/usr/lib/raspi-config/init_resize.sh||' /tmp/1/cmdline.txt
  else
    sed -i '1 s|.*|& sdhci.debug_quirks2=4|' /tmp/1/cmdline.txt
  fi

fi

cd /tmp/1
fixup "initramfs*"
cd /tmp

umount /tmp/1
umount /tmp/2
