#!/bin/sh
# Install as /usr/local/sbin/plx-ventoy-firstboot (mode 755) in the PendriveLinux OS image.
#
# Run very early at boot (see plx-ventoy-firstboot.service). If this system's root is on a
# Ventoy drive - which is the case when UUI-Py copied the OS into a partition after Ventoy's
# (the Windows copy can't edit files inside the system, so the system does it itself) - it makes
# PendriveLinux's own disk tools stand down: no grub-install onto an EFI partition, no root
# growing, no first-boot disk setup, no "host" unit that would unmount the root at shutdown.
STATE=/var/lib/plx

[ -e "$STATE/vtoy-mode" ] && exit 0

on_ventoy=0
# 1. UUI-Py's menu entries pass plx.ventoy=1 on the kernel command line.
grep -qw 'plx.ventoy=1' /proc/cmdline && on_ventoy=1
# 2. Otherwise: is there a VTOYEFI partition on the same disk as the root filesystem?
if [ "$on_ventoy" = 0 ]; then
    src=$(findmnt -no SOURCE / 2>/dev/null)
    disk=$(lsblk -no PKNAME "$src" 2>/dev/null | head -n1)
    if [ -n "$disk" ] && lsblk -nro LABEL "/dev/$disk" 2>/dev/null | grep -qx VTOYEFI; then
        on_ventoy=1
    fi
fi
[ "$on_ventoy" = 1 ] || exit 0

mkdir -p "$STATE" /etc/systemd/system
: > "$STATE/vtoy-mode"
echo "root partition on a Ventoy drive (set up at boot by plx-ventoy-firstboot)" > "$STATE/ventoy-extracted"
rm -f "$STATE/disk-setup-pending"
ln -sf /dev/null /etc/systemd/system/plx-vtoy-host.service
if [ -f /etc/fstab ]; then
    sed -i 's|^\(LABEL=PLX-EFI[[:space:]].*\)$|# no EFI system partition on a Ventoy drive: \1|' /etc/fstab
fi
systemctl daemon-reload 2>/dev/null || true
exit 0
