#!/bin/bash
# Author: Steven Shiau <steven _at_ clonezilla org>
# License: GPL
# Description: This program generates nic-firmware.lst inside a chroot for Clonezilla
# This file contains code generated by Gemini, created by Google.

DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"
. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

# Settings
OUTPUT_f="nic-firmware.lst"
out_d_def="/tmp"
out_d="$1"

[ -z "$out_d" ] && out_d=$out_d_def
OUTPUT="$out_d/nic-firmware.lst"

# 1. Find the kernel version installed in the chroot.
# We look for the directory in /lib/modules/ that contains the most files.
# This avoids empty directories or partial installs.
KVER=$(ls -1 /lib/modules | sort -V | tail -n 1)

if [ -z "$KVER" ]; then
    echo "Error: No kernel modules found in /lib/modules. Is a kernel installed?"
    exit 1
fi

MOD_PATH="/lib/modules/$KVER/kernel/drivers/net/"

echo "Detected kernel version in chroot: $KVER"

# 2. Start the list
echo "# Automatically generated NIC firmware list for Clonezilla" > "$OUTPUT"
echo "# Source Kernel: $KVER" >> "$OUTPUT"
echo "# Generated on: $(date)" >> "$OUTPUT"

# 3. Scan the network driver modules
# We look for .ko (regular) or .ko.xz / .ko.zst (compressed) files
if [ -d "$MOD_PATH" ]; then
    find "$MOD_PATH" -type f \( -name "*.ko" -o -name "*.ko.*" \) -exec modinfo -F firmware {} + \
    | sort -u >> "$OUTPUT"
    
    # Remove any empty lines or duplicates
    sed -i '/^$/d' "$OUTPUT"
    
    echo "Successfully updated $OUTPUT with $(grep -v '^#' "$OUTPUT" | wc -l) firmware entries."
else
    echo "Error: Network driver path $MOD_PATH not found."
    exit 1
fi
