# We don't want to install SCT during release tarball generation and while in
# chroot or containers.
if systemd-detect-virt -qrc ; then
    echo $"-- Running in container or chroot; Skipping the installation."
    exit 0
fi

if [ ! -e /sys/firmware/efi ] ; then
    echo "The system is not booted with EFI, skipping."
    exit 0
fi

# Define the source and target paths for the program
PROGRAM_SOURCE="/usr/share/SctPackage"
PROGRAM_TARGET_DIR="EFI/"
PROGRAM_TARGET=""

# List all mounted vfat partitions and check for /efi or /boot/efi
MOUNT_POINTS=$(findmnt -rno TARGET -t vfat)

for MOUNT_POINT in $MOUNT_POINTS; do
    if [[ "$MOUNT_POINT" == "/efi" || "$MOUNT_POINT" == "/boot/efi" ]]; then
        PROGRAM_TARGET="$MOUNT_POINT/$PROGRAM_TARGET_DIR"
        break
    fi
done

# If no suitable mount point is found, output an error and exit
if [ -z "$PROGRAM_TARGET" ]; then
    echo "Warning: Could not find a mounted EFI System Partition."
    exit 0
fi

# Create the target directory if it doesn't exist
mkdir -pv $(dirname "$PROGRAM_TARGET")

# Copy the program files to the target directory
echo "Copying SctPackage to $PROGRAM_TARGET..."
cp -rf "$PROGRAM_SOURCE" "$PROGRAM_TARGET"

# Success message
echo "Program successfully installed to $PROGRAM_TARGET/SctPackage"
